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": 4,
"code_window": [
" width?: string\n",
"}\n",
"\n",
"const {\n",
" url,\n",
" socialMedias,\n",
" title = 'NocoDB',\n",
" summary,\n",
" hashTags = '',\n",
" css = '',\n",
" iconClass = '',\n",
" width = '45px',\n",
"} = defineProps<Props>()\n",
"\n",
"const summaryArr = [\n",
" 'Instant #Rest & #GraphQL APIs on any #SQL Database (Supports : MySQL, PostgresSQL, MsSQL, SQLite, MariaDB) #nocodb ',\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
"const { url, socialMedias, title, summary, hashTags, css, iconClass, width } = withDefaults(defineProps<Props>(), {\n",
" title: 'NocoDB',\n",
" hashTags: '',\n",
" css: '',\n",
" iconClass: '',\n",
" width: '45px',\n",
"})\n"
],
"file_path": "packages/nc-gui/components/general/Share.vue",
"type": "replace",
"edit_start_line_idx": 14
} | ---
title: "Column Operations"
description: "Column Operations: Fields, Sort & Filter"
---
## Fields
Click `Fields` to control the visibility of a field.
<img width="1262" alt="image" src="https://user-images.githubusercontent.com/35857179/189098625-8b4930e7-9bb4-4e8f-aa44-d2a28a31abdb.png" />
By default, all system fields will be hid. However, you can tick `Show system fields` to make them visible.
<img width="1268" alt="image" src="https://user-images.githubusercontent.com/35857179/189098684-4fe2ebfc-df00-40fc-8f3c-1d4d14a8fb23.png" />
### Re-order Columns
Column positions can be re-ordered. Open `Fields` menu, and re-order fields as needed by dragging and dropping the `drag icon`.
<img width="358" alt="image" src="https://user-images.githubusercontent.com/35857179/189100445-d1a3816e-ddc0-4830-ba0a-a7b65597d264.png" />
<!-- #### Demo -->
<!-- <img src="https://github.com/dstala/nocodb-files/blob/2c4ca2ff31460ee5636262e88ba303e2d436ba54/ColumnReorder.gif?raw=true" width="100%"/> -- />
<!-- img src="https://media0.giphy.com/media/z5mYR1XoO85Umd5abh/giphy.gif?cid=790b7611f53d7e966bf9de3ae6b1cd5a7d6380b0ab8a4337&rid=giphy.gif&ct=g" width="60%"/ -->
### Hide / Unhide Columns
To hide / unhide columns, open `Fields` menu, tick checkbox to keep the column visible, untick checkbox to remove it from the view.
:::tip
You can create different grid views with different fields shown in each view.
:::
<img width="355" alt="image" src="https://user-images.githubusercontent.com/35857179/189100701-125b529b-5578-43ad-a707-e8c1738e788c.png" />
<!-- #### Demo -->
<!-- <img src="https://github.com/dstala/nocodb-files/blob/2c4ca2ff31460ee5636262e88ba303e2d436ba54/ColumnHide.gif?raw=true" width="100%"/> -- />
<!-- img src="https://media2.giphy.com/media/8NXvWfHDoul72dwLhk/giphy.gif?cid=790b76116fa008b45c79bb91bfe611e324fa38cde21a255a&rid=giphy.gif&ct=g" width="60%"/ -->
## Sort
Sorting allows you to order contents alphabetically (A → Z) / (Z → A) (OR) in ascending / descending order. NocoDB allows nested sorting. You can choose column fields & order in which to apply nested sorting. Lookup, Formula, Nested Data are also supported in Sorting.
<img width="462" alt="image" src="https://user-images.githubusercontent.com/35857179/189100830-29b164a2-dd63-41f9-987a-09de53e0a0ec.png" />
<img width="473" alt="image" src="https://user-images.githubusercontent.com/35857179/189100869-e458814c-ef9b-4d88-8d7c-4e7de0f3b416.png" />
<img width="607" alt="image" src="https://user-images.githubusercontent.com/35857179/189100945-f2575174-f0d2-48e5-8b89-2d14baa873e5.png" />
<!-- #### Demo -->
<!-- <img src="https://github.com/dstala/nocodb-files/blob/2c4ca2ff31460ee5636262e88ba303e2d436ba54/ColumnSort-2.gif?raw=true" width="100%"/> -- />
<!-- img src="https://media4.giphy.com/media/ThQ8d42U2zdFyZGeZe/giphy.gif?cid=790b761183da2eb690295c5c25f83ace7acf5212c82569a1&rid=giphy.gif&ct=g" width="60%"/ -->
## Filter
Filters allow you to restrict / organize your data on the view as per your needs. NocoDB allows nested filters. You can choose multiple columns and conditions to apply filter. Between filters, you can opt for either `and` or `or` mode operation. Lookup, Formula, Nested Data are also supported in Filtering.
<img width="1011" alt="image" src="https://user-images.githubusercontent.com/35857179/189102268-706ba965-e332-4c93-b2d2-ea04f0fabf11.png" />
<img width="1021" alt="image" src="https://user-images.githubusercontent.com/35857179/189102641-bd4f64b1-21fc-42a0-bbe6-2a019e213eda.png" />
You can also group several filters together using Filter Group.
<img width="1025" alt="image" src="https://user-images.githubusercontent.com/35857179/189102932-aa0e31ef-554f-4e8b-ae0e-2024b7f4d35b.png" />
### Enable NULL and EMPTY Filters
NULL filters (`is null` & `is not null`) and EMPTY filters (`is empty` & `is not empty`) are hidden by default. If you wish to filter out either one only, you may enable `Show NULL and EMPTY Filter` in Project Settings.

Otherwise, we can use Blank filters to filter out cells with NULL values and EMPTY values.
### Supported Filters
Currently we support different types of filters for corresponding columns. Please refer the below matrix for details.
<iframe width="100%" height="700vh" src="https://docs.google.com/spreadsheets/d/e/2PACX-1vTpCNKtA-szaXUKJEO5uuSIRnzUOK793MKnyBz9m2rQcwn7HqK19jPHeER-IIRWH9X56J78wfxXZuuv/pubhtml?gid=427284630&single=true&widget=true&headers=false"></iframe> | packages/noco-docs/versioned_docs/version-0.109.7/030.setup-and-usages/030.column-operations.md | 0 | https://github.com/nocodb/nocodb/commit/b862043ce25ff49926754ea05282a300278ec746 | [
0.00033439238904975355,
0.00018668011762201786,
0.0001625881268410012,
0.00016997706552501768,
0.00005230021270108409
] |
{
"id": 4,
"code_window": [
" width?: string\n",
"}\n",
"\n",
"const {\n",
" url,\n",
" socialMedias,\n",
" title = 'NocoDB',\n",
" summary,\n",
" hashTags = '',\n",
" css = '',\n",
" iconClass = '',\n",
" width = '45px',\n",
"} = defineProps<Props>()\n",
"\n",
"const summaryArr = [\n",
" 'Instant #Rest & #GraphQL APIs on any #SQL Database (Supports : MySQL, PostgresSQL, MsSQL, SQLite, MariaDB) #nocodb ',\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
"const { url, socialMedias, title, summary, hashTags, css, iconClass, width } = withDefaults(defineProps<Props>(), {\n",
" title: 'NocoDB',\n",
" hashTags: '',\n",
" css: '',\n",
" iconClass: '',\n",
" width: '45px',\n",
"})\n"
],
"file_path": "packages/nc-gui/components/general/Share.vue",
"type": "replace",
"edit_start_line_idx": 14
} | import { Controller, Delete, Get, UseGuards } from '@nestjs/common';
import { OrgUserRoles } from 'nocodb-sdk';
import { CachesService } from '~/services/caches.service';
import { GlobalGuard } from '~/guards/global/global.guard';
import { Acl } from '~/middlewares/extract-ids/extract-ids.middleware';
import { MetaApiLimiterGuard } from '~/guards/meta-api-limiter.guard';
@Controller()
@UseGuards(MetaApiLimiterGuard, GlobalGuard)
export class CachesController {
constructor(private readonly cachesService: CachesService) {}
@Get(['/api/v1/db/meta/cache', '/api/v2/meta/cache'])
@Acl('cacheGet', {
scope: 'org',
allowedRoles: [OrgUserRoles.SUPER_ADMIN],
blockApiTokenAccess: true,
})
async cacheGet(_, res) {
const data = await this.cachesService.cacheGet();
res.set({
'Content-Type': 'application/json',
'Content-Disposition': `attachment; filename="cache-export.json"`,
});
return JSON.stringify(data);
}
@Delete(['/api/v1/db/meta/cache', '/api/v2/meta/cache'])
@Acl('cacheDelete', {
scope: 'org',
allowedRoles: [OrgUserRoles.SUPER_ADMIN],
blockApiTokenAccess: true,
})
async cacheDelete() {
return await this.cachesService.cacheDelete();
}
}
| packages/nocodb/src/controllers/caches.controller.ts | 0 | https://github.com/nocodb/nocodb/commit/b862043ce25ff49926754ea05282a300278ec746 | [
0.00017416079936083406,
0.0001711017539491877,
0.0001688954362180084,
0.000170675411936827,
0.000002086673021040042
] |
{
"id": 5,
"code_window": [
" nav?: boolean\n",
"}\n",
"\n",
"const { nav = false } = defineProps<Props>()\n",
"</script>\n",
"\n",
"<template>\n",
" <a-card class=\"w-[300px] shadow-sm !rounded-lg\">\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"const { nav } = withDefaults(defineProps<Props>(), { nav: false })\n"
],
"file_path": "packages/nc-gui/components/general/Sponsors.vue",
"type": "replace",
"edit_start_line_idx": 5
} | <script lang="ts" setup>
import type { BaseType } from 'nocodb-sdk'
import { iconMap, navigateTo, useColors, useNuxtApp } from '#imports'
interface Props {
bases?: BaseType[]
}
const { bases = [] } = defineProps<Props>()
const emit = defineEmits(['delete-base'])
const { $e } = useNuxtApp()
const { getColorByIndex } = useColors(true)
const openProject = async (base: BaseType) => {
await navigateTo(`/nc/${base.id}`)
$e('a:base:open', { count: bases.length })
}
const formatTitle = (title?: string) =>
title
?.split(' ')
.map((w) => w[0])
.slice(0, 2)
.join('')
</script>
<template>
<div class="grid grid-cols-2 md:grid-cols-4 lg:grid-cols-6 3xl:grid-cols-8 gap-6 md:(gap-y-16)">
<div class="group flex flex-col items-center gap-2">
<v-menu>
<template #activator="{ props }">
<div
class="thumbnail hover:(after:!opacity-100 shadow-lg to-primary/50)"
:style="{ '--thumbnail-color': '#1348ba' }"
@click="props.onClick"
>
a
<component :is="iconMap.plus" />
</div>
<div class="prose-lg font-semibold">
{{ $t('title.newProj') }}
</div>
</template>
<v-list class="!py-0 flex flex-col bg-white rounded-lg shadow-md border-1 border-gray-300 mt-2 ml-2">
<div
class="grid grid-cols-12 cursor-pointer hover:bg-gray-200 flex items-center p-2"
@click="navigateTo('/base/create')"
>
<component :is="iconMap.plus" class="col-span-2 mr-1 mt-[1px] text-primary text-lg" />
<div class="col-span-10 text-sm xl:text-md">{{ $t('activity.createProject') }}</div>
</div>
<div
class="grid grid-cols-12 cursor-pointer hover:bg-gray-200 flex items-center p-2"
@click="navigateTo('/base/create-external')"
>
<component :is="iconMap.dtabase" class="col-span-2 mr-1 mt-[1px] text-green-500 text-lg" />
<div class="col-span-10 text-sm xl:text-md" v-html="$t('activity.createProjectExtended.extDB')" />
</div>
</v-list>
</v-menu>
</div>
<div v-for="(base, i) of bases" :key="base.id" class="group flex flex-col items-center gap-2">
<div class="thumbnail" :style="{ '--thumbnail-color': getColorByIndex(i) }" @click="openProject(base)">
{{ formatTitle(base.title) }}
<a-dropdown overlay-class-name="nc-dropdown-base-operations" @click.stop>
<component :is="iconMap.arrowDown" class="menu-icon" />
<template #overlay>
<a-menu>
<a-menu-item @click.stop="emit('delete-base', base)">
<div class="grid grid-cols-6 cursor-pointer flex items-center p-2">
<component :is="iconMap.delete" class="col-span-2 mr-1 mt-[1px] text-red text-lg" />
<div class="col-span-4 text-sm xl:text-md">{{ $t('general.delete') }}</div>
</div>
</a-menu-item>
<a-menu-item @click.stop="navigateTo(`/base/${base.id}`)">
<div class="grid grid-cols-6 cursor-pointer flex items-center p-2">
<component :is="iconMap.edit" class="col-span-2 mr-1 mt-[1px] text-primary text-lg" />
<div class="col-span-4 text-sm xl:text-md">{{ $t('general.edit') }}</div>
</div>
</a-menu-item>
</a-menu>
</template>
</a-dropdown>
</div>
<div class="prose-lg font-semibold overflow-ellipsis w-full overflow-hidden text-center capitalize">
{{ base.title || 'Untitled' }}
</div>
</div>
</div>
</template>
<style scoped>
.thumbnail {
@apply relative rounded-md opacity-75 font-bold text-white text-[75px] h-[100px] w-full w-[100px] shadow-md cursor-pointer uppercase flex items-center justify-center color-transition hover:(after:opacity-100 shadow-none);
}
.thumbnail::after {
@apply rounded-md absolute top-0 left-0 right-0 bottom-0 transition-all duration-150 ease-in-out opacity-75;
background-color: var(--thumbnail-color);
content: '';
z-index: -1;
}
.thumbnail:hover::after {
@apply shadow-2xl transform scale-110;
}
.menu-icon,
.star-icon {
@apply w-auto opacity-0 absolute h-[1.75rem] transition-opacity !duration-200 group-hover:opacity-100;
}
.star-icon {
@apply top-1 right-1 transform hover:(scale-120 text-yellow-300/75) transition-all duration-100 ease;
}
.menu-icon {
@apply bottom-1 right-1 transform hover:(scale-150 text-gray-200) transition-all duration-100 ease;
}
</style>
| packages/nc-gui/pages/projects/index/index.vue | 1 | https://github.com/nocodb/nocodb/commit/b862043ce25ff49926754ea05282a300278ec746 | [
0.02272200398147106,
0.0019819450099021196,
0.00016653505736030638,
0.00023515419161412865,
0.005987838376313448
] |
{
"id": 5,
"code_window": [
" nav?: boolean\n",
"}\n",
"\n",
"const { nav = false } = defineProps<Props>()\n",
"</script>\n",
"\n",
"<template>\n",
" <a-card class=\"w-[300px] shadow-sm !rounded-lg\">\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"const { nav } = withDefaults(defineProps<Props>(), { nav: false })\n"
],
"file_path": "packages/nc-gui/components/general/Sponsors.vue",
"type": "replace",
"edit_start_line_idx": 5
} | import type { BoolType, GridColumnType } from 'nocodb-sdk';
import View from '~/models/View';
import Noco from '~/Noco';
import { extractProps } from '~/helpers/extractProps';
import NocoCache from '~/cache/NocoCache';
import { CacheGetType, CacheScope, MetaTable } from '~/utils/globals';
export default class GridViewColumn implements GridColumnType {
id: string;
show: BoolType;
order: number;
width?: string;
fk_view_id: string;
fk_column_id: string;
base_id?: string;
source_id?: string;
group_by?: BoolType;
group_by_order?: number;
group_by_sort?: string;
constructor(data: GridViewColumn) {
Object.assign(this, data);
}
public static async list(
viewId: string,
ncMeta = Noco.ncMeta,
): Promise<GridViewColumn[]> {
const cachedList = await NocoCache.getList(CacheScope.GRID_VIEW_COLUMN, [
viewId,
]);
let { list: views } = cachedList;
const { isNoneList } = cachedList;
if (!isNoneList && !views.length) {
views = await ncMeta.metaList2(null, null, MetaTable.GRID_VIEW_COLUMNS, {
condition: {
fk_view_id: viewId,
},
orderBy: {
order: 'asc',
},
});
await NocoCache.setList(CacheScope.GRID_VIEW_COLUMN, [viewId], views);
}
views.sort(
(a, b) =>
(a.order != null ? a.order : Infinity) -
(b.order != null ? b.order : Infinity),
);
return views?.map((v) => new GridViewColumn(v));
}
public static async get(gridViewColumnId: string, ncMeta = Noco.ncMeta) {
let view =
gridViewColumnId &&
(await NocoCache.get(
`${CacheScope.GRID_VIEW_COLUMN}:${gridViewColumnId}`,
CacheGetType.TYPE_OBJECT,
));
if (!view) {
view = await ncMeta.metaGet2(
null,
null,
MetaTable.GRID_VIEW_COLUMNS,
gridViewColumnId,
);
await NocoCache.set(
`${CacheScope.GRID_VIEW_COLUMN}:${gridViewColumnId}`,
view,
);
}
return view && new GridViewColumn(view);
}
static async insert(column: Partial<GridViewColumn>, ncMeta = Noco.ncMeta) {
const insertObj = extractProps(column, [
'fk_view_id',
'fk_column_id',
'show',
'base_id',
'source_id',
'order',
'width',
'group_by',
'group_by_order',
'group_by_sort',
]);
insertObj.order =
column?.order ??
(await ncMeta.metaGetNextOrder(MetaTable.GRID_VIEW_COLUMNS, {
fk_view_id: column.fk_view_id,
}));
if (!(column.base_id && column.source_id)) {
const viewRef = await View.get(column.fk_view_id, ncMeta);
insertObj.base_id = viewRef.base_id;
insertObj.source_id = viewRef.source_id;
}
const { id, fk_column_id } = await ncMeta.metaInsert2(
null,
null,
MetaTable.GRID_VIEW_COLUMNS,
insertObj,
);
await NocoCache.set(`${CacheScope.GRID_VIEW_COLUMN}:${fk_column_id}`, id);
// if cache is not present skip pushing it into the list to avoid unexpected behaviour
const { list } = await NocoCache.getList(CacheScope.GRID_VIEW_COLUMN, [
column.fk_view_id,
]);
if (list.length)
await NocoCache.appendToList(
CacheScope.GRID_VIEW_COLUMN,
[column.fk_view_id],
`${CacheScope.GRID_VIEW_COLUMN}:${id}`,
);
await View.fixPVColumnForView(column.fk_view_id, ncMeta);
// on new view column, delete any optimised single query cache
{
const view = await View.get(column.fk_view_id, ncMeta);
await NocoCache.delAll(
CacheScope.SINGLE_QUERY,
`${view.fk_model_id}:${view.id}:*`,
);
}
return this.get(id, ncMeta);
}
static async update(
columnId: string,
body: Partial<GridViewColumn>,
ncMeta = Noco.ncMeta,
) {
const updateObj = extractProps(body, [
'order',
'show',
'width',
'group_by',
'group_by_order',
'group_by_sort',
]);
// get existing cache
const key = `${CacheScope.GRID_VIEW_COLUMN}:${columnId}`;
let o = await NocoCache.get(key, CacheGetType.TYPE_OBJECT);
if (o) {
// update data
o = { ...o, ...updateObj };
// set cache
await NocoCache.set(key, o);
}
// set meta
const res = await ncMeta.metaUpdate(
null,
null,
MetaTable.GRID_VIEW_COLUMNS,
updateObj,
columnId,
);
// on view column update, delete any optimised single query cache
{
const gridCol = await this.get(columnId, ncMeta);
const view = await View.get(gridCol.fk_view_id, ncMeta);
await NocoCache.delAll(
CacheScope.SINGLE_QUERY,
`${view.fk_model_id}:${view.id}:*`,
);
}
return res;
}
}
| packages/nocodb/src/models/GridViewColumn.ts | 0 | https://github.com/nocodb/nocodb/commit/b862043ce25ff49926754ea05282a300278ec746 | [
0.00018954943516291678,
0.00017280795145779848,
0.00016649188182782382,
0.00017319120524916798,
0.000005068935934104957
] |
{
"id": 5,
"code_window": [
" nav?: boolean\n",
"}\n",
"\n",
"const { nav = false } = defineProps<Props>()\n",
"</script>\n",
"\n",
"<template>\n",
" <a-card class=\"w-[300px] shadow-sm !rounded-lg\">\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"const { nav } = withDefaults(defineProps<Props>(), { nav: false })\n"
],
"file_path": "packages/nc-gui/components/general/Sponsors.vue",
"type": "replace",
"edit_start_line_idx": 5
} | {
"label": "Workspaces ☁",
"collapsible": true,
"collapsed": true,
"link": {
"type": "generated-index"
}
} | packages/noco-docs/docs/030.workspaces/_category_.json | 0 | https://github.com/nocodb/nocodb/commit/b862043ce25ff49926754ea05282a300278ec746 | [
0.00017225099145434797,
0.00017225099145434797,
0.00017225099145434797,
0.00017225099145434797,
0
] |
{
"id": 5,
"code_window": [
" nav?: boolean\n",
"}\n",
"\n",
"const { nav = false } = defineProps<Props>()\n",
"</script>\n",
"\n",
"<template>\n",
" <a-card class=\"w-[300px] shadow-sm !rounded-lg\">\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"const { nav } = withDefaults(defineProps<Props>(), { nav: false })\n"
],
"file_path": "packages/nc-gui/components/general/Sponsors.vue",
"type": "replace",
"edit_start_line_idx": 5
} | import debug from 'debug';
const namespaces = {};
const levels = {
api: 'A',
info: 'I',
error: 'E',
warn: 'W',
debug: 'D',
};
export default class DebugMgr {
static _create(namespace) {
if (namespaces[namespace]) {
namespaces[namespace][`${namespace}_A`].enabled = debug.enabled(
`${namespace}_A`,
);
namespaces[namespace][`${namespace}_D`].enabled = debug.enabled(
`${namespace}_D`,
);
namespaces[namespace][`${namespace}_I`].enabled = debug.enabled(
`${namespace}_I`,
);
namespaces[namespace][`${namespace}_W`].enabled = debug.enabled(
`${namespace}_W`,
);
namespaces[namespace][`${namespace}_E`].enabled = debug.enabled(
`${namespace}_E`,
);
} else {
namespaces[namespace] = {};
namespaces[namespace][`${namespace}_A`] = {
level: 'api',
enabled: debug.enabled(`${namespace}_A`),
};
namespaces[namespace][`${namespace}_W`] = {
level: 'warn',
enabled: debug.enabled(`${namespace}_W`),
};
namespaces[namespace][`${namespace}_I`] = {
level: 'info',
enabled: debug.enabled(`${namespace}_I`),
};
namespaces[namespace][`${namespace}_E`] = {
level: 'error',
enabled: debug.enabled(`${namespace}_E`),
};
namespaces[namespace][`${namespace}_D`] = {
level: 'debug',
enabled: debug.enabled(`${namespace}_D`),
};
}
}
static createNamespace(namespace) {
if (!(namespace in namespaces)) {
this._create(namespace);
// console.log(namespaces);
}
}
static getNamespaces() {
return namespaces;
}
static refreshNamespace(namespace) {
this._create(namespace);
}
static enable(namespace, level) {
const toBeEnabled = `${namespace}_${levels[level]},${debug.disable()}`;
debug.enable(`${toBeEnabled}`);
this.refreshNamespace(namespace);
}
static disable(namespace, level) {
const toBeRemoved = `${namespace}_${levels[level]}`;
let list = `${debug.disable()}`;
list = list.replace(toBeRemoved, '');
debug.enable(list);
this.refreshNamespace(namespace);
}
static enableAll(namespace) {
for (const key in levels) {
debug.enable(`${namespace}_${levels[key]}`);
this.refreshNamespace(namespace);
}
}
static disableAll(namespace) {
for (const key in levels) {
debug.disable(`${namespace}_${levels[key]}`);
this.refreshNamespace(namespace);
}
}
}
| packages/nocodb/src/db/util/DebugMgr.ts | 0 | https://github.com/nocodb/nocodb/commit/b862043ce25ff49926754ea05282a300278ec746 | [
0.0001766273780958727,
0.00017282800399698317,
0.00016424557543359697,
0.0001735998084768653,
0.000003627304977271706
] |
{
"id": 6,
"code_window": [
" length?: number\n",
"}\n",
"\n",
"const { placement = 'bottom', length = 20 } = defineProps<Props>()\n",
"\n",
"const text = ref<HTMLDivElement>()\n",
"\n",
"const enableTooltip = computed(() => text.value?.textContent?.length && text.value?.textContent?.length > length)\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"const { placement, length } = withDefaults(defineProps<Props>(), { placement: 'bottom', length: 20 })\n"
],
"file_path": "packages/nc-gui/components/general/TruncateText.vue",
"type": "replace",
"edit_start_line_idx": 20
} | <script lang="ts" setup>
import { computed, ref } from '#imports'
interface Props {
placement?:
| 'top'
| 'left'
| 'right'
| 'bottom'
| 'topLeft'
| 'topRight'
| 'bottomLeft'
| 'bottomRight'
| 'leftTop'
| 'leftBottom'
| 'rightTop'
| 'rightBottom'
length?: number
}
const { placement = 'bottom', length = 20 } = defineProps<Props>()
const text = ref<HTMLDivElement>()
const enableTooltip = computed(() => text.value?.textContent?.length && text.value?.textContent?.length > length)
const shortName = computed(() =>
text.value?.textContent?.length && text.value?.textContent.length > length
? `${text.value?.textContent?.substr(0, length - 3)}...`
: text.value?.textContent,
)
</script>
<template>
<a-tooltip v-if="enableTooltip" :placement="placement">
<template #title>
<slot />
</template>
<div class="w-full">{{ shortName }}</div>
</a-tooltip>
<div v-else class="w-full" data-testid="truncate-label">
<slot />
</div>
<div ref="text" class="hidden"><slot /></div>
</template>
| packages/nc-gui/components/general/TruncateText.vue | 1 | https://github.com/nocodb/nocodb/commit/b862043ce25ff49926754ea05282a300278ec746 | [
0.9980692267417908,
0.20080240070819855,
0.00016676737868692726,
0.0008565190364606678,
0.39863696694374084
] |
{
"id": 6,
"code_window": [
" length?: number\n",
"}\n",
"\n",
"const { placement = 'bottom', length = 20 } = defineProps<Props>()\n",
"\n",
"const text = ref<HTMLDivElement>()\n",
"\n",
"const enableTooltip = computed(() => text.value?.textContent?.length && text.value?.textContent?.length > length)\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"const { placement, length } = withDefaults(defineProps<Props>(), { placement: 'bottom', length: 20 })\n"
],
"file_path": "packages/nc-gui/components/general/TruncateText.vue",
"type": "replace",
"edit_start_line_idx": 20
} | export async function extractSdkResponseErrorMsg(e: Error & { response: any }) {
if (!e || !e.response) return e.message
let msg
let errors: any[] | null = null
if (e.response.data instanceof Blob) {
try {
const parsedData = JSON.parse(await e.response.data.text())
msg = parsedData.msg
errors = parsedData.errors
} catch {
msg = 'Some internal error occurred'
}
} else {
msg = e.response.data.msg || e.response.data.message || 'Some internal error occurred'
errors = e.response.data.errors
}
if (Array.isArray(errors) && errors.length) {
return errors.map((e: any) => (e.instancePath ? `${e.instancePath} - ` : '') + e.message).join(', ')
}
return msg || 'Some error occurred'
}
| packages/nc-gui/utils/errorUtils.ts | 0 | https://github.com/nocodb/nocodb/commit/b862043ce25ff49926754ea05282a300278ec746 | [
0.0011454985942691565,
0.0004965660627931356,
0.0001707952469587326,
0.0001734043617034331,
0.0004588658339343965
] |
{
"id": 6,
"code_window": [
" length?: number\n",
"}\n",
"\n",
"const { placement = 'bottom', length = 20 } = defineProps<Props>()\n",
"\n",
"const text = ref<HTMLDivElement>()\n",
"\n",
"const enableTooltip = computed(() => text.value?.textContent?.length && text.value?.textContent?.length > length)\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"const { placement, length } = withDefaults(defineProps<Props>(), { placement: 'bottom', length: 20 })\n"
],
"file_path": "packages/nc-gui/components/general/TruncateText.vue",
"type": "replace",
"edit_start_line_idx": 20
} | import BasePage from '../../Base';
import { expect, Locator } from '@playwright/test';
import { DetailsPage } from './index';
export class ErdPage extends BasePage {
readonly detailsPage: DetailsPage;
readonly contextMenuBase: Locator;
readonly contextMenu = {};
readonly btn_fullScreen: Locator;
readonly btn_zoomIn: Locator;
readonly btn_zoomOut: Locator;
constructor(details: DetailsPage) {
super(details.rootPage);
this.detailsPage = details;
this.btn_fullScreen = this.get().locator('.nc-erd-histogram > .nc-icon');
this.btn_zoomIn = this.get().locator('.nc-erd-zoom-btn').nth(0);
this.btn_zoomOut = this.get().locator('.nc-erd-zoom-btn').nth(1);
this.contextMenuBase = this.get().locator('.nc-erd-context-menu');
this.contextMenu['Show Columns'] = this.contextMenuBase.locator('.ant-checkbox-wrapper').nth(0);
this.contextMenu['Show Primary and Foreign Keys'] = this.contextMenuBase.locator('.ant-checkbox-wrapper').nth(1);
this.contextMenu['Show SQL Views'] = this.contextMenuBase.locator('.ant-checkbox-wrapper').nth(2);
}
get() {
// pop up when triggered from data sources page
return this.rootPage.locator('.vue-flow');
}
async verifyNode({
tableName,
columnName,
columnNameShouldNotExist,
}: {
tableName: string;
columnName?: string;
columnNameShouldNotExist?: string;
}) {
await this.get().locator(`.nc-erd-table-node-${tableName}`).waitFor({ state: 'visible' });
if (columnName) {
await this.get().locator(`.nc-erd-table-node-${tableName}-column-${columnName}`).waitFor({ state: 'visible' });
}
if (columnNameShouldNotExist) {
await this.get()
.locator(`.nc-erd-table-node-${tableName}-column-${columnNameShouldNotExist}`)
.waitFor({ state: 'hidden' });
}
}
async verifyNodeDoesNotExist({ tableName }: { tableName: string }) {
await this.get().locator(`.nc-erd-table-node-${tableName}`).waitFor({ state: 'hidden' });
}
async verifyColumns({ tableName, columns }: { tableName: string; columns: string[] }) {
for (const column of columns) {
await this.verifyNode({ tableName, columnName: column });
}
}
async verifyNodesCount(count: number) {
await expect(this.get().locator('.nc-erd-table-node')).toHaveCount(count);
}
async verifyEdgesCount({
count,
circleCount,
rectangleCount,
}: {
count: number;
circleCount: number;
rectangleCount: number;
}) {
await expect(this.get().locator('.vue-flow__edge')).toHaveCount(count);
await expect(this.get().locator('.nc-erd-edge-circle')).toHaveCount(circleCount);
await expect(this.get().locator('.nc-erd-edge-rect')).toHaveCount(rectangleCount);
}
async verifyJunctionTableLabel({ tableTitle, tableName }: { tableName: string; tableTitle: string }) {
await this.get().locator(`.nc-erd-table-label-${tableTitle}-${tableName}`).waitFor({
state: 'visible',
});
}
async clickShowColumnNames() {
await this.contextMenu['Show Columns'].click();
await (await this.get().elementHandle())?.waitForElementState('stable');
}
async clickShowPkAndFk() {
await this.contextMenu['Show Primary and Foreign Keys'].click();
await (await this.get().elementHandle())?.waitForElementState('stable');
}
async clickShowSqlViews() {
await this.contextMenu['Show SQL Views'].click();
await (await this.get().elementHandle())?.waitForElementState('stable');
}
async close() {
await this.get().click();
await this.rootPage.keyboard.press('Escape');
await this.get().waitFor({ state: 'hidden' });
}
}
| tests/playwright/pages/Dashboard/Details/ErdPage.ts | 0 | https://github.com/nocodb/nocodb/commit/b862043ce25ff49926754ea05282a300278ec746 | [
0.00017673586262390018,
0.00017282951739616692,
0.00016789877554401755,
0.00017289436073042452,
0.0000025253511921619065
] |
{
"id": 6,
"code_window": [
" length?: number\n",
"}\n",
"\n",
"const { placement = 'bottom', length = 20 } = defineProps<Props>()\n",
"\n",
"const text = ref<HTMLDivElement>()\n",
"\n",
"const enableTooltip = computed(() => text.value?.textContent?.length && text.value?.textContent?.length > length)\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"const { placement, length } = withDefaults(defineProps<Props>(), { placement: 'bottom', length: 20 })\n"
],
"file_path": "packages/nc-gui/components/general/TruncateText.vue",
"type": "replace",
"edit_start_line_idx": 20
} | export default `<!doctype html>
<html>
<head>
<meta name="viewport" content="width=device-width">
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Simple Transactional Email</title>
<style>
@media only screen and (max-width: 620px) {
table[class=body] h1 {
font-size: 28px !important;
margin-bottom: 10px !important;
}
table[class=body] p,
table[class=body] ul,
table[class=body] ol,
table[class=body] td,
table[class=body] span,
table[class=body] a {
font-size: 16px !important;
}
table[class=body] .wrapper,
table[class=body] .article {
padding: 10px !important;
}
table[class=body] .content {
padding: 0 !important;
}
table[class=body] .container {
padding: 0 !important;
width: 100% !important;
}
table[class=body] .main {
border-left-width: 0 !important;
border-radius: 0 !important;
border-right-width: 0 !important;
}
table[class=body] .btn table {
width: 100% !important;
}
table[class=body] .btn a {
width: 100% !important;
}
table[class=body] .img-responsive {
height: auto !important;
max-width: 100% !important;
width: auto !important;
}
}
@media all {
.ExternalClass {
width: 100%;
}
.ExternalClass,
.ExternalClass p,
.ExternalClass span,
.ExternalClass font,
.ExternalClass td,
.ExternalClass div {
line-height: 100%;
}
.apple-link a {
color: inherit !important;
font-family: inherit !important;
font-size: inherit !important;
font-weight: inherit !important;
line-height: inherit !important;
text-decoration: none !important;
}
#MessageViewBody a {
color: inherit;
text-decoration: none;
font-size: inherit;
font-family: inherit;
font-weight: inherit;
line-height: inherit;
}
.btn-primary table td:hover {
background-color: #34495e !important;
}
.btn-primary a:hover {
background-color: #34495e !important;
border-color: #34495e !important;
}
}
</style>
</head>
<body class="" style="background-color: #f6f6f6; font-family: sans-serif; -webkit-font-smoothing: antialiased; font-size: 14px; line-height: 1.4; margin: 0; padding: 0; -ms-text-size-adjust: 100%; -webkit-text-size-adjust: 100%;">
<span class="preheader" style="color: transparent; display: none; height: 0; max-height: 0; max-width: 0; opacity: 0; overflow: hidden; mso-hide: all; visibility: hidden; width: 0;">This is preheader text. Some clients will show this text as a preview.</span>
<table role="presentation" border="0" cellpadding="0" cellspacing="0" class="body" style="border-collapse: separate; mso-table-lspace: 0pt; mso-table-rspace: 0pt; background-color: #f6f6f6; width: 100%;" width="100%" bgcolor="#f6f6f6">
<tr>
<td style="font-family: sans-serif; font-size: 14px; vertical-align: top;" valign="top"> </td>
<td class="container" style="font-family: sans-serif; font-size: 14px; vertical-align: top; display: block; max-width: 580px; padding: 10px; width: 580px; margin: 0 auto;" width="580" valign="top">
<div class="content" style="box-sizing: border-box; display: block; margin: 0 auto; max-width: 580px; padding: 10px;">
<!-- START CENTERED WHITE CONTAINER -->
<table role="presentation" class="main" style="border-collapse: separate; mso-table-lspace: 0pt; mso-table-rspace: 0pt; background: #ffffff; border-radius: 3px; width: 100%;" width="100%">
<!-- START MAIN CONTENT AREA -->
<tr>
<td class="wrapper" style="font-family: sans-serif; font-size: 14px; vertical-align: top; box-sizing: border-box; padding: 20px;" valign="top">
<table role="presentation" border="0" cellpadding="0" cellspacing="0" style="border-collapse: separate; mso-table-lspace: 0pt; mso-table-rspace: 0pt; width: 100%;" width="100%">
<tr>
<td style="font-family: sans-serif; font-size: 14px; vertical-align: top;" valign="top">
<p style="font-family: sans-serif; font-size: 14px; font-weight: normal; margin: 0; margin-bottom: 15px;">Hi,</p>
<p style="font-family: sans-serif; font-size: 14px; font-weight: normal; margin: 0; margin-bottom: 15px;">To change your NocoDB account password click the following link.</p>
<table role="presentation" border="0" cellpadding="0" cellspacing="0" class="btn btn-primary" style="border-collapse: separate; mso-table-lspace: 0pt; mso-table-rspace: 0pt; box-sizing: border-box; width: 100%;" width="100%">
<tbody>
<tr>
<td align="left" style="font-family: sans-serif; font-size: 14px; vertical-align: top; padding-bottom: 15px;" valign="top">
<table role="presentation" border="0" cellpadding="0" cellspacing="0" style="border-collapse: separate; mso-table-lspace: 0pt; mso-table-rspace: 0pt; width: auto;">
<tbody>
<tr>
<td style="font-family: sans-serif; font-size: 14px; vertical-align: top; border-radius: 5px; text-align: center; background-color: #3498db;" valign="top" align="center" bgcolor="#1088ff"> <a href="<%- resetLink %>" target="_blank" style="border: solid 1px rgb(23, 139, 255); border-radius: 5px; box-sizing: border-box; cursor: pointer; display: inline-block; font-size: 14px; font-weight: bold; margin: 0; padding: 12px 25px; text-decoration: none; text-transform: capitalize; background-color: rgb(23, 139, 255); border-color: #3498db; color: #ffffff;">Reset Password</a> </td>
</tr>
</tbody>
</table>
</td>
</tr>
</tbody>
</table>
<p style="font-family: sans-serif; font-size: 14px; font-weight: normal; margin: 0; margin-bottom: 15px;">Thanks regards NocoDB.</p>
</td>
</tr>
</table>
</td>
</tr>
<!-- END MAIN CONTENT AREA -->
</table>
<!-- END CENTERED WHITE CONTAINER -->
<!-- START FOOTER -->
<div class="footer" style="clear: both; margin-top: 10px; text-align: center; width: 100%;">
<table role="presentation" border="0" cellpadding="0" cellspacing="0" style="border-collapse: separate; mso-table-lspace: 0pt; mso-table-rspace: 0pt; width: 100%;" width="100%">
<tr>
<td class="content-block" style="font-family: sans-serif; vertical-align: top; padding-bottom: 10px; padding-top: 10px; color: #999999; font-size: 12px; text-align: center;" valign="top" align="center">
<span class="apple-link" style="color: #999999; font-size: 12px; text-align: center;"></span>
<!-- <br> Don't like these emails? <a href="http://i.imgur.com/CScmqnj.gif">Unsubscribe</a>.-->
</td>
</tr>
<tr>
<td class="content-block powered-by" style="font-family: sans-serif; vertical-align: top; padding-bottom: 10px; padding-top: 10px; color: #999999; font-size: 12px; text-align: center;" valign="top" align="center">
<a href="http://nocodb.com/">NocoDB</a>
<!-- Powered by <a href="http://htmlemail.io">HTMLemail</a>.-->
</td>
</tr>
</table>
</div>
<!-- END FOOTER -->
</div>
</td>
<td style="font-family: sans-serif; font-size: 14px; vertical-align: top;" valign="top"> </td>
</tr>
</table>
</body>
</html>
`;
| packages/nocodb/src/controllers/auth/ui/emailTemplates/forgotPassword.ts | 0 | https://github.com/nocodb/nocodb/commit/b862043ce25ff49926754ea05282a300278ec746 | [
0.00017533081700094044,
0.0001696831895969808,
0.0001649219630053267,
0.0001699718413874507,
0.0000030530600270139985
] |
{
"id": 7,
"code_window": [
" readOnly?: boolean\n",
"}\n",
"\n",
"const { hideMinimap, lang = 'json', validate = true, disableDeepCompare = false, modelValue, readOnly } = defineProps<Props>()\n",
"\n",
"const emits = defineEmits(['update:modelValue'])\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
"const { hideMinimap, lang, validate, disableDeepCompare, modelValue, readOnly } = withDefaults(defineProps<Props>(), {\n",
" lang: 'json',\n",
" validate: true,\n",
" disableDeepCompare: false,\n",
"})\n"
],
"file_path": "packages/nc-gui/components/monaco/Editor.vue",
"type": "replace",
"edit_start_line_idx": 16
} | <script lang="ts" setup>
interface Props {
nav?: boolean
}
const { nav = false } = defineProps<Props>()
</script>
<template>
<a-card class="w-[300px] shadow-sm !rounded-lg">
<template #cover>
<img class="max-h-[180px] !rounded-t-lg" alt="cover" src="~/assets/img/ants-leaf-cutter.jpeg" />
</template>
<a-card-meta>
<template #title>
<span v-if="!nav" class="text-xl pb-4">
{{ $t('msg.info.sponsor.header') }}
</span>
</template>
</a-card-meta>
<div v-if="!nav" class="py-5 text-sm">
{{ $t('msg.info.sponsor.message') }}
</div>
<div class="flex justify-center">
<nuxt-link no-prefetch no-rel href="https://github.com/sponsors/nocodb" target="_blank">
<a-button class="!shadow rounded" size="large">
<div class="flex items-center">
<mdi-cards-heart class="text-red-500 mr-2" />
{{ $t('activity.sponsorUs') }}
</div>
</a-button>
</nuxt-link>
</div>
</a-card>
</template>
| packages/nc-gui/components/general/Sponsors.vue | 1 | https://github.com/nocodb/nocodb/commit/b862043ce25ff49926754ea05282a300278ec746 | [
0.317428857088089,
0.07948560267686844,
0.000169849387020804,
0.00017184823809657246,
0.137376606464386
] |
{
"id": 7,
"code_window": [
" readOnly?: boolean\n",
"}\n",
"\n",
"const { hideMinimap, lang = 'json', validate = true, disableDeepCompare = false, modelValue, readOnly } = defineProps<Props>()\n",
"\n",
"const emits = defineEmits(['update:modelValue'])\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
"const { hideMinimap, lang, validate, disableDeepCompare, modelValue, readOnly } = withDefaults(defineProps<Props>(), {\n",
" lang: 'json',\n",
" validate: true,\n",
" disableDeepCompare: false,\n",
"})\n"
],
"file_path": "packages/nc-gui/components/monaco/Editor.vue",
"type": "replace",
"edit_start_line_idx": 16
} | <script lang="ts" setup>
const workspaceStore = useWorkspace()
const { isWorkspaceLoading } = storeToRefs(workspaceStore)
const { isSharedBase } = storeToRefs(useBase())
const { isMobileMode } = useGlobal()
const treeViewDom = ref<HTMLElement>()
const isTreeViewOnScrollTop = ref(false)
const checkScrollTopMoreThanZero = () => {
if (isMobileMode.value) return
if (treeViewDom.value) {
if (treeViewDom.value.scrollTop > 0) {
isTreeViewOnScrollTop.value = true
} else {
isTreeViewOnScrollTop.value = false
}
}
return false
}
onMounted(() => {
treeViewDom.value?.addEventListener('scroll', checkScrollTopMoreThanZero)
})
onUnmounted(() => {
treeViewDom.value?.removeEventListener('scroll', checkScrollTopMoreThanZero)
})
</script>
<template>
<div
class="nc-sidebar flex flex-col bg-gray-50 outline-r-1 outline-gray-100 select-none w-full h-full"
:style="{
outlineWidth: '1px',
}"
>
<div class="flex flex-col">
<DashboardSidebarHeader />
<DashboardSidebarTopSection v-if="!isSharedBase" />
</div>
<div
ref="treeViewDom"
class="flex flex-col nc-scrollbar-dark-md flex-grow xs:(border-transparent pt-2 pr-2)"
:class="{
'border-t-1': !isSharedBase,
'border-transparent': !isTreeViewOnScrollTop,
'pt-0.25': isSharedBase,
}"
>
<DashboardTreeView v-if="!isWorkspaceLoading" />
</div>
<div v-if="!isSharedBase">
<DashboardSidebarUserInfo />
</div>
</div>
</template>
<style lang="scss" scoped>
.nc-sidebar-top-button {
@apply flex flex-row mx-1 px-3.5 rounded-md items-center py-0.75 my-0.5 gap-x-2 hover:bg-gray-200 cursor-pointer;
}
</style>
| packages/nc-gui/components/dashboard/Sidebar.vue | 0 | https://github.com/nocodb/nocodb/commit/b862043ce25ff49926754ea05282a300278ec746 | [
0.0002867529110517353,
0.00020048879378009588,
0.00016907445387914777,
0.0001712526718620211,
0.000047739726142026484
] |
{
"id": 7,
"code_window": [
" readOnly?: boolean\n",
"}\n",
"\n",
"const { hideMinimap, lang = 'json', validate = true, disableDeepCompare = false, modelValue, readOnly } = defineProps<Props>()\n",
"\n",
"const emits = defineEmits(['update:modelValue'])\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
"const { hideMinimap, lang, validate, disableDeepCompare, modelValue, readOnly } = withDefaults(defineProps<Props>(), {\n",
" lang: 'json',\n",
" validate: true,\n",
" disableDeepCompare: false,\n",
"})\n"
],
"file_path": "packages/nc-gui/components/monaco/Editor.vue",
"type": "replace",
"edit_start_line_idx": 16
} | <script lang="ts" setup>
import { RoleColors, RoleIcons, RoleLabels } from 'nocodb-sdk'
import { toRef } from '#imports'
const props = withDefaults(
defineProps<{
role: keyof typeof RoleLabels
clickable?: boolean
inherit?: boolean
border?: boolean
size?: 'sm' | 'md'
}>(),
{
clickable: false,
inherit: false,
border: true,
size: 'sm',
},
)
const roleRef = toRef(props, 'role')
const clickableRef = toRef(props, 'clickable')
const borderRef = toRef(props, 'border')
const sizeSelect = computed(() => props.size)
const roleProperties = computed(() => {
const role = roleRef.value
const color = RoleColors[role]
const icon = RoleIcons[role]
const label = RoleLabels[role]
return {
color,
icon,
label,
}
})
</script>
<template>
<div
class="flex items-start rounded-md"
:class="{
'cursor-pointer': clickableRef,
}"
>
<NcBadge class="!px-2" :color="roleProperties.color" :border="borderRef" :size="sizeSelect">
<div
class="badge-text flex items-center gap-2"
:class="{
'text-purple-700': roleProperties.color === 'purple',
'text-blue-700': roleProperties.color === 'blue',
'text-green-700': roleProperties.color === 'green',
'text-orange-700': roleProperties.color === 'orange',
'text-yellow-700': roleProperties.color === 'yellow',
'text-red-700': roleProperties.color === 'red',
'text-maroon-700': roleProperties.color === 'maroon',
'text-gray-300': !roleProperties.color,
sizeSelect,
}"
>
<GeneralIcon :icon="roleProperties.icon" />
<span class="flex whitespace-nowrap">
{{ $t(`objects.roleType.${roleProperties.label}`) }}
</span>
<GeneralIcon v-if="clickableRef" icon="arrowDown" />
</div>
</NcBadge>
<!--
<a-tooltip v-if="inheritRef" placement="bottom">
<div class="text-gray-400 text-xs p-1 rounded-md">Workspace Role</div>
</a-tooltip>
-->
</div>
</template>
<style scoped lang="scss"></style>
| packages/nc-gui/components/roles/Badge.vue | 0 | https://github.com/nocodb/nocodb/commit/b862043ce25ff49926754ea05282a300278ec746 | [
0.7844937443733215,
0.09822022169828415,
0.0001701753935776651,
0.00017404071695636958,
0.2593870162963867
] |
{
"id": 7,
"code_window": [
" readOnly?: boolean\n",
"}\n",
"\n",
"const { hideMinimap, lang = 'json', validate = true, disableDeepCompare = false, modelValue, readOnly } = defineProps<Props>()\n",
"\n",
"const emits = defineEmits(['update:modelValue'])\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
"const { hideMinimap, lang, validate, disableDeepCompare, modelValue, readOnly } = withDefaults(defineProps<Props>(), {\n",
" lang: 'json',\n",
" validate: true,\n",
" disableDeepCompare: false,\n",
"})\n"
],
"file_path": "packages/nc-gui/components/monaco/Editor.vue",
"type": "replace",
"edit_start_line_idx": 16
} | import { parse } from 'papaparse'
import type { UploadFile } from 'ant-design-vue'
import { UITypes, getDateFormat, validateDateWithUnknownFormat } from 'nocodb-sdk'
import {
extractMultiOrSingleSelectProps,
getCheckboxValue,
isCheckboxType,
isDecimalType,
isEmailType,
isMultiLineTextType,
isUrlType,
} from './parserHelpers'
export default class CSVTemplateAdapter {
config: Record<string, any>
source: UploadFile[] | string
detectedColumnTypes: Record<number, Record<string, number>>
distinctValues: Record<number, Set<string>>
headers: Record<number, string[]>
tables: Record<number, any>
base: {
tables: Record<string, any>[]
}
data: Record<string, any> = {}
columnValues: Record<number, []>
private progressCallback?: (msg: string) => void
constructor(source: UploadFile[] | string, parserConfig = {}, progressCallback?: (msg: string) => void) {
this.config = parserConfig
this.source = source
this.base = {
tables: [],
}
this.detectedColumnTypes = {}
this.distinctValues = {}
this.headers = {}
this.columnValues = {}
this.tables = {}
this.progressCallback = progressCallback
}
async init() {}
initTemplate(tableIdx: number, tn: string, columnNames: string[]) {
const columnNameRowExist = +columnNames.every((v: any) => v === null || typeof v === 'string')
const columnNamePrefixRef: Record<string, any> = { id: 0 }
const tableObj: Record<string, any> = {
table_name: tn,
ref_table_name: tn,
columns: [],
}
this.headers[tableIdx] = []
this.tables[tableIdx] = []
for (const [columnIdx, columnName] of columnNames.entries()) {
const title = ((columnNameRowExist && columnName.toString().trim()) || `Field ${columnIdx + 1}`).trim()
let cn: string = ((columnNameRowExist && columnName.toString().trim()) || `field_${columnIdx + 1}`)
.replace(/[` ~!@#$%^&*()_|+\-=?;:'",.<>\{\}\[\]\\\/]/g, '_')
.trim()
while (cn in columnNamePrefixRef) {
cn = `${cn}${++columnNamePrefixRef[cn]}`
}
columnNamePrefixRef[cn] = 0
this.detectedColumnTypes[columnIdx] = {}
this.distinctValues[columnIdx] = new Set<string>()
this.columnValues[columnIdx] = []
tableObj.columns.push({
title,
column_name: cn,
ref_column_name: cn,
meta: {},
uidt: UITypes.SingleLineText,
key: columnIdx,
})
this.headers[tableIdx].push(cn)
this.tables[tableIdx] = tableObj
}
}
detectInitialUidt(v: string) {
if (!isNaN(Number(v)) && !isNaN(parseFloat(v))) return UITypes.Number
if (validateDateWithUnknownFormat(v)) return UITypes.DateTime
if (isCheckboxType(v)) return UITypes.Checkbox
return UITypes.SingleLineText
}
detectColumnType(tableIdx: number, data: []) {
for (let columnIdx = 0; columnIdx < data.length; columnIdx++) {
// skip null data
if (!data[columnIdx]) continue
const colData: any = [data[columnIdx]]
const colProps = { uidt: this.detectInitialUidt(data[columnIdx]) }
// TODO(import): centralise
if (isMultiLineTextType(colData)) {
colProps.uidt = UITypes.LongText
} else if (colProps.uidt === UITypes.SingleLineText) {
if (isEmailType(colData)) {
colProps.uidt = UITypes.Email
} else if (isUrlType(colData)) {
colProps.uidt = UITypes.URL
} else if (isCheckboxType(colData)) {
colProps.uidt = UITypes.Checkbox
} else {
if (data[columnIdx] && columnIdx < this.config.maxRowsToParse) {
this.columnValues[columnIdx].push(data[columnIdx])
colProps.uidt = UITypes.SingleSelect
}
}
} else if (colProps.uidt === UITypes.Number) {
if (isDecimalType(colData)) {
colProps.uidt = UITypes.Decimal
}
} else if (colProps.uidt === UITypes.DateTime) {
if (data[columnIdx] && columnIdx < this.config.maxRowsToParse) {
this.columnValues[columnIdx].push(data[columnIdx])
}
}
if (!(colProps.uidt in this.detectedColumnTypes[columnIdx])) {
this.detectedColumnTypes[columnIdx] = {
...this.detectedColumnTypes[columnIdx],
[colProps.uidt]: 0,
}
}
this.detectedColumnTypes[columnIdx][colProps.uidt] += 1
if (data[columnIdx]) {
this.distinctValues[columnIdx].add(data[columnIdx])
}
}
}
getPossibleUidt(columnIdx: number) {
const detectedColTypes = this.detectedColumnTypes[columnIdx]
const len = Object.keys(detectedColTypes).length
// all records are null
if (len === 0) {
return UITypes.SingleLineText
}
// handle numeric case
if (len === 2 && UITypes.Number in detectedColTypes && UITypes.Decimal in detectedColTypes) {
return UITypes.Decimal
}
// if there are multiple detected column types
// then return either LongText or SingleLineText
if (len > 1) {
if (UITypes.LongText in detectedColTypes) {
return UITypes.LongText
}
return UITypes.SingleLineText
}
// otherwise, all records have the same column type
return Object.keys(detectedColTypes)[0]
}
updateTemplate(tableIdx: number) {
for (let columnIdx = 0; columnIdx < this.headers[tableIdx].length; columnIdx++) {
const uidt = this.getPossibleUidt(columnIdx)
if (this.columnValues[columnIdx].length > 0) {
if (uidt === UITypes.DateTime) {
const dateFormat: Record<string, number> = {}
if (
this.columnValues[columnIdx].slice(1, this.config.maxRowsToParse).every((v: any) => {
const isDate = v.split(' ').length === 1
if (isDate) {
dateFormat[getDateFormat(v)] = (dateFormat[getDateFormat(v)] || 0) + 1
}
return isDate
})
) {
this.tables[tableIdx].columns[columnIdx].uidt = UITypes.Date
// take the date format with the max occurrence
const objKeys = Object.keys(dateFormat)
this.tables[tableIdx].columns[columnIdx].meta.date_format = objKeys.length
? objKeys.reduce((x, y) => (dateFormat[x] > dateFormat[y] ? x : y))
: 'YYYY/MM/DD'
} else {
// Datetime
this.tables[tableIdx].columns[columnIdx].uidt = uidt
}
} else if (uidt === UITypes.SingleSelect || uidt === UITypes.MultiSelect) {
// assume it is a SingleLineText first
this.tables[tableIdx].columns[columnIdx].uidt = UITypes.SingleLineText
// override with UITypes.SingleSelect or UITypes.MultiSelect if applicable
Object.assign(this.tables[tableIdx].columns[columnIdx], extractMultiOrSingleSelectProps(this.columnValues[columnIdx]))
} else {
this.tables[tableIdx].columns[columnIdx].uidt = uidt
}
delete this.columnValues[columnIdx]
} else {
this.tables[tableIdx].columns[columnIdx].uidt = uidt
}
}
}
async _parseTableData(tableIdx: number, source: UploadFile | string, tn: string) {
return new Promise((resolve, reject) => {
const that = this
let steppers = 0
if (that.config.shouldImportData) {
that.progress(`Processing ${tn} data`)
steppers = 0
const parseSource = (this.config.importFromURL ? (source as string) : (source as UploadFile).originFileObj)!
parse(parseSource, {
download: that.config.importFromURL,
// worker: true,
skipEmptyLines: 'greedy',
step(row) {
steppers += 1
if (row && steppers >= +that.config.firstRowAsHeaders + 1) {
const rowData: Record<string, any> = {}
for (let columnIdx = 0; columnIdx < that.headers[tableIdx].length; columnIdx++) {
const column = that.tables[tableIdx].columns[columnIdx]
const data = (row.data as [])[columnIdx] === '' ? null : (row.data as [])[columnIdx]
if (column.uidt === UITypes.Checkbox) {
rowData[column.column_name] = getCheckboxValue(data)
} else if (column.uidt === UITypes.SingleSelect || column.uidt === UITypes.MultiSelect) {
rowData[column.column_name] = (data || '').toString().trim() || null
} else {
// TODO(import): do parsing if necessary based on type
rowData[column.column_name] = data
}
}
that.data[tn].push(rowData)
}
if (steppers % 1000 === 0) {
that.progress(`Processed ${steppers} rows of ${tn}`)
}
},
complete() {
that.progress(`Processed ${tn} data`)
resolve(true)
},
error(e: Error) {
reject(e)
},
})
} else {
resolve(true)
}
})
}
async _parseTableMeta(tableIdx: number, source: UploadFile | string) {
return new Promise((resolve, reject) => {
const that = this
let steppers = 0
const tn = ((this.config.importFromURL ? (source as string).split('/').pop() : (source as UploadFile).name) as string)
.replace(/[` ~!@#$%^&*()_|+\-=?;:'",.<>\{\}\[\]\\\/]/g, '_')
.trim()!
this.data[tn] = []
const parseSource = (this.config.importFromURL ? (source as string) : (source as UploadFile).originFileObj)!
parse(parseSource, {
download: that.config.importFromURL,
skipEmptyLines: 'greedy',
step(row) {
steppers += 1
if (row) {
if (steppers === 1) {
if (that.config.firstRowAsHeaders) {
// row.data is header
that.initTemplate(tableIdx, tn, row.data as [])
} else {
// use dummy column names as header
that.initTemplate(
tableIdx,
tn,
[...Array((row.data as []).length)].map((_, i) => `field_${i + 1}`),
)
if (that.config.autoSelectFieldTypes) {
// row.data is data
that.detectColumnType(tableIdx, row.data as [])
}
}
} else {
if (that.config.autoSelectFieldTypes) {
// row.data is data
that.detectColumnType(tableIdx, row.data as [])
}
}
}
},
async complete() {
that.updateTemplate(tableIdx)
that.base.tables.push(that.tables[tableIdx])
that.progress(`Processed ${tn} metadata`)
await that._parseTableData(tableIdx, source, tn)
resolve(true)
},
error(e: Error) {
reject(e)
},
})
})
}
async parse() {
if (this.config.importFromURL) {
await this._parseTableMeta(0, this.source as string)
} else {
await Promise.all(
(this.source as UploadFile[]).map((file: UploadFile, tableIdx: number) =>
(async (f, idx) => {
this.progress(`Parsing ${f.name}`)
await this._parseTableMeta(idx, f)
})(file, tableIdx),
),
)
}
}
getColumns() {
return this.base.tables.map((t: Record<string, any>) => t.columns)
}
getData() {
return this.data
}
getTemplate() {
return this.base
}
progress(msg: string) {
this.progressCallback?.(msg)
}
}
| packages/nc-gui/helpers/parsers/CSVTemplateAdapter.ts | 0 | https://github.com/nocodb/nocodb/commit/b862043ce25ff49926754ea05282a300278ec746 | [
0.0002991596411447972,
0.00017679377924650908,
0.00016703506116755307,
0.00017172111256513745,
0.000022398142391466536
] |
{
"id": 8,
"code_window": [
" readonly?: boolean\n",
"}\n",
"\n",
"const { value, item, column, showUnlinkButton, border = true, readonly: readonlyProp } = defineProps<Props>()\n",
"\n",
"const emit = defineEmits(['unlink'])\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
"const {\n",
" value,\n",
" item,\n",
" column,\n",
" showUnlinkButton,\n",
" border,\n",
" readonly: readonlyProp,\n",
"} = withDefaults(defineProps<Props>(), { border: true })\n"
],
"file_path": "packages/nc-gui/components/virtual-cell/components/ItemChip.vue",
"type": "replace",
"edit_start_line_idx": 24
} | <script setup lang="ts">
import dayjs from 'dayjs'
import {
ActiveCellInj,
EditColumnInj,
IsExpandedFormOpenInj,
ReadonlyInj,
computed,
inject,
onClickOutside,
ref,
useSelectedCellKeyupListener,
watch,
} from '#imports'
interface Props {
modelValue?: number | string | null
isPk?: boolean
}
const { modelValue, isPk = false } = defineProps<Props>()
const emit = defineEmits(['update:modelValue'])
const { showNull } = useGlobal()
const readOnly = inject(ReadonlyInj, ref(false))
const active = inject(ActiveCellInj, ref(false))
const editable = inject(EditModeInj, ref(false))
const isEditColumn = inject(EditColumnInj, ref(false))
const isExpandedFormOpen = inject(IsExpandedFormOpenInj, ref(false))!
const isYearInvalid = ref(false)
const { t } = useI18n()
const localState = computed({
get() {
if (!modelValue) {
return undefined
}
const yearDate = dayjs(modelValue.toString(), 'YYYY')
if (!yearDate.isValid()) {
isYearInvalid.value = true
return undefined
}
return yearDate
},
set(val?: dayjs.Dayjs) {
if (!val) {
emit('update:modelValue', null)
return
}
if (val?.isValid()) {
emit('update:modelValue', val.format('YYYY'))
}
},
})
const open = ref<boolean>(false)
const randomClass = `picker_${Math.floor(Math.random() * 99999)}`
watch(
open,
(next) => {
if (next) {
onClickOutside(document.querySelector(`.${randomClass}`)! as HTMLDivElement, () => (open.value = false))
} else {
editable.value = false
}
},
{ flush: 'post' },
)
const placeholder = computed(() => {
if (isEditColumn.value && (modelValue === '' || modelValue === null)) {
return t('labels.optional')
} else if (modelValue === null && showNull.value) {
return t('general.null')
} else if (isYearInvalid.value) {
return t('msg.invalidTime')
} else {
return ''
}
})
const isOpen = computed(() => {
if (readOnly.value) return false
return (readOnly.value || (localState.value && isPk)) && !active.value && !editable.value ? false : open.value
})
useSelectedCellKeyupListener(active, (e: KeyboardEvent) => {
switch (e.key) {
case 'Enter':
e.stopPropagation()
open.value = true
break
case 'Escape':
if (open.value) {
e.stopPropagation()
open.value = false
}
break
}
})
</script>
<template>
<a-date-picker
v-model:value="localState"
:tabindex="0"
picker="year"
:bordered="false"
class="!w-full !py-1 !border-none"
:class="{ 'nc-null': modelValue === null && showNull, '!px-2': isExpandedFormOpen, '!px-0': !isExpandedFormOpen }"
:placeholder="placeholder"
:allow-clear="(!readOnly && !localState && !isPk) || isEditColumn"
:input-read-only="true"
:open="isOpen"
:dropdown-class-name="`${randomClass} nc-picker-year children:border-1 children:border-gray-200 ${open ? 'active' : ''}`"
@click="open = (active || editable) && !open"
@change="open = (active || editable) && !open"
@ok="open = !open"
@keydown.enter="open = !open"
>
<template #suffixIcon></template>
</a-date-picker>
</template>
<style scoped>
:deep(.ant-picker-input > input[disabled]) {
@apply !text-current;
}
</style>
| packages/nc-gui/components/cell/YearPicker.vue | 1 | https://github.com/nocodb/nocodb/commit/b862043ce25ff49926754ea05282a300278ec746 | [
0.9264780282974243,
0.1187812015414238,
0.00016715185483917594,
0.0018529314547777176,
0.28944653272628784
] |
{
"id": 8,
"code_window": [
" readonly?: boolean\n",
"}\n",
"\n",
"const { value, item, column, showUnlinkButton, border = true, readonly: readonlyProp } = defineProps<Props>()\n",
"\n",
"const emit = defineEmits(['unlink'])\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
"const {\n",
" value,\n",
" item,\n",
" column,\n",
" showUnlinkButton,\n",
" border,\n",
" readonly: readonlyProp,\n",
"} = withDefaults(defineProps<Props>(), { border: true })\n"
],
"file_path": "packages/nc-gui/components/virtual-cell/components/ItemChip.vue",
"type": "replace",
"edit_start_line_idx": 24
} | import { FormulaDataTypes } from 'nocodb-sdk';
import type { MapFnArgs } from '../mapFunctionName';
import { NcError } from '~/helpers/catchError';
async function treatArgAsConditionalExp(
args: MapFnArgs,
argument = args.pt?.arguments?.[0],
) {
const condArg = (await args.fn(argument)).builder.toQuery();
let cond = condArg;
// based on the data type of the argument, we need to handle the condition
// if string - value is not null and not empty then true
// if number - value is not null and not 0 then true
// if boolean - value is not null and not false then true
// if date - value is not null then true
switch (argument.dataType as FormulaDataTypes) {
case FormulaDataTypes.NUMERIC:
cond = `(${condArg}) IS NOT NULL AND (${condArg}) != 0`;
break;
case FormulaDataTypes.STRING:
cond = `(${condArg}) IS NOT NULL AND (${condArg}) != ''`;
break;
case FormulaDataTypes.BOOLEAN:
cond = `(${condArg}) IS NOT NULL AND (${condArg}) != false`;
break;
case FormulaDataTypes.DATE:
cond = `(${condArg}) IS NOT NULL`;
break;
}
return { builder: args.knex.raw(cond) };
}
export default {
SWITCH: async (args: MapFnArgs) => {
const count = Math.floor((args.pt.arguments.length - 1) / 2);
let query = '';
const returnArgsType = new Set(
args.pt.arguments
.filter(
(type, i) => i > 1 && i % 2 === 0 && type !== FormulaDataTypes.NULL,
)
.map((type) => type.dataType),
);
// if else case present then push that to types
if (args.pt.arguments.length % 2 === 0) {
returnArgsType.add(
args.pt.arguments[args.pt.arguments.length - 1].dataType,
);
}
const switchVal = (await args.fn(args.pt.arguments[0])).builder.toQuery();
// used it for null value check
let elseValPrefix = '';
for (let i = 0; i < count; i++) {
let val;
// cast to string if the return value types are different
if (returnArgsType.size > 1) {
val = (
await args.fn({
type: 'CallExpression',
arguments: [args.pt.arguments[i * 2 + 2]],
callee: {
type: 'Identifier',
name: 'STRING',
},
} as any)
).builder.toQuery();
} else {
val = (await args.fn(args.pt.arguments[i * 2 + 2])).builder.toQuery();
}
if (
args.pt.arguments[i * 2 + 1].type === 'CallExpression' &&
args.pt.arguments[i * 2 + 1].callee?.name === 'BLANK'
) {
elseValPrefix += args.knex
.raw(
`\n\tWHEN ${switchVal} IS NULL ${
args.pt.arguments[i * 2 + 1].dataType === FormulaDataTypes.STRING
? `OR ${switchVal} = ''`
: ''
} THEN ${val}`,
)
.toQuery();
} else if (
args.pt.arguments[i * 2 + 1].dataType === FormulaDataTypes.NULL
) {
elseValPrefix += args.knex
.raw(`\n\tWHEN ${switchVal} IS NULL THEN ${val}`)
.toQuery();
} else {
query += args.knex
.raw(
`\n\tWHEN ${(
await args.fn(args.pt.arguments[i * 2 + 1])
).builder.toQuery()} THEN ${val}`,
)
.toQuery();
}
}
if (args.pt.arguments.length % 2 === 0) {
let val;
// cast to string if the return value types are different
if (returnArgsType.size > 1) {
val = (
await args.fn({
type: 'CallExpression',
arguments: [args.pt.arguments[args.pt.arguments.length - 1]],
callee: {
type: 'Identifier',
name: 'STRING',
},
} as any)
).builder.toQuery();
} else {
val = (
await args.fn(args.pt.arguments[args.pt.arguments.length - 1])
).builder.toQuery();
}
if (elseValPrefix) {
query += `\n\tELSE (CASE ${elseValPrefix} ELSE ${val} END)`;
} else {
query += `\n\tELSE ${val}`;
}
} else if (elseValPrefix) {
query += `\n\tELSE (CASE ${elseValPrefix} END)`;
}
return {
builder: args.knex.raw(
`CASE ${switchVal} ${query}\n END${args.colAlias}`,
),
};
},
IF: async (args: MapFnArgs) => {
const cond = (await treatArgAsConditionalExp(args)).builder;
let thenArg;
let elseArg;
const returnArgsType = new Set(
[args.pt.arguments[1].dataType, args.pt.arguments[2].dataType].filter(
(type) => type !== FormulaDataTypes.NULL,
),
);
// cast to string if the return value types are different
if (returnArgsType.size > 1) {
thenArg = (
await args.fn({
type: 'CallExpression',
arguments: [args.pt.arguments[1]],
callee: {
type: 'Identifier',
name: 'STRING',
},
} as any)
).builder;
elseArg = (
await args.fn({
type: 'CallExpression',
arguments: [args.pt.arguments[2]],
callee: {
type: 'Identifier',
name: 'STRING',
},
} as any)
).builder;
} else {
thenArg = (await args.fn(args.pt.arguments[1])).builder.toQuery();
elseArg = (await args.fn(args.pt.arguments[2])).builder.toQuery();
}
let query = args.knex.raw(`\n\tWHEN ${cond} THEN ${thenArg}`).toQuery();
if (args.pt.arguments[2]) {
query += args.knex.raw(`\n\tELSE ${elseArg}`).toQuery();
}
return { builder: args.knex.raw(`CASE ${query}\n END${args.colAlias}`) };
},
// used only for casting to string internally, this one is dummy function
// and will work as fallback for dbs which don't support/implemented CAST
STRING(args: MapFnArgs) {
return args.fn(args.pt?.arguments?.[0]);
},
AND: async (args: MapFnArgs) => {
return {
builder: args.knex.raw(
`${args.knex
.raw(
`${(
await Promise.all(
args.pt.arguments.map(async (ar) =>
(await treatArgAsConditionalExp(args, ar)).builder.toQuery(),
),
)
).join(' AND ')}`,
)
.wrap('(', ')')
.toQuery()}${args.colAlias}`,
),
};
},
OR: async (args: MapFnArgs) => {
return {
builder: args.knex.raw(
`${args.knex
.raw(
`${(
await Promise.all(
args.pt.arguments.map(async (ar) =>
(await treatArgAsConditionalExp(args, ar)).builder.toQuery(),
),
)
).join(' OR ')}`,
)
.wrap('(', ')')
.toQuery()}${args.colAlias}`,
),
};
},
AVG: async (args: MapFnArgs) => {
if (args.pt.arguments.length > 1) {
return args.fn(
{
type: 'BinaryExpression',
operator: '/',
left: { ...args.pt, callee: { name: 'SUM' } },
right: { type: 'Literal', value: args.pt.arguments.length },
},
args.a,
args.prevBinaryOp,
);
} else {
return args.fn(args.pt.arguments[0], args.a, args.prevBinaryOp);
}
},
FLOAT: async (args: MapFnArgs) => {
return {
builder: (await args.fn(args.pt?.arguments?.[0])).builder.wrap('(', ')'),
};
},
BLANK: async (args: MapFnArgs) => {
return { builder: args.knex.raw(`?`, [null]) };
},
TRUE: async (args: MapFnArgs) => {
return { builder: args.knex.raw(`?`, [1]) };
},
FALSE: async (args: MapFnArgs) => {
return { builder: args.knex.raw(`?`, [0]) };
},
EVEN: async (args: MapFnArgs) => {
const query = (await args.fn(args.pt.arguments[0])).builder;
return {
builder: args.knex.raw(
`CASE WHEN ${query} >= 0 THEN CEIL((${query}) / 2.0) * 2 \n ELSE FLOOR((${query} + 2) / 2.0) * 2 - 2\n END${args.colAlias}`,
),
};
},
ODD: async (args: MapFnArgs) => {
const query = (await args.fn(args.pt.arguments[0])).builder;
return {
builder: args.knex.raw(
`CASE WHEN ${query} >= 0 THEN CEIL((${query} - 1) / 2.0) * 2 + 1 \n ELSE FLOOR((${query} + 1) / 2.0) * 2 - 1\n END${args.colAlias}`,
),
};
},
RECORD_ID: async (args: MapFnArgs) => {
const pkCol = args.model?.primaryKey;
if (!pkCol) {
NcError.badRequest('Primary key not found');
}
return {
builder: args.knex.raw(
`${
(await args.fn({ type: 'Identifier', name: pkCol.id }, args.a))
.builder
} ${args.colAlias}`,
),
};
},
CREATED_TIME: async (args: MapFnArgs) => {
const createdAtCol = args.model?.columns?.find(
(col) => col.column_name === 'created_at',
);
if (!createdAtCol) {
NcError.badRequest('Created at field not found');
}
return {
builder: args.knex.raw(
`${
(await args.fn({ type: 'Identifier', name: createdAtCol.id }, args.a))
.builder
} ${args.colAlias}`,
),
};
},
LAST_MODIFIED_TIME: async (args: MapFnArgs) => {
const createdAtCol = args.model?.columns?.find(
(col) => col.column_name === 'updated_at',
);
if (!createdAtCol) {
NcError.badRequest('Updated at field not found');
}
return {
builder: args.knex.raw(
`${
(await args.fn({ type: 'Identifier', name: createdAtCol.id }, args.a))
.builder
} ${args.colAlias}`,
),
};
},
// todo: verify the behaviour of this function
COUNTALL: async ({ knex, pt, colAlias }: MapFnArgs) => {
return {
builder: knex.raw(`? ${colAlias}`, [pt.arguments.length]),
};
},
ROUNDDOWN: async ({ fn, knex, pt, colAlias }: MapFnArgs) => {
const { builder: valueBuilder } = await fn(pt.arguments[0]);
let precisionBuilder = knex.raw('0');
if (pt.arguments[1]) {
const { builder } = await fn(pt.arguments[1]);
precisionBuilder = builder;
}
return {
builder: knex.raw(
`(FLOOR((${valueBuilder}) * POWER(10, ${precisionBuilder})) / POWER(10, ${precisionBuilder}))${colAlias}`,
),
};
},
ROUNDUP: async ({ fn, knex, pt, colAlias }: MapFnArgs) => {
const { builder: valueBuilder } = await fn(pt.arguments[0]);
let precisionBuilder = knex.raw('0');
if (pt.arguments[1]) {
const { builder } = await fn(pt.arguments[1]);
precisionBuilder = builder;
}
return {
builder: knex.raw(
`(CEIL((${valueBuilder}) * POWER(10, ${precisionBuilder})) / POWER(10, ${precisionBuilder}))${colAlias}`,
),
};
},
ISBLANK: async ({ fn, knex, pt, colAlias }: MapFnArgs) => {
const { builder: valueBuilder } = await fn(pt.arguments[0]);
return {
builder: knex.raw(
`(${valueBuilder} IS NULL OR ${valueBuilder} = '')${colAlias}`,
),
};
},
ISNULL: async ({ fn, knex, pt, colAlias }: MapFnArgs) => {
const { builder: valueBuilder } = await fn(pt.arguments[0]);
return {
builder: knex.raw(`(${valueBuilder} IS NULL)${colAlias}`),
};
},
ISNOTBLANK: async ({ fn, knex, pt, colAlias }: MapFnArgs) => {
const { builder: valueBuilder } = await fn(pt.arguments[0]);
return {
builder: knex.raw(
`(${valueBuilder} IS NOT NULL AND ${valueBuilder} != '')${colAlias}`,
),
};
},
ISNOTNULL: async ({ fn, knex, pt, colAlias }: MapFnArgs) => {
const { builder: valueBuilder } = await fn(pt.arguments[0]);
return {
builder: knex.raw(`(${valueBuilder} IS NOT NULL)${colAlias}`),
};
},
};
| packages/nocodb/src/db/functionMappings/commonFns.ts | 0 | https://github.com/nocodb/nocodb/commit/b862043ce25ff49926754ea05282a300278ec746 | [
0.00536869652569294,
0.0003470435331109911,
0.00016595171473454684,
0.00017108781321439892,
0.0008473021443933249
] |
{
"id": 8,
"code_window": [
" readonly?: boolean\n",
"}\n",
"\n",
"const { value, item, column, showUnlinkButton, border = true, readonly: readonlyProp } = defineProps<Props>()\n",
"\n",
"const emit = defineEmits(['unlink'])\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
"const {\n",
" value,\n",
" item,\n",
" column,\n",
" showUnlinkButton,\n",
" border,\n",
" readonly: readonlyProp,\n",
"} = withDefaults(defineProps<Props>(), { border: true })\n"
],
"file_path": "packages/nc-gui/components/virtual-cell/components/ItemChip.vue",
"type": "replace",
"edit_start_line_idx": 24
} | import { jsepTreeToFormula } from 'nocodb-sdk';
export default function (args: {
virtualColumns;
oldColumnName: string;
newColumnName: string;
}): void | boolean {
let modified = false;
const fn = (pt) => {
if (pt.type === 'CallExpression') {
pt.arguments.map((arg) => fn(arg));
} else if (pt.type === 'Literal') {
} else if (pt.type === 'Identifier') {
if (pt.name === args.oldColumnName) {
pt.name = args.newColumnName;
modified = true;
}
} else if (pt.type === 'BinaryExpression') {
fn(pt.left);
fn(pt.right);
}
};
if (!args.virtualColumns) {
return;
}
for (const v of args.virtualColumns) {
if (!v.formula?.tree) {
continue;
}
fn(v.formula.tree);
v.formula.value = jsepTreeToFormula(v.formula.tree);
}
return modified;
}
| packages/nocodb/src/utils/common/helpers/updateColumnNameInFormula.ts | 0 | https://github.com/nocodb/nocodb/commit/b862043ce25ff49926754ea05282a300278ec746 | [
0.00017610758368391544,
0.00017266054055653512,
0.00016778611461631954,
0.00017337421013507992,
0.0000030279306884040125
] |
{
"id": 8,
"code_window": [
" readonly?: boolean\n",
"}\n",
"\n",
"const { value, item, column, showUnlinkButton, border = true, readonly: readonlyProp } = defineProps<Props>()\n",
"\n",
"const emit = defineEmits(['unlink'])\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
"const {\n",
" value,\n",
" item,\n",
" column,\n",
" showUnlinkButton,\n",
" border,\n",
" readonly: readonlyProp,\n",
"} = withDefaults(defineProps<Props>(), { border: true })\n"
],
"file_path": "packages/nc-gui/components/virtual-cell/components/ItemChip.vue",
"type": "replace",
"edit_start_line_idx": 24
} | var should = require('chai').should();
var expect = require('chai').expect;
var knex = require('../build/main/lib/sql/CustomKnex').default({
client: 'mysql2'
});
const cstomKnex = require('../build/main/lib/sql/CustomKnex').default;
[{
condition: {a: {eq: "test"}, _and: [{test: {eq: 1}}]},
expect: 'select * from `test` where `a` = \'test\' and ((`test` = 1))'
},
{
condition: {
_not: {
title: {
eq: '123'
}
}
},
expect: 'select * from `test` where not (`title` = \'123\')'
}
]
.forEach(({condition, expect}, i) => {
it(`Test case : ${i} - ${JSON.stringify(condition)}`, function (done) {
const res = knex('test').condition(condition).toQuery();
console.log(res)
res.should.be.equal(expect)
done();
});
})
it(`Test`, function (done) {
const res = knex('test').conditionGraph({
_not: {
title: {
eq: '123'
}
}
}, {}).toQuery();
res.should.be.equal('select * from `test` where not (`test`.`title` = \'123\')');
const res1 = knex('test').conditionGraph({
test1: {
relationType: "hm",
test3: {
relationType: "bt",
test3Col: {
eq: "123"
}
}
}
}, {
test: {
hasMany: [{
"tn": "test1",
"cn": "test_ref_id",
"rtn": "test",
"rcn": "test_id"
}]
},
test1: {
belongsTo: [{
"tn": "test1",
"cn": "test_ref_id",
"rtn": "test",
"rcn": "test_id"
}, {
"tn": "test1",
"cn": "test3_ref_id",
"rtn": "test3",
"rcn": "test3_id"
}],
}
}).toQuery();
res1.should.be.equal('select * from `test` inner join `test1` on `test1`.`test_ref_id` = `test`.`test_id` inner join `test3` on `test1`.`test3_ref_id` = `test3`.`test3_id` where `test3`.`test3Col` = \'123\'')
done();
});
[{
knex: cstomKnex({
client: 'mysql2'
}),
expectedOp : 'select * from `test` inner join `test1` on `test1`.`test_ref_id` = `test`.`test_id` inner join `test3` on `test1`.`test3_ref_id` = `test3`.`test3_id` where `test3`.`test3Col` = \'123\''
},
{
knex :cstomKnex({
client: 'pg'
}),
expectedOp :'select * from "test" inner join "test1" on "test1"."test_ref_id" = "test"."test_id" inner join "test3" on "test1"."test3_ref_id" = "test3"."test3_id" where "test3"."test3Col" = \'123\''
},
{
knex :cstomKnex({
client: 'mssql'
}),
expectedOp: 'select * from [test] inner join [test1] on [test1].[test_ref_id] = [test].[test_id] inner join [test3] on [test1].[test3_ref_id] = [test3].[test3_id] where [test3].[test3Col] = \'123\''
},
{
knex :cstomKnex({
client: 'sqlite3'
}),
expectedOp: 'select * from `test` inner join `test1` on `test1`.`test_ref_id` = `test`.`test_id` inner join `test3` on `test1`.`test3_ref_id` = `test3`.`test3_id` where `test3`.`test3Col` = \'123\''
},
{
knex :cstomKnex({
client: 'oracledb'
}),
expectedOp: 'select * from "test" inner join "test1" on "test1"."test_ref_id" = "test"."test_id" inner join "test3" on "test1"."test3_ref_id" = "test3"."test3_id" where "test3"."test3Col" = \'123\''
}].forEach(({knex,expectedOp}) => {
it(`Nested condition`, function (done) {
const res = knex('test').conditionGraph({
condition: {
test1: {
// relationType: "hm",
// test3: {
// relationType: "bt",
// test3Col: {
// eq: "123"
// }
// }
}
}
, models: {
test: {
hasManyRelations: [{
"tn": "test1",
"cn": "test_ref_id",
"rtn": "test",
"rcn": "test_id"
}]
},
test1: {
belongsToRelations: [{
"tn": "test1",
"cn": "test_ref_id",
"rtn": "test",
"rcn": "test_id"
}, {
"tn": "test1",
"cn": "test3_ref_id",
"rtn": "test3",
"rcn": "test3_id"
}],
}
}
}).toQuery();
res.should.be.equal(expectedOp);
done();
});
}); | packages/nocodb/src/db/sql-data-mapper/__tests__/conditionClause.test.js | 0 | https://github.com/nocodb/nocodb/commit/b862043ce25ff49926754ea05282a300278ec746 | [
0.0001729855575831607,
0.000171159059391357,
0.00016877532470971346,
0.00017154193483293056,
0.0000013296908036863897
] |
{
"id": 9,
"code_window": [
"interface Props {\n",
" bases?: BaseType[]\n",
"}\n",
"\n",
"const { bases = [] } = defineProps<Props>()\n",
"\n",
"const emit = defineEmits(['delete-base'])\n",
"\n",
"const { $e } = useNuxtApp()\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"const { bases } = withDefaults(defineProps<Props>(), {\n",
" bases: () => [],\n",
"})\n"
],
"file_path": "packages/nc-gui/pages/projects/index/index.vue",
"type": "replace",
"edit_start_line_idx": 8
} | <script lang="ts" setup>
import type { ColumnType } from 'nocodb-sdk'
import { UITypes, isVirtualCol } from 'nocodb-sdk'
import {
ActiveCellInj,
IsFormInj,
ReadonlyInj,
iconMap,
inject,
isAttachment,
ref,
useExpandedFormDetached,
useLTARStoreOrThrow,
} from '#imports'
interface Props {
value: string | number | boolean
item: any
column: any
showUnlinkButton?: boolean
border?: boolean
readonly?: boolean
}
const { value, item, column, showUnlinkButton, border = true, readonly: readonlyProp } = defineProps<Props>()
const emit = defineEmits(['unlink'])
const { relatedTableMeta } = useLTARStoreOrThrow()!
const { isUIAllowed } = useRoles()
const readOnly = inject(ReadonlyInj, ref(false))
const active = inject(ActiveCellInj, ref(false))
const isForm = inject(IsFormInj)!
const { open } = useExpandedFormDetached()
function openExpandedForm() {
const rowId = extractPkFromRow(item, relatedTableMeta.value.columns as ColumnType[])
if (!readOnly.value && !readonlyProp && rowId) {
open({
isOpen: true,
row: { row: item, rowMeta: {}, oldRow: { ...item } },
meta: relatedTableMeta.value,
rowId,
useMetaFields: true,
})
}
}
</script>
<script lang="ts">
export default {
name: 'ItemChip',
}
</script>
<template>
<div
v-e="['c:row-expand:open']"
class="chip group mr-1 my-1 flex items-center rounded-[2px] flex-row"
:class="{ active, 'border-1 py-1 px-2': isAttachment(column) }"
@click="openExpandedForm"
>
<span class="name">
<!-- Render virtual cell -->
<div v-if="isVirtualCol(column)">
<template v-if="column.uidt === UITypes.LinkToAnotherRecord">
<LazySmartsheetVirtualCell :edit-enabled="false" :model-value="value" :column="column" :read-only="true" />
</template>
<LazySmartsheetVirtualCell v-else :edit-enabled="false" :read-only="true" :model-value="value" :column="column" />
</div>
<!-- Render normal cell -->
<template v-else>
<div v-if="isAttachment(column) && value && !Array.isArray(value) && typeof value === 'object'">
<LazySmartsheetCell :model-value="value" :column="column" :edit-enabled="false" :read-only="true" />
</div>
<!-- For attachment cell avoid adding chip style -->
<template v-else>
<div
class="min-w-max"
:class="{
'px-1 rounded-full flex-1': !isAttachment(column),
'border-gray-200 rounded border-1':
border && ![UITypes.Attachment, UITypes.MultiSelect, UITypes.SingleSelect].includes(column.uidt),
}"
>
<LazySmartsheetCell :model-value="value" :column="column" :edit-enabled="false" :virtual="true" :read-only="true" />
</div>
</template>
</template>
</span>
<div v-show="active || isForm" v-if="showUnlinkButton && !readOnly && isUIAllowed('dataEdit')" class="flex items-center">
<component
:is="iconMap.closeThick"
class="nc-icon unlink-icon text-xs text-gray-500/50 group-hover:text-gray-500"
@click.stop="emit('unlink')"
/>
</div>
</div>
</template>
<style scoped lang="scss">
.chip {
max-width: max(100%, 60px);
.name {
text-overflow: ellipsis;
overflow: hidden;
white-space: nowrap;
}
}
</style>
| packages/nc-gui/components/virtual-cell/components/ItemChip.vue | 1 | https://github.com/nocodb/nocodb/commit/b862043ce25ff49926754ea05282a300278ec746 | [
0.961933434009552,
0.08084036409854889,
0.00016723904991522431,
0.00017177333938889205,
0.2656651735305786
] |
{
"id": 9,
"code_window": [
"interface Props {\n",
" bases?: BaseType[]\n",
"}\n",
"\n",
"const { bases = [] } = defineProps<Props>()\n",
"\n",
"const emit = defineEmits(['delete-base'])\n",
"\n",
"const { $e } = useNuxtApp()\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"const { bases } = withDefaults(defineProps<Props>(), {\n",
" bases: () => [],\n",
"})\n"
],
"file_path": "packages/nc-gui/pages/projects/index/index.vue",
"type": "replace",
"edit_start_line_idx": 8
} | import type { BaseType, ColumnType, FilterType, MetaType, PaginatedType, Roles, RolesObj, TableType, ViewTypes } from 'nocodb-sdk'
import type { I18n } from 'vue-i18n'
import type { Theme as AntTheme } from 'ant-design-vue/es/config-provider'
import type { UploadFile } from 'ant-design-vue'
import type { ImportSource, ImportType, TabType } from './enums'
import type { rolePermissions } from './acl'
interface User {
id: string
email: string
firstname: string | null
lastname: string | null
roles: RolesObj
base_roles: RolesObj
workspace_roles: RolesObj
invite_token?: string
base_id?: string
display_name?: string | null
}
interface ProjectMetaInfo {
Node?: string
Arch?: string
Platform?: string
Docker?: boolean
Database?: string
ProjectOnRootDB?: boolean
RootDB?: string
PackageVersion?: string
}
interface Field {
order: number
show: number | boolean
title: string
fk_column_id?: string
system?: boolean
isViewEssentialField?: boolean
}
type Filter = FilterType & {
field?: string
status?: 'update' | 'delete' | 'create'
parentId?: string
readOnly?: boolean
}
type NocoI18n = I18n<{}, unknown, unknown, string, false>
interface ThemeConfig extends AntTheme {
primaryColor: string
accentColor: string
}
interface Row {
row: Record<string, any>
oldRow: Record<string, any>
rowMeta: {
new?: boolean
selected?: boolean
commentCount?: number
changed?: boolean
saving?: boolean
// use in datetime picker component
isUpdatedFromCopyNPaste?: Record<string, boolean>
}
}
type RolePermissions = Omit<typeof rolePermissions, 'guest' | 'admin' | 'super'>
type GetKeys<T> = T extends Record<any, Record<infer Key, boolean>> ? Key : never
type Permission<K extends keyof RolePermissions = keyof RolePermissions> = RolePermissions[K] extends Record<any, any>
? GetKeys<RolePermissions[K]>
: never
interface TabItem {
type: TabType
title: string
id?: string
viewTitle?: string
viewId?: string
sortsState?: Map<string, any>
filterState?: Map<string, any>
meta?: MetaType
tabMeta?: any
baseId?: string
}
interface SharedViewMeta extends Record<string, any> {
surveyMode?: boolean
transitionDuration?: number // in ms
withTheme?: boolean
theme?: Partial<ThemeConfig>
allowCSVDownload?: boolean
rtl?: boolean
}
interface SharedView {
uuid?: string
id: string
password?: string
type?: ViewTypes
meta: SharedViewMeta
}
type importFileList = (UploadFile & { data: string | ArrayBuffer })[]
type streamImportFileList = UploadFile[]
type Nullable<T> = { [K in keyof T]: T[K] | null }
/**
* @description: Base type for frontend
*/
type NcProject = BaseType & {
/**
* When base is expanded in sidebar
* */
isExpanded?: boolean
/**
* When base's content is being fetched i.e tables, views, etc
*/
isLoading?: boolean
temp_title?: string
edit?: boolean
starred?: boolean
uuid?: string
users?: User[]
}
interface UndoRedoAction {
undo: { fn: Function; args: any[] }
redo: { fn: Function; args: any[] }
scope?: { key: string; param: string | string[] }[]
}
interface ImportWorkerPayload {
importType: ImportType
importSource: ImportSource
value: any
config: Record<string, any>
}
interface Group {
key: string
column: ColumnType
color: string
count: number
nestedIn: GroupNestedIn[]
paginationData: PaginatedType
nested: boolean
children?: Group[]
rows?: Row[]
root?: boolean
}
interface GroupNestedIn {
title: string
column_name: string
key: string
column_uidt: string
}
interface Users {
emails?: string
role: Roles
invitationToken?: string
}
type ViewPageType = 'view' | 'webhook' | 'api' | 'field' | 'relation'
type NcButtonSize = 'xxsmall' | 'xsmall' | 'small' | 'medium'
interface SidebarTableNode extends TableType {
isMetaLoading?: boolean
isViewsLoading?: boolean
}
interface UsersSortType {
field?: 'email' | 'roles'
direction?: 'asc' | 'desc'
}
export type {
User,
ProjectMetaInfo,
Field,
Filter,
NocoI18n,
ThemeConfig,
Row,
RolePermissions,
Permission,
TabItem,
SharedView,
SharedViewMeta,
importFileList,
streamImportFileList,
Nullable,
NcProject,
UndoRedoAction,
ImportWorkerPayload,
Group,
GroupNestedIn,
Users,
ViewPageType,
NcButtonSize,
SidebarTableNode,
UsersSortType,
}
| packages/nc-gui/lib/types.ts | 0 | https://github.com/nocodb/nocodb/commit/b862043ce25ff49926754ea05282a300278ec746 | [
0.0006708793807774782,
0.0002122987061738968,
0.00016676055383868515,
0.00017233678954653442,
0.00011284509673714638
] |
{
"id": 9,
"code_window": [
"interface Props {\n",
" bases?: BaseType[]\n",
"}\n",
"\n",
"const { bases = [] } = defineProps<Props>()\n",
"\n",
"const emit = defineEmits(['delete-base'])\n",
"\n",
"const { $e } = useNuxtApp()\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"const { bases } = withDefaults(defineProps<Props>(), {\n",
" bases: () => [],\n",
"})\n"
],
"file_path": "packages/nc-gui/pages/projects/index/index.vue",
"type": "replace",
"edit_start_line_idx": 8
} | ---
title: 'Duration'
description: 'This article explains how to create & work with a Duration field.'
tags: ['Fields', 'Field types', 'Date & Time']
keywords: ['Fields', 'Field types', 'Date & Time', 'Create duration field']
---
`Duration` field type is used to store duration of time in seconds or minutes. Different formats are supported by NocoDB, as detailed in the table below.
## Create a duration field
1. Click on `+` icon to the right of `Fields header`
2. On the dropdown modal, enter the field name (Optional).
3. Select the field type as `Duration` from the dropdown.
4. Configure `Duration Format`
5. Configure default value (Optional)
6. Click on `Save Field` button.

### Supported duration formats
| Format | Example |
|--------------|--------------|
| HH:mm | 14:20 |
| HH:mm:ss | 12:45:30 |
| HH:mm:ss.s | 12:45:30.5 |
| HH:mm.ss.ss | 12:45.30.50 |
| HH:mm.ss.sss | 12:45.30.500 |
## Related fields
- [DateTime](010.date-time.md)
- [Date](020.date.md)
- [Time](030.time.md)
| packages/noco-docs/docs/070.fields/040.field-types/070.date-time-based/040.duration.md | 0 | https://github.com/nocodb/nocodb/commit/b862043ce25ff49926754ea05282a300278ec746 | [
0.00017396612383890897,
0.00017086646403186023,
0.00016716413665562868,
0.00017116781964432448,
0.000002554358388806577
] |
{
"id": 9,
"code_window": [
"interface Props {\n",
" bases?: BaseType[]\n",
"}\n",
"\n",
"const { bases = [] } = defineProps<Props>()\n",
"\n",
"const emit = defineEmits(['delete-base'])\n",
"\n",
"const { $e } = useNuxtApp()\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"const { bases } = withDefaults(defineProps<Props>(), {\n",
" bases: () => [],\n",
"})\n"
],
"file_path": "packages/nc-gui/pages/projects/index/index.vue",
"type": "replace",
"edit_start_line_idx": 8
} | html {
font-size: 16px;
word-spacing: 1px;
-ms-text-size-adjust: 100%;
-webkit-text-size-adjust: 100%;
-moz-osx-font-smoothing: grayscale;
-webkit-font-smoothing: antialiased;
box-sizing: border-box;
}
body , * {
font-family: Manrope, 'Inter', 'Source Sans Pro', -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial,
sans-serif;
}
/*
Apply Manrope for rtl
*/
.rtl .v-application *:not(.material-icons) {
font-family: Manrope !important;
}
.rtl .v-application .ml-n1 {
margin-left: 0px !important;
}
/*
For Drag and Drop
*/
.grabbing * {
cursor: grabbing;
}
.flex.hidden {
display: none;
} | packages/nc-gui/assets/css/global.css | 0 | https://github.com/nocodb/nocodb/commit/b862043ce25ff49926754ea05282a300278ec746 | [
0.00017273931007366627,
0.00016912861610762775,
0.00016720875282771885,
0.00016828320804052055,
0.0000021303953872120474
] |
{
"id": 10,
"code_window": [
" bases?: BaseType[]\n",
"}\n",
"\n",
"const { bases = [] } = defineProps<Props>()\n",
"\n",
"const emit = defineEmits(['delete-base'])\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
"const { bases } = withDefaults(defineProps<Props>(), {\n",
" bases: () => [],\n",
"})\n"
],
"file_path": "packages/nc-gui/pages/projects/index/list.vue",
"type": "replace",
"edit_start_line_idx": 8
} | <script lang="ts" setup>
import type { ColumnType } from 'nocodb-sdk'
import { UITypes, isVirtualCol } from 'nocodb-sdk'
import {
ActiveCellInj,
IsFormInj,
ReadonlyInj,
iconMap,
inject,
isAttachment,
ref,
useExpandedFormDetached,
useLTARStoreOrThrow,
} from '#imports'
interface Props {
value: string | number | boolean
item: any
column: any
showUnlinkButton?: boolean
border?: boolean
readonly?: boolean
}
const { value, item, column, showUnlinkButton, border = true, readonly: readonlyProp } = defineProps<Props>()
const emit = defineEmits(['unlink'])
const { relatedTableMeta } = useLTARStoreOrThrow()!
const { isUIAllowed } = useRoles()
const readOnly = inject(ReadonlyInj, ref(false))
const active = inject(ActiveCellInj, ref(false))
const isForm = inject(IsFormInj)!
const { open } = useExpandedFormDetached()
function openExpandedForm() {
const rowId = extractPkFromRow(item, relatedTableMeta.value.columns as ColumnType[])
if (!readOnly.value && !readonlyProp && rowId) {
open({
isOpen: true,
row: { row: item, rowMeta: {}, oldRow: { ...item } },
meta: relatedTableMeta.value,
rowId,
useMetaFields: true,
})
}
}
</script>
<script lang="ts">
export default {
name: 'ItemChip',
}
</script>
<template>
<div
v-e="['c:row-expand:open']"
class="chip group mr-1 my-1 flex items-center rounded-[2px] flex-row"
:class="{ active, 'border-1 py-1 px-2': isAttachment(column) }"
@click="openExpandedForm"
>
<span class="name">
<!-- Render virtual cell -->
<div v-if="isVirtualCol(column)">
<template v-if="column.uidt === UITypes.LinkToAnotherRecord">
<LazySmartsheetVirtualCell :edit-enabled="false" :model-value="value" :column="column" :read-only="true" />
</template>
<LazySmartsheetVirtualCell v-else :edit-enabled="false" :read-only="true" :model-value="value" :column="column" />
</div>
<!-- Render normal cell -->
<template v-else>
<div v-if="isAttachment(column) && value && !Array.isArray(value) && typeof value === 'object'">
<LazySmartsheetCell :model-value="value" :column="column" :edit-enabled="false" :read-only="true" />
</div>
<!-- For attachment cell avoid adding chip style -->
<template v-else>
<div
class="min-w-max"
:class="{
'px-1 rounded-full flex-1': !isAttachment(column),
'border-gray-200 rounded border-1':
border && ![UITypes.Attachment, UITypes.MultiSelect, UITypes.SingleSelect].includes(column.uidt),
}"
>
<LazySmartsheetCell :model-value="value" :column="column" :edit-enabled="false" :virtual="true" :read-only="true" />
</div>
</template>
</template>
</span>
<div v-show="active || isForm" v-if="showUnlinkButton && !readOnly && isUIAllowed('dataEdit')" class="flex items-center">
<component
:is="iconMap.closeThick"
class="nc-icon unlink-icon text-xs text-gray-500/50 group-hover:text-gray-500"
@click.stop="emit('unlink')"
/>
</div>
</div>
</template>
<style scoped lang="scss">
.chip {
max-width: max(100%, 60px);
.name {
text-overflow: ellipsis;
overflow: hidden;
white-space: nowrap;
}
}
</style>
| packages/nc-gui/components/virtual-cell/components/ItemChip.vue | 1 | https://github.com/nocodb/nocodb/commit/b862043ce25ff49926754ea05282a300278ec746 | [
0.042459238320589066,
0.004185851197689772,
0.00016471624257974327,
0.0001724709727568552,
0.011649146676063538
] |
{
"id": 10,
"code_window": [
" bases?: BaseType[]\n",
"}\n",
"\n",
"const { bases = [] } = defineProps<Props>()\n",
"\n",
"const emit = defineEmits(['delete-base'])\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
"const { bases } = withDefaults(defineProps<Props>(), {\n",
" bases: () => [],\n",
"})\n"
],
"file_path": "packages/nc-gui/pages/projects/index/list.vue",
"type": "replace",
"edit_start_line_idx": 8
} | import { expect } from '@playwright/test';
import BasePage from '../../Base';
import { DataSourcePage } from './DataSourcePage';
export class AuditPage extends BasePage {
constructor(dataSource: DataSourcePage) {
super(dataSource.rootPage);
}
get() {
return this.rootPage.locator('div.ant-modal-content');
}
async verifyRow({
index,
opType,
opSubtype,
description,
user,
created,
}: {
index: number;
opType?: string;
opSubtype?: string;
description?: string;
user?: string;
created?: string;
}) {
const table = this.get().locator('[data-testid="audit-tab-table"]');
const row = table.locator(`tr.ant-table-row`).nth(index);
if (opType) {
await row
.locator(`td.ant-table-cell`)
.nth(0)
.textContent()
.then(async text => expect(text).toContain(opType));
}
if (opSubtype) {
await row
.locator(`td.ant-table-cell`)
.nth(1)
.textContent()
.then(async text => expect(text).toContain(opSubtype));
}
if (description) {
await row
.locator(`td.ant-table-cell`)
.nth(2)
.textContent()
.then(async text => expect(text).toContain(description));
}
if (user) {
await row
.locator(`td.ant-table-cell`)
.nth(3)
.textContent()
.then(async text => expect(text).toContain(user));
}
if (created) {
await row
.locator(`td.ant-table-cell`)
.nth(4)
.textContent()
.then(async text => expect(text).toContain(created));
}
}
async close() {
await this.get().click();
await this.rootPage.keyboard.press('Escape');
}
}
| tests/playwright/pages/Dashboard/ProjectView/Audit.ts | 0 | https://github.com/nocodb/nocodb/commit/b862043ce25ff49926754ea05282a300278ec746 | [
0.0001747861533658579,
0.00017271966498810798,
0.00016960744687821716,
0.0001730247458908707,
0.000001504896090409602
] |
{
"id": 10,
"code_window": [
" bases?: BaseType[]\n",
"}\n",
"\n",
"const { bases = [] } = defineProps<Props>()\n",
"\n",
"const emit = defineEmits(['delete-base'])\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
"const { bases } = withDefaults(defineProps<Props>(), {\n",
" bases: () => [],\n",
"})\n"
],
"file_path": "packages/nc-gui/pages/projects/index/list.vue",
"type": "replace",
"edit_start_line_idx": 8
} | <script setup lang="ts">
import { computed, isDrawerOrModalExist, isMac, useNuxtApp, useSidebar } from '#imports'
const rightSidebar = useSidebar('nc-right-sidebar')
const leftSidebar = useSidebar('nc-left-sidebar')
const { $e } = useNuxtApp()
const isSidebarsOpen = computed({
get: () => rightSidebar.isOpen.value || leftSidebar.isOpen.value,
set: (value) => {
rightSidebar.toggle(value)
leftSidebar.toggle(value)
},
})
useEventListener(document, 'keydown', async (e: KeyboardEvent) => {
const cmdOrCtrl = isMac() ? e.metaKey : e.ctrlKey
if (e.altKey && !e.shiftKey && !cmdOrCtrl) {
switch (e.keyCode) {
case 70: {
// ALT + F
if (!isDrawerOrModalExist()) {
$e('c:shortcut', { key: 'ALT + F' })
isSidebarsOpen.value = !isSidebarsOpen.value
}
break
}
}
}
})
</script>
<template>
<a-tooltip placement="left">
<template #title>
<span class="text-xs">{{ isSidebarsOpen ? $t('activity.fullWidth') : $t('activity.exitFullWidth') }}</span>
</template>
<div
v-e="['c:toolbar:fullscreen']"
class="nc-fullscreen-btn cursor-pointer flex align-center self-center px-2 py-2 mr-2"
@click="isSidebarsOpen = !isSidebarsOpen"
>
<IcTwotoneWidthFull v-if="isSidebarsOpen" class="text-gray-300" />
<IcTwotoneWidthNormal v-else class="text-gray-300" />
</div>
</a-tooltip>
</template>
| packages/nc-gui/components/general/FullScreen.vue | 0 | https://github.com/nocodb/nocodb/commit/b862043ce25ff49926754ea05282a300278ec746 | [
0.00017502265109214932,
0.0001733106910251081,
0.00017126671446021646,
0.0001739607978379354,
0.0000013581769735537819
] |
{
"id": 10,
"code_window": [
" bases?: BaseType[]\n",
"}\n",
"\n",
"const { bases = [] } = defineProps<Props>()\n",
"\n",
"const emit = defineEmits(['delete-base'])\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
"const { bases } = withDefaults(defineProps<Props>(), {\n",
" bases: () => [],\n",
"})\n"
],
"file_path": "packages/nc-gui/pages/projects/index/list.vue",
"type": "replace",
"edit_start_line_idx": 8
} | import { expect, test } from '@playwright/test';
import setup, { NcContext, unsetup } from '../../../setup';
import { DashboardPage } from '../../../pages/Dashboard';
import { Api } from 'nocodb-sdk';
import { createDemoTable } from '../../../setup/demoTable';
interface paramsType {
dashboard: DashboardPage;
context: NcContext;
api: Api<any>;
table: any;
}
async function dragDrop({
firstColumn,
lastColumn,
params,
}: {
firstColumn: string;
lastColumn: string;
params: paramsType;
}) {
await params.dashboard.grid.cell.get({ index: 0, columnHeader: firstColumn }).click();
await params.dashboard.rootPage.keyboard.press(
(await params.dashboard.grid.isMacOs()) ? 'Meta+Shift+ArrowRight' : 'Control+Shift+ArrowRight'
);
// get fill handle locator
const src = await params.dashboard.rootPage.locator(`.nc-fill-handle`);
const dst = await params.dashboard.grid.cell.get({ index: 3, columnHeader: lastColumn });
// drag and drop
await src.dragTo(dst);
}
async function beforeEachInit({ page, tableType }: { page: any; tableType: string }) {
const context = await setup({ page, isEmptyProject: true });
const dashboard = new DashboardPage(page, context.base);
const api = new Api({
baseURL: `http://localhost:8080/`,
headers: {
'xc-auth': context.token,
},
});
const table = await createDemoTable({ context, type: tableType, recordCnt: 10 });
await page.reload();
await dashboard.treeView.openTable({ title: tableType });
return { dashboard, context, api, table } as paramsType;
}
test.describe('Fill Handle', () => {
let p: paramsType;
test.beforeEach(async ({ page }) => {
p = await beforeEachInit({ page, tableType: 'textBased' });
});
test.afterEach(async () => {
await unsetup(p.context);
});
test('Text based', async () => {
const fields = [
{ title: 'SingleLineText', value: 'Afghanistan', type: 'text' },
{ title: 'Email', value: '[email protected]', type: 'text' },
{ title: 'PhoneNumber', value: '1-541-754-3010', type: 'text' },
{ title: 'URL', value: 'https://www.google.com', type: 'text' },
{ title: 'MultiLineText', value: 'Aberdeen, United Kingdom', type: 'longText' },
];
await dragDrop({ firstColumn: 'SingleLineText', lastColumn: 'URL', params: p });
// verify data on grid (verifying just two rows)
for (let i = 0; i < fields.length; i++) {
for (let j = 0; j < 4; j++) {
await p.dashboard.grid.cell.verify({ index: j, columnHeader: fields[i].title, value: fields[i].value });
}
}
// verify api response
const updatedRecords = (await p.api.dbTableRow.list('noco', p.context.base.id, p.table.id, { limit: 4 })).list;
for (let i = 0; i < updatedRecords.length; i++) {
for (let j = 0; j < fields.length; j++) {
expect(updatedRecords[i][fields[j].title]).toEqual(fields[j].value);
}
}
});
});
test.describe('Fill Handle', () => {
let p: paramsType;
test.beforeEach(async ({ page }) => {
p = await beforeEachInit({ page, tableType: 'numberBased' });
});
test.afterEach(async () => {
await unsetup(p.context);
});
test('Number based', async () => {
const fields = [
{ title: 'Number', value: 33, type: 'text' },
{ title: 'Decimal', value: 33.3, type: 'text' },
{ title: 'Currency', value: 33.3, type: 'text' },
{ title: 'Percent', value: 33, type: 'text' },
{ title: 'Duration', value: '00:01', type: 'text' },
{ title: 'Rating', value: 3, type: 'rating' },
{ title: 'Year', value: '2023', type: 'year' },
{ title: 'Time', value: '02:02', type: 'time' },
];
// kludge: insert time from browser until mysql issue with timezone is fixed
await p.dashboard.grid.cell.time.set({ index: 0, columnHeader: 'Time', value: '02:02' });
// set rating for first record
await p.dashboard.grid.cell.rating.select({ index: 0, columnHeader: 'Rating', rating: 2 });
await dragDrop({ firstColumn: 'Number', lastColumn: 'Time', params: p });
// verify data on grid
for (let i = 0; i < fields.length; i++) {
for (let j = 0; j < 4; j++) {
if (fields[i].type === 'rating') {
await p.dashboard.grid.cell.rating.verify({
index: j,
columnHeader: fields[i].title,
rating: +fields[i].value,
});
} else if (fields[i].type === 'year') {
await p.dashboard.grid.cell.year.verify({ index: j, columnHeader: fields[i].title, value: +fields[i].value });
} else if (fields[i].type === 'time') {
await p.dashboard.grid.cell.time.verify({ index: j, columnHeader: fields[i].title, value: fields[i].value });
} else {
await p.dashboard.grid.cell.verify({ index: j, columnHeader: fields[i].title, value: fields[i].value });
}
}
}
// verify api response
// duration in seconds
const APIResponse = [33, 33.3, 33.3, 33, 60, 3, 2023, '02:02:00'];
const updatedRecords = (await p.api.dbTableRow.list('noco', p.context.base.id, p.table.id, { limit: 4 })).list;
for (let i = 0; i < updatedRecords.length; i++) {
for (let j = 0; j < fields.length; j++) {
if (fields[j].title === 'Time') {
expect(updatedRecords[i][fields[j].title]).toContain(APIResponse[j]);
} else {
expect(+updatedRecords[i][fields[j].title]).toEqual(APIResponse[j]);
}
}
}
});
});
test.describe('Fill Handle', () => {
let p: paramsType;
test.beforeEach(async ({ page }) => {
p = await beforeEachInit({ page, tableType: 'selectBased' });
});
test.afterEach(async () => {
await unsetup(p.context);
});
test('Select based', async ({ page }) => {
const fields = [
{ title: 'SingleSelect', value: 'jan', type: 'singleSelect' },
{ title: 'MultiSelect', value: 'jan,feb,mar', type: 'multiSelect' },
];
await dragDrop({ firstColumn: 'SingleSelect', lastColumn: 'MultiSelect', params: p });
await page.waitForTimeout(1000);
// verify data on grid
const displayOptions = ['jan', 'feb', 'mar'];
for (let i = 0; i < fields.length; i++) {
for (let j = 0; j < 4; j++) {
if (fields[i].type === 'singleSelect') {
await p.dashboard.grid.cell.selectOption.verify({
index: j,
columnHeader: fields[i].title,
option: fields[i].value,
});
} else {
await p.dashboard.grid.cell.selectOption.verifyOptions({
index: j,
columnHeader: fields[i].title,
options: displayOptions,
});
}
}
}
// verify api response
const updatedRecords = (await p.api.dbTableRow.list('noco', p.context.base.id, p.table.id, { limit: 4 })).list;
for (let i = 0; i < updatedRecords.length; i++) {
for (let j = 0; j < fields.length; j++) {
expect(updatedRecords[i][fields[j].title]).toContain(fields[j].value);
}
}
});
});
test.describe('Fill Handle', () => {
let p: paramsType;
test.beforeEach(async ({ page }) => {
p = await beforeEachInit({ page, tableType: 'miscellaneous' });
});
test.afterEach(async () => {
await unsetup(p.context);
});
test('Miscellaneous (Checkbox, attachment)', async () => {
const fields = [
{ title: 'Checkbox', value: 'true', type: 'checkbox' },
{ title: 'Attachment', value: `${process.cwd()}/fixtures/sampleFiles/1.json`, type: 'attachment' },
];
await p.dashboard.grid.cell.checkbox.click({ index: 0, columnHeader: 'Checkbox' });
const filepath = [`${process.cwd()}/fixtures/sampleFiles/1.json`];
await p.dashboard.grid.cell.attachment.addFile({
index: 0,
columnHeader: 'Attachment',
filePath: filepath,
});
await dragDrop({ firstColumn: 'Checkbox', lastColumn: 'Attachment', params: p });
// verify data on grid
for (let i = 0; i < fields.length; i++) {
for (let j = 0; j < 4; j++) {
if (fields[i].type === 'checkbox') {
await p.dashboard.grid.cell.checkbox.verifyChecked({
index: j,
columnHeader: fields[i].title,
});
} else {
await p.dashboard.grid.cell.attachment.verifyFileCount({
index: j,
columnHeader: fields[i].title,
count: 1,
});
}
}
}
// verify api response
const updatedRecords = (await p.api.dbTableRow.list('noco', p.context.base.id, p.table.id, { limit: 4 })).list;
for (let i = 0; i < updatedRecords.length; i++) {
for (let j = 0; j < fields.length; j++) {
expect(+updatedRecords[i]['Checkbox']).toBe(1);
expect(updatedRecords[i]['Attachment'][0].title).toBe('1.json');
expect(updatedRecords[i]['Attachment'][0].mimetype).toBe('application/json');
}
}
});
});
test.describe('Fill Handle', () => {
let p: paramsType;
test.beforeEach(async ({ page }) => {
p = await beforeEachInit({ page, tableType: 'dateTimeBased' });
});
test.afterEach(async () => {
await unsetup(p.context);
});
test('Date Time Based', async () => {
const row0_date = await p.api.dbTableRow.read('noco', p.context.base.id, p.table.id, 1);
const fields = [{ title: 'Date', value: row0_date['Date'], type: 'date' }];
await dragDrop({ firstColumn: 'Date', lastColumn: 'Date', params: p });
// verify data on grid
for (let i = 0; i < fields.length; i++) {
for (let j = 0; j < 4; j++) {
await p.dashboard.grid.cell.date.verify({
index: j,
columnHeader: fields[i].title,
date: fields[i].value,
});
}
}
// verify api response
const updatedRecords = (await p.api.dbTableRow.list('noco', p.context.base.id, p.table.id, { limit: 4 })).list;
for (let i = 0; i < updatedRecords.length; i++) {
for (let j = 0; j < fields.length; j++) {
expect(updatedRecords[i]['Date']).toBe(fields[j].value);
}
}
});
});
| tests/playwright/tests/db/features/verticalFillHandle.spec.ts | 0 | https://github.com/nocodb/nocodb/commit/b862043ce25ff49926754ea05282a300278ec746 | [
0.0004271313373465091,
0.00019000974134542048,
0.00016939669148996472,
0.000174361135577783,
0.00005455998325487599
] |
{
"id": 0,
"code_window": [
"\t\t});\n",
"\t}\n",
"\n",
"\tprivate launchOrAttachToSession(session: IDebugSession, focus = true): Promise<void> {\n",
"\t\tconst dbgr = this.configurationManager.getDebugger(session.configuration.type);\n",
"\t\treturn session.initialize(dbgr!).then(() => {\n",
"\t\t\treturn session.launchOrAttach(session.configuration).then(() => {\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
"\tprivate launchOrAttachToSession(session: IDebugSession, forceFocus = false): Promise<void> {\n"
],
"file_path": "src/vs/workbench/contrib/debug/browser/debugService.ts",
"type": "replace",
"edit_start_line_idx": 481
} | /*---------------------------------------------------------------------------------------------
* 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 { Event, Emitter } from 'vs/base/common/event';
import { URI as uri } from 'vs/base/common/uri';
import { first, distinct } from 'vs/base/common/arrays';
import * as errors from 'vs/base/common/errors';
import severity from 'vs/base/common/severity';
import * as aria from 'vs/base/browser/ui/aria/aria';
import { IContextKeyService, IContextKey } from 'vs/platform/contextkey/common/contextkey';
import { IMarkerService } from 'vs/platform/markers/common/markers';
import { ILifecycleService } from 'vs/platform/lifecycle/common/lifecycle';
import { IExtensionService } from 'vs/workbench/services/extensions/common/extensions';
import { IInstantiationService } from 'vs/platform/instantiation/common/instantiation';
import { FileChangesEvent, FileChangeType, IFileService } from 'vs/platform/files/common/files';
import { ITelemetryService } from 'vs/platform/telemetry/common/telemetry';
import { IStorageService, StorageScope } from 'vs/platform/storage/common/storage';
import { DebugModel, ExceptionBreakpoint, FunctionBreakpoint, Breakpoint, Expression, DataBreakpoint } from 'vs/workbench/contrib/debug/common/debugModel';
import { ViewModel } from 'vs/workbench/contrib/debug/common/debugViewModel';
import * as debugactions from 'vs/workbench/contrib/debug/browser/debugActions';
import { ConfigurationManager } from 'vs/workbench/contrib/debug/browser/debugConfigurationManager';
import Constants from 'vs/workbench/contrib/markers/browser/constants';
import { ITaskService, ITaskSummary } from 'vs/workbench/contrib/tasks/common/taskService';
import { TaskError } from 'vs/workbench/contrib/tasks/common/taskSystem';
import { VIEWLET_ID as EXPLORER_VIEWLET_ID } from 'vs/workbench/contrib/files/common/files';
import { IViewletService } from 'vs/workbench/services/viewlet/browser/viewlet';
import { IPanelService } from 'vs/workbench/services/panel/common/panelService';
import { IWorkbenchLayoutService, Parts } from 'vs/workbench/services/layout/browser/layoutService';
import { ITextFileService } from 'vs/workbench/services/textfile/common/textfiles';
import { IConfigurationService } from 'vs/platform/configuration/common/configuration';
import { IWorkspaceContextService, WorkbenchState, IWorkspaceFolder } from 'vs/platform/workspace/common/workspace';
import { IEditorService } from 'vs/workbench/services/editor/common/editorService';
import { parse, getFirstFrame } from 'vs/base/common/console';
import { TaskEvent, TaskEventKind, TaskIdentifier } from 'vs/workbench/contrib/tasks/common/tasks';
import { IDialogService } from 'vs/platform/dialogs/common/dialogs';
import { INotificationService } from 'vs/platform/notification/common/notification';
import { IAction, Action } from 'vs/base/common/actions';
import { deepClone, equals } from 'vs/base/common/objects';
import { DebugSession } from 'vs/workbench/contrib/debug/browser/debugSession';
import { dispose, IDisposable } from 'vs/base/common/lifecycle';
import { IDebugService, State, IDebugSession, CONTEXT_DEBUG_TYPE, CONTEXT_DEBUG_STATE, CONTEXT_IN_DEBUG_MODE, IThread, IDebugConfiguration, VIEWLET_ID, REPL_ID, IConfig, ILaunch, IViewModel, IConfigurationManager, IDebugModel, IEnablement, IBreakpoint, IBreakpointData, ICompound, IGlobalConfig, IStackFrame, AdapterEndEvent, getStateLabel } from 'vs/workbench/contrib/debug/common/debug';
import { isExtensionHostDebugging } from 'vs/workbench/contrib/debug/common/debugUtils';
import { isErrorWithActions, createErrorWithActions } from 'vs/base/common/errorsWithActions';
import { RunOnceScheduler } from 'vs/base/common/async';
import { IExtensionHostDebugService } from 'vs/platform/debug/common/extensionHostDebug';
import { isCodeEditor } from 'vs/editor/browser/editorBrowser';
import { CancellationTokenSource } from 'vs/base/common/cancellation';
const DEBUG_BREAKPOINTS_KEY = 'debug.breakpoint';
const DEBUG_BREAKPOINTS_ACTIVATED_KEY = 'debug.breakpointactivated';
const DEBUG_FUNCTION_BREAKPOINTS_KEY = 'debug.functionbreakpoint';
const DEBUG_DATA_BREAKPOINTS_KEY = 'debug.databreakpoint';
const DEBUG_EXCEPTION_BREAKPOINTS_KEY = 'debug.exceptionbreakpoint';
const DEBUG_WATCH_EXPRESSIONS_KEY = 'debug.watchexpressions';
function once(match: (e: TaskEvent) => boolean, event: Event<TaskEvent>): Event<TaskEvent> {
return (listener, thisArgs = null, disposables?) => {
const result = event(e => {
if (match(e)) {
result.dispose();
return listener.call(thisArgs, e);
}
}, null, disposables);
return result;
};
}
const enum TaskRunResult {
Failure,
Success
}
export class DebugService implements IDebugService {
_serviceBrand: any;
private readonly _onDidChangeState: Emitter<State>;
private readonly _onDidNewSession: Emitter<IDebugSession>;
private readonly _onWillNewSession: Emitter<IDebugSession>;
private readonly _onDidEndSession: Emitter<IDebugSession>;
private model: DebugModel;
private viewModel: ViewModel;
private configurationManager: ConfigurationManager;
private toDispose: IDisposable[];
private debugType: IContextKey<string>;
private debugState: IContextKey<string>;
private inDebugMode: IContextKey<boolean>;
private breakpointsToSendOnResourceSaved: Set<string>;
private initializing = false;
private previousState: State | undefined;
private initCancellationToken: CancellationTokenSource | undefined;
constructor(
@IStorageService private readonly storageService: IStorageService,
@IEditorService private readonly editorService: IEditorService,
@ITextFileService private readonly textFileService: ITextFileService,
@IViewletService private readonly viewletService: IViewletService,
@IPanelService private readonly panelService: IPanelService,
@INotificationService private readonly notificationService: INotificationService,
@IDialogService private readonly dialogService: IDialogService,
@IWorkbenchLayoutService private readonly layoutService: IWorkbenchLayoutService,
@ITelemetryService private readonly telemetryService: ITelemetryService,
@IWorkspaceContextService private readonly contextService: IWorkspaceContextService,
@IContextKeyService contextKeyService: IContextKeyService,
@ILifecycleService private readonly lifecycleService: ILifecycleService,
@IInstantiationService private readonly instantiationService: IInstantiationService,
@IExtensionService private readonly extensionService: IExtensionService,
@IMarkerService private readonly markerService: IMarkerService,
@ITaskService private readonly taskService: ITaskService,
@IFileService private readonly fileService: IFileService,
@IConfigurationService private readonly configurationService: IConfigurationService,
@IExtensionHostDebugService private readonly extensionHostDebugService: IExtensionHostDebugService
) {
this.toDispose = [];
this.breakpointsToSendOnResourceSaved = new Set<string>();
this._onDidChangeState = new Emitter<State>();
this._onDidNewSession = new Emitter<IDebugSession>();
this._onWillNewSession = new Emitter<IDebugSession>();
this._onDidEndSession = new Emitter<IDebugSession>();
this.configurationManager = this.instantiationService.createInstance(ConfigurationManager, this);
this.toDispose.push(this.configurationManager);
this.debugType = CONTEXT_DEBUG_TYPE.bindTo(contextKeyService);
this.debugState = CONTEXT_DEBUG_STATE.bindTo(contextKeyService);
this.inDebugMode = CONTEXT_IN_DEBUG_MODE.bindTo(contextKeyService);
this.model = new DebugModel(this.loadBreakpoints(), this.storageService.getBoolean(DEBUG_BREAKPOINTS_ACTIVATED_KEY, StorageScope.WORKSPACE, true), this.loadFunctionBreakpoints(),
this.loadExceptionBreakpoints(), this.loadDataBreakpoints(), this.loadWatchExpressions(), this.textFileService);
this.toDispose.push(this.model);
this.viewModel = new ViewModel(contextKeyService);
this.toDispose.push(this.fileService.onFileChanges(e => this.onFileChanges(e)));
this.lifecycleService.onShutdown(this.dispose, this);
this.toDispose.push(this.extensionHostDebugService.onAttachSession(event => {
const session = this.model.getSession(event.sessionId, true);
if (session) {
// EH was started in debug mode -> attach to it
session.configuration.request = 'attach';
session.configuration.port = event.port;
session.setSubId(event.subId);
this.launchOrAttachToSession(session).then(undefined, errors.onUnexpectedError);
}
}));
this.toDispose.push(this.extensionHostDebugService.onTerminateSession(event => {
const session = this.model.getSession(event.sessionId);
if (session && session.subId === event.subId) {
session.disconnect().then(undefined, errors.onUnexpectedError);
}
}));
this.toDispose.push(this.extensionHostDebugService.onLogToSession(event => {
const session = this.model.getSession(event.sessionId, true);
if (session) {
// extension logged output -> show it in REPL
const sev = event.log.severity === 'warn' ? severity.Warning : event.log.severity === 'error' ? severity.Error : severity.Info;
const { args, stack } = parse(event.log);
const frame = !!stack ? getFirstFrame(stack) : undefined;
session.logToRepl(sev, args, frame);
}
}));
this.toDispose.push(this.viewModel.onDidFocusStackFrame(() => {
this.onStateChange();
}));
this.toDispose.push(this.viewModel.onDidFocusSession(session => {
const id = session ? session.getId() : undefined;
this.model.setBreakpointsSessionId(id);
this.onStateChange();
}));
}
getModel(): IDebugModel {
return this.model;
}
getViewModel(): IViewModel {
return this.viewModel;
}
getConfigurationManager(): IConfigurationManager {
return this.configurationManager;
}
sourceIsNotAvailable(uri: uri): void {
this.model.sourceIsNotAvailable(uri);
}
dispose(): void {
this.toDispose = dispose(this.toDispose);
}
//---- state management
get state(): State {
const focusedSession = this.viewModel.focusedSession;
if (focusedSession) {
return focusedSession.state;
}
return this.initializing ? State.Initializing : State.Inactive;
}
private startInitializingState() {
if (!this.initializing) {
this.initializing = true;
this.onStateChange();
}
}
private endInitializingState() {
if (this.initCancellationToken) {
this.initCancellationToken.cancel();
this.initCancellationToken = undefined;
}
if (this.initializing) {
this.initializing = false;
this.onStateChange();
}
}
private onStateChange(): void {
const state = this.state;
if (this.previousState !== state) {
this.debugState.set(getStateLabel(state));
this.inDebugMode.set(state !== State.Inactive);
this.previousState = state;
this._onDidChangeState.fire(state);
}
}
get onDidChangeState(): Event<State> {
return this._onDidChangeState.event;
}
get onDidNewSession(): Event<IDebugSession> {
return this._onDidNewSession.event;
}
get onWillNewSession(): Event<IDebugSession> {
return this._onWillNewSession.event;
}
get onDidEndSession(): Event<IDebugSession> {
return this._onDidEndSession.event;
}
//---- life cycle management
/**
* main entry point
* properly manages compounds, checks for errors and handles the initializing state.
*/
startDebugging(launch: ILaunch | undefined, configOrName?: IConfig | string, noDebug = false, parentSession?: IDebugSession): Promise<boolean> {
this.startInitializingState();
// make sure to save all files and that the configuration is up to date
return this.extensionService.activateByEvent('onDebug').then(() => {
return this.textFileService.saveAll().then(() => this.configurationService.reloadConfiguration(launch ? launch.workspace : undefined).then(() => {
return this.extensionService.whenInstalledExtensionsRegistered().then(() => {
let config: IConfig | undefined;
let compound: ICompound | undefined;
if (!configOrName) {
configOrName = this.configurationManager.selectedConfiguration.name;
}
if (typeof configOrName === 'string' && launch) {
config = launch.getConfiguration(configOrName);
compound = launch.getCompound(configOrName);
const sessions = this.model.getSessions();
const alreadyRunningMessage = nls.localize('configurationAlreadyRunning', "There is already a debug configuration \"{0}\" running.", configOrName);
if (sessions.some(s => s.configuration.name === configOrName && (!launch || !launch.workspace || !s.root || s.root.uri.toString() === launch.workspace.uri.toString()))) {
return Promise.reject(new Error(alreadyRunningMessage));
}
if (compound && compound.configurations && sessions.some(p => compound!.configurations.indexOf(p.configuration.name) !== -1)) {
return Promise.reject(new Error(alreadyRunningMessage));
}
} else if (typeof configOrName !== 'string') {
config = configOrName;
}
if (compound) {
// we are starting a compound debug, first do some error checking and than start each configuration in the compound
if (!compound.configurations) {
return Promise.reject(new Error(nls.localize({ key: 'compoundMustHaveConfigurations', comment: ['compound indicates a "compounds" configuration item', '"configurations" is an attribute and should not be localized'] },
"Compound must have \"configurations\" attribute set in order to start multiple configurations.")));
}
return Promise.all(compound.configurations.map(configData => {
const name = typeof configData === 'string' ? configData : configData.name;
if (name === compound!.name) {
return Promise.resolve(false);
}
let launchForName: ILaunch | undefined;
if (typeof configData === 'string') {
const launchesContainingName = this.configurationManager.getLaunches().filter(l => !!l.getConfiguration(name));
if (launchesContainingName.length === 1) {
launchForName = launchesContainingName[0];
} else if (launch && launchesContainingName.length > 1 && launchesContainingName.indexOf(launch) >= 0) {
// If there are multiple launches containing the configuration give priority to the configuration in the current launch
launchForName = launch;
} else {
return Promise.reject(new Error(launchesContainingName.length === 0 ? nls.localize('noConfigurationNameInWorkspace', "Could not find launch configuration '{0}' in the workspace.", name)
: nls.localize('multipleConfigurationNamesInWorkspace', "There are multiple launch configurations '{0}' in the workspace. Use folder name to qualify the configuration.", name)));
}
} else if (configData.folder) {
const launchesMatchingConfigData = this.configurationManager.getLaunches().filter(l => l.workspace && l.workspace.name === configData.folder && !!l.getConfiguration(configData.name));
if (launchesMatchingConfigData.length === 1) {
launchForName = launchesMatchingConfigData[0];
} else {
return Promise.reject(new Error(nls.localize('noFolderWithName', "Can not find folder with name '{0}' for configuration '{1}' in compound '{2}'.", configData.folder, configData.name, compound!.name)));
}
}
return this.createSession(launchForName, launchForName!.getConfiguration(name), noDebug, parentSession);
})).then(values => values.every(success => !!success)); // Compound launch is a success only if each configuration launched successfully
}
if (configOrName && !config) {
const message = !!launch ? nls.localize('configMissing', "Configuration '{0}' is missing in 'launch.json'.", typeof configOrName === 'string' ? configOrName : JSON.stringify(configOrName)) :
nls.localize('launchJsonDoesNotExist', "'launch.json' does not exist.");
return Promise.reject(new Error(message));
}
return this.createSession(launch, config, noDebug, parentSession);
});
}));
}).then(success => {
// make sure to get out of initializing state, and propagate the result
this.endInitializingState();
return success;
}, err => {
this.endInitializingState();
return Promise.reject(err);
});
}
/**
* gets the debugger for the type, resolves configurations by providers, substitutes variables and runs prelaunch tasks
*/
private createSession(launch: ILaunch | undefined, config: IConfig | undefined, noDebug: boolean, parentSession?: IDebugSession): Promise<boolean> {
// We keep the debug type in a separate variable 'type' so that a no-folder config has no attributes.
// Storing the type in the config would break extensions that assume that the no-folder case is indicated by an empty config.
let type: string | undefined;
if (config) {
type = config.type;
} else {
// a no-folder workspace has no launch.config
config = Object.create(null);
}
const unresolvedConfig = deepClone(config);
if (noDebug) {
config!.noDebug = true;
}
const debuggerThenable: Promise<void> = type ? Promise.resolve() : this.configurationManager.guessDebugger().then(dbgr => { type = dbgr && dbgr.type; });
return debuggerThenable.then(() => {
this.initCancellationToken = new CancellationTokenSource();
return this.configurationManager.resolveConfigurationByProviders(launch && launch.workspace ? launch.workspace.uri : undefined, type, config!, this.initCancellationToken.token).then(config => {
// a falsy config indicates an aborted launch
if (config && config.type) {
return this.substituteVariables(launch, config).then(resolvedConfig => {
if (!resolvedConfig) {
// User canceled resolving of interactive variables, silently return
return false;
}
if (!this.configurationManager.getDebugger(resolvedConfig.type) || (config.request !== 'attach' && config.request !== 'launch')) {
let message: string;
if (config.request !== 'attach' && config.request !== 'launch') {
message = config.request ? nls.localize('debugRequestNotSupported', "Attribute '{0}' has an unsupported value '{1}' in the chosen debug configuration.", 'request', config.request)
: nls.localize('debugRequesMissing', "Attribute '{0}' is missing from the chosen debug configuration.", 'request');
} else {
message = resolvedConfig.type ? nls.localize('debugTypeNotSupported', "Configured debug type '{0}' is not supported.", resolvedConfig.type) :
nls.localize('debugTypeMissing', "Missing property 'type' for the chosen launch configuration.");
}
return this.showError(message).then(() => false);
}
const workspace = launch ? launch.workspace : undefined;
return this.runTaskAndCheckErrors(workspace, resolvedConfig.preLaunchTask).then(result => {
if (result === TaskRunResult.Success) {
return this.doCreateSession(workspace, { resolved: resolvedConfig, unresolved: unresolvedConfig }, parentSession);
}
return false;
});
}, err => {
if (err && err.message) {
return this.showError(err.message).then(() => false);
}
if (this.contextService.getWorkbenchState() === WorkbenchState.EMPTY) {
return this.showError(nls.localize('noFolderWorkspaceDebugError', "The active file can not be debugged. Make sure it is saved and that you have a debug extension installed for that file type."))
.then(() => false);
}
return !!launch && launch.openConfigFile(false, true, undefined, this.initCancellationToken ? this.initCancellationToken.token : undefined).then(() => false);
});
}
if (launch && type && config === null) { // show launch.json only for "config" being "null".
return launch.openConfigFile(false, true, type, this.initCancellationToken ? this.initCancellationToken.token : undefined).then(() => false);
}
return false;
});
});
}
/**
* instantiates the new session, initializes the session, registers session listeners and reports telemetry
*/
private doCreateSession(root: IWorkspaceFolder | undefined, configuration: { resolved: IConfig, unresolved: IConfig | undefined }, parentSession?: IDebugSession): Promise<boolean> {
const session = this.instantiationService.createInstance(DebugSession, configuration, root, this.model, parentSession);
this.model.addSession(session);
// register listeners as the very first thing!
this.registerSessionListeners(session);
// since the Session is now properly registered under its ID and hooked, we can announce it
// this event doesn't go to extensions
this._onWillNewSession.fire(session);
const openDebug = this.configurationService.getValue<IDebugConfiguration>('debug').openDebug;
// Open debug viewlet based on the visibility of the side bar and openDebug setting. Do not open for 'run without debug'
if (!configuration.resolved.noDebug && (openDebug === 'openOnSessionStart' || (openDebug === 'openOnFirstSessionStart' && this.viewModel.firstSessionStart))) {
this.viewletService.openViewlet(VIEWLET_ID).then(undefined, errors.onUnexpectedError);
}
return this.launchOrAttachToSession(session).then(() => {
const internalConsoleOptions = session.configuration.internalConsoleOptions || this.configurationService.getValue<IDebugConfiguration>('debug').internalConsoleOptions;
if (internalConsoleOptions === 'openOnSessionStart' || (this.viewModel.firstSessionStart && internalConsoleOptions === 'openOnFirstSessionStart')) {
this.panelService.openPanel(REPL_ID, false);
}
this.viewModel.firstSessionStart = false;
const showSubSessions = this.configurationService.getValue<IDebugConfiguration>('debug').showSubSessionsInToolBar;
const sessions = this.model.getSessions();
const shownSessions = showSubSessions ? sessions : sessions.filter(s => !s.parentSession);
if (shownSessions.length > 1) {
this.viewModel.setMultiSessionView(true);
}
// since the initialized response has arrived announce the new Session (including extensions)
this._onDidNewSession.fire(session);
return this.telemetryDebugSessionStart(root, session.configuration.type);
}).then(() => true, (error: Error | string) => {
if (errors.isPromiseCanceledError(error)) {
// don't show 'canceled' error messages to the user #7906
return Promise.resolve(false);
}
// Show the repl if some error got logged there #5870
if (session && session.getReplElements().length > 0) {
this.panelService.openPanel(REPL_ID, false);
}
if (session.configuration && session.configuration.request === 'attach' && session.configuration.__autoAttach) {
// ignore attach timeouts in auto attach mode
return Promise.resolve(false);
}
const errorMessage = error instanceof Error ? error.message : error;
this.telemetryDebugMisconfiguration(session.configuration ? session.configuration.type : undefined, errorMessage);
return this.showError(errorMessage, isErrorWithActions(error) ? error.actions : []).then(() => false);
});
}
private launchOrAttachToSession(session: IDebugSession, focus = true): Promise<void> {
const dbgr = this.configurationManager.getDebugger(session.configuration.type);
return session.initialize(dbgr!).then(() => {
return session.launchOrAttach(session.configuration).then(() => {
if (focus) {
this.focusStackFrame(undefined, undefined, session);
}
});
}).then(undefined, err => {
session.shutdown();
return Promise.reject(err);
});
}
private registerSessionListeners(session: IDebugSession): void {
const sessionRunningScheduler = new RunOnceScheduler(() => {
// Do not immediatly defocus the stack frame if the session is running
if (session.state === State.Running && this.viewModel.focusedSession === session) {
this.viewModel.setFocus(undefined, this.viewModel.focusedThread, session, false);
}
}, 200);
this.toDispose.push(session.onDidChangeState(() => {
if (session.state === State.Running && this.viewModel.focusedSession === session) {
sessionRunningScheduler.schedule();
}
if (session === this.viewModel.focusedSession) {
this.onStateChange();
}
}));
this.toDispose.push(session.onDidEndAdapter(adapterExitEvent => {
if (adapterExitEvent.error) {
this.notificationService.error(nls.localize('debugAdapterCrash', "Debug adapter process has terminated unexpectedly ({0})", adapterExitEvent.error.message || adapterExitEvent.error.toString()));
}
// 'Run without debugging' mode VSCode must terminate the extension host. More details: #3905
if (isExtensionHostDebugging(session.configuration) && session.state === State.Running && session.configuration.noDebug) {
this.extensionHostDebugService.close(session.getId());
}
this.telemetryDebugSessionStop(session, adapterExitEvent);
if (session.configuration.postDebugTask) {
this.runTask(session.root, session.configuration.postDebugTask).then(undefined, err =>
this.notificationService.error(err)
);
}
session.shutdown();
this.endInitializingState();
this._onDidEndSession.fire(session);
const focusedSession = this.viewModel.focusedSession;
if (focusedSession && focusedSession.getId() === session.getId()) {
this.focusStackFrame(undefined);
}
if (this.model.getSessions().length === 0) {
this.viewModel.setMultiSessionView(false);
if (this.layoutService.isVisible(Parts.SIDEBAR_PART) && this.configurationService.getValue<IDebugConfiguration>('debug').openExplorerOnEnd) {
this.viewletService.openViewlet(EXPLORER_VIEWLET_ID);
}
// Data breakpoints that can not be persisted should be cleared when a session ends
const dataBreakpoints = this.model.getDataBreakpoints().filter(dbp => !dbp.canPersist);
dataBreakpoints.forEach(dbp => this.model.removeDataBreakpoints(dbp.getId()));
}
}));
}
restartSession(session: IDebugSession, restartData?: any): Promise<any> {
return this.textFileService.saveAll().then(() => {
const isAutoRestart = !!restartData;
const runTasks: () => Promise<TaskRunResult> = () => {
if (isAutoRestart) {
// Do not run preLaunch and postDebug tasks for automatic restarts
return Promise.resolve(TaskRunResult.Success);
}
return this.runTask(session.root, session.configuration.postDebugTask)
.then(() => this.runTaskAndCheckErrors(session.root, session.configuration.preLaunchTask));
};
if (session.capabilities.supportsRestartRequest) {
return runTasks().then(taskResult => taskResult === TaskRunResult.Success ? session.restart() : undefined);
}
if (isExtensionHostDebugging(session.configuration)) {
return runTasks().then(taskResult => taskResult === TaskRunResult.Success ? this.extensionHostDebugService.reload(session.getId()) : undefined);
}
const shouldFocus = this.viewModel.focusedSession && session.getId() === this.viewModel.focusedSession.getId();
// If the restart is automatic -> disconnect, otherwise -> terminate #55064
return (isAutoRestart ? session.disconnect(true) : session.terminate(true)).then(() => {
return new Promise<void>((c, e) => {
setTimeout(() => {
runTasks().then(taskResult => {
if (taskResult !== TaskRunResult.Success) {
return;
}
// Read the configuration again if a launch.json has been changed, if not just use the inmemory configuration
let needsToSubstitute = false;
let unresolved: IConfig | undefined;
const launch = session.root ? this.configurationManager.getLaunch(session.root.uri) : undefined;
if (launch) {
unresolved = launch.getConfiguration(session.configuration.name);
if (unresolved && !equals(unresolved, session.unresolvedConfiguration)) {
// Take the type from the session since the debug extension might overwrite it #21316
unresolved.type = session.configuration.type;
unresolved.noDebug = session.configuration.noDebug;
needsToSubstitute = true;
}
}
let substitutionThenable: Promise<IConfig | null | undefined> = Promise.resolve(session.configuration);
if (launch && needsToSubstitute && unresolved) {
this.initCancellationToken = new CancellationTokenSource();
substitutionThenable = this.configurationManager.resolveConfigurationByProviders(launch.workspace ? launch.workspace.uri : undefined, unresolved.type, unresolved, this.initCancellationToken.token)
.then(resolved => {
if (resolved) {
// start debugging
return this.substituteVariables(launch, resolved);
} else if (resolved === null) {
// abort debugging silently and open launch.json
return Promise.resolve(null);
} else {
// abort debugging silently
return Promise.resolve(undefined);
}
});
}
substitutionThenable.then(resolved => {
if (!resolved) {
return c(undefined);
}
session.setConfiguration({ resolved, unresolved });
session.configuration.__restart = restartData;
this.launchOrAttachToSession(session, shouldFocus).then(() => {
this._onDidNewSession.fire(session);
c(undefined);
}, err => e(err));
});
});
}, 300);
});
});
});
}
stopSession(session: IDebugSession): Promise<any> {
if (session) {
return session.terminate();
}
const sessions = this.model.getSessions();
if (sessions.length === 0) {
this.endInitializingState();
}
return Promise.all(sessions.map(s => s.terminate()));
}
private substituteVariables(launch: ILaunch | undefined, config: IConfig): Promise<IConfig | undefined> {
const dbg = this.configurationManager.getDebugger(config.type);
if (dbg) {
let folder: IWorkspaceFolder | undefined = undefined;
if (launch && launch.workspace) {
folder = launch.workspace;
} else {
const folders = this.contextService.getWorkspace().folders;
if (folders.length === 1) {
folder = folders[0];
}
}
return dbg.substituteVariables(folder, config).then(config => {
return config;
}, (err: Error) => {
this.showError(err.message);
return undefined; // bail out
});
}
return Promise.resolve(config);
}
private showError(message: string, errorActions: ReadonlyArray<IAction> = []): Promise<void> {
const configureAction = this.instantiationService.createInstance(debugactions.ConfigureAction, debugactions.ConfigureAction.ID, debugactions.ConfigureAction.LABEL);
const actions = [...errorActions, configureAction];
return this.dialogService.show(severity.Error, message, actions.map(a => a.label).concat(nls.localize('cancel', "Cancel")), { cancelId: actions.length }).then(choice => {
if (choice < actions.length) {
return actions[choice].run();
}
return undefined;
});
}
//---- task management
private runTaskAndCheckErrors(root: IWorkspaceFolder | undefined, taskId: string | TaskIdentifier | undefined): Promise<TaskRunResult> {
const debugAnywayAction = new Action('debug.debugAnyway', nls.localize('debugAnyway', "Debug Anyway"), undefined, true, () => Promise.resolve(TaskRunResult.Success));
return this.runTask(root, taskId).then((taskSummary: ITaskSummary) => {
const errorCount = taskId ? this.markerService.getStatistics().errors : 0;
const successExitCode = taskSummary && taskSummary.exitCode === 0;
const failureExitCode = taskSummary && taskSummary.exitCode !== undefined && taskSummary.exitCode !== 0;
if (successExitCode || (errorCount === 0 && !failureExitCode)) {
return <any>TaskRunResult.Success;
}
const taskLabel = typeof taskId === 'string' ? taskId : taskId ? taskId.name : '';
const message = errorCount > 1
? nls.localize('preLaunchTaskErrors', "Errors exist after running preLaunchTask '{0}'.", taskLabel)
: errorCount === 1
? nls.localize('preLaunchTaskError', "Error exists after running preLaunchTask '{0}'.", taskLabel)
: nls.localize('preLaunchTaskExitCode', "The preLaunchTask '{0}' terminated with exit code {1}.", taskLabel, taskSummary.exitCode);
const showErrorsAction = new Action('debug.showErrors', nls.localize('showErrors', "Show Errors"), undefined, true, () => {
this.panelService.openPanel(Constants.MARKERS_PANEL_ID);
return Promise.resolve(TaskRunResult.Failure);
});
return this.showError(message, [debugAnywayAction, showErrorsAction]);
}, (err: TaskError) => {
return this.showError(err.message, [debugAnywayAction, this.taskService.configureAction()]);
});
}
private runTask(root: IWorkspaceFolder | undefined, taskId: string | TaskIdentifier | undefined): Promise<ITaskSummary | null> {
if (!taskId) {
return Promise.resolve(null);
}
if (!root) {
return Promise.reject(new Error(nls.localize('invalidTaskReference', "Task '{0}' can not be referenced from a launch configuration that is in a different workspace folder.", typeof taskId === 'string' ? taskId : taskId.type)));
}
// run a task before starting a debug session
return this.taskService.getTask(root, taskId).then(task => {
if (!task) {
const errorMessage = typeof taskId === 'string'
? nls.localize('DebugTaskNotFoundWithTaskId', "Could not find the task '{0}'.", taskId)
: nls.localize('DebugTaskNotFound', "Could not find the specified task.");
return Promise.reject(createErrorWithActions(errorMessage));
}
// If a task is missing the problem matcher the promise will never complete, so we need to have a workaround #35340
let taskStarted = false;
const promise: Promise<ITaskSummary | null> = this.taskService.getActiveTasks().then(tasks => {
if (tasks.filter(t => t._id === task._id).length) {
// task is already running - nothing to do.
return Promise.resolve(null);
}
once(e => ((e.kind === TaskEventKind.Active) || (e.kind === TaskEventKind.DependsOnStarted)) && e.taskId === task._id, this.taskService.onDidStateChange)(() => {
// Task is active, so everything seems to be fine, no need to prompt after 10 seconds
// Use case being a slow running task should not be prompted even though it takes more than 10 seconds
taskStarted = true;
});
const taskPromise = this.taskService.run(task);
if (task.configurationProperties.isBackground) {
return new Promise((c, e) => once(e => e.kind === TaskEventKind.Inactive && e.taskId === task._id, this.taskService.onDidStateChange)(() => {
taskStarted = true;
c(null);
}));
}
return taskPromise;
});
return new Promise((c, e) => {
promise.then(result => {
taskStarted = true;
c(result);
}, error => e(error));
setTimeout(() => {
if (!taskStarted) {
const errorMessage = typeof taskId === 'string'
? nls.localize('taskNotTrackedWithTaskId', "The specified task cannot be tracked.")
: nls.localize('taskNotTracked', "The task '{0}' cannot be tracked.", JSON.stringify(taskId));
e({ severity: severity.Error, message: errorMessage });
}
}, 10000);
});
});
}
//---- focus management
focusStackFrame(stackFrame: IStackFrame | undefined, thread?: IThread, session?: IDebugSession, explicit?: boolean): void {
if (!session) {
if (stackFrame || thread) {
session = stackFrame ? stackFrame.thread.session : thread!.session;
} else {
const sessions = this.model.getSessions();
const stoppedSession = sessions.filter(s => s.state === State.Stopped).shift();
session = stoppedSession || (sessions.length ? sessions[0] : undefined);
}
}
if (!thread) {
if (stackFrame) {
thread = stackFrame.thread;
} else {
const threads = session ? session.getAllThreads() : undefined;
const stoppedThread = threads && threads.filter(t => t.stopped).shift();
thread = stoppedThread || (threads && threads.length ? threads[0] : undefined);
}
}
if (!stackFrame) {
if (thread) {
const callStack = thread.getCallStack();
stackFrame = first(callStack, sf => !!(sf && sf.source && sf.source.available && sf.source.presentationHint !== 'deemphasize'), undefined);
}
}
if (stackFrame) {
stackFrame.openInEditor(this.editorService, true).then(editor => {
if (editor) {
const control = editor.getControl();
if (stackFrame && isCodeEditor(control) && control.hasModel()) {
const model = control.getModel();
if (stackFrame.range.startLineNumber <= model.getLineCount()) {
const lineContent = control.getModel().getLineContent(stackFrame.range.startLineNumber);
aria.alert(nls.localize('debuggingPaused', "Debugging paused {0}, {1} {2} {3}", thread && thread.stoppedDetails ? `, reason ${thread.stoppedDetails.reason}` : '', stackFrame.source ? stackFrame.source.name : '', stackFrame.range.startLineNumber, lineContent));
}
}
}
});
}
if (session) {
this.debugType.set(session.configuration.type);
} else {
this.debugType.reset();
}
this.viewModel.setFocus(stackFrame, thread, session, !!explicit);
}
//---- watches
addWatchExpression(name: string): void {
const we = this.model.addWatchExpression(name);
this.viewModel.setSelectedExpression(we);
this.storeWatchExpressions();
}
renameWatchExpression(id: string, newName: string): void {
this.model.renameWatchExpression(id, newName);
this.storeWatchExpressions();
}
moveWatchExpression(id: string, position: number): void {
this.model.moveWatchExpression(id, position);
this.storeWatchExpressions();
}
removeWatchExpressions(id?: string): void {
this.model.removeWatchExpressions(id);
this.storeWatchExpressions();
}
//---- breakpoints
async enableOrDisableBreakpoints(enable: boolean, breakpoint?: IEnablement): Promise<void> {
if (breakpoint) {
this.model.setEnablement(breakpoint, enable);
if (breakpoint instanceof Breakpoint) {
await this.sendBreakpoints(breakpoint.uri);
} else if (breakpoint instanceof FunctionBreakpoint) {
await this.sendFunctionBreakpoints();
} else if (breakpoint instanceof DataBreakpoint) {
await this.sendDataBreakpoints();
} else {
await this.sendExceptionBreakpoints();
}
} else {
this.model.enableOrDisableAllBreakpoints(enable);
await this.sendAllBreakpoints();
}
this.storeBreakpoints();
}
async addBreakpoints(uri: uri, rawBreakpoints: IBreakpointData[], context: string): Promise<IBreakpoint[]> {
const breakpoints = this.model.addBreakpoints(uri, rawBreakpoints);
breakpoints.forEach(bp => aria.status(nls.localize('breakpointAdded', "Added breakpoint, line {0}, file {1}", bp.lineNumber, uri.fsPath)));
breakpoints.forEach(bp => this.telemetryDebugAddBreakpoint(bp, context));
await this.sendBreakpoints(uri);
this.storeBreakpoints();
return breakpoints;
}
async updateBreakpoints(uri: uri, data: Map<string, DebugProtocol.Breakpoint>, sendOnResourceSaved: boolean): Promise<void> {
this.model.updateBreakpoints(data);
if (sendOnResourceSaved) {
this.breakpointsToSendOnResourceSaved.add(uri.toString());
} else {
await this.sendBreakpoints(uri);
}
this.storeBreakpoints();
}
async removeBreakpoints(id?: string): Promise<void> {
const toRemove = this.model.getBreakpoints().filter(bp => !id || bp.getId() === id);
toRemove.forEach(bp => aria.status(nls.localize('breakpointRemoved', "Removed breakpoint, line {0}, file {1}", bp.lineNumber, bp.uri.fsPath)));
const urisToClear = distinct(toRemove, bp => bp.uri.toString()).map(bp => bp.uri);
this.model.removeBreakpoints(toRemove);
await Promise.all(urisToClear.map(uri => this.sendBreakpoints(uri)));
this.storeBreakpoints();
}
setBreakpointsActivated(activated: boolean): Promise<void> {
this.model.setBreakpointsActivated(activated);
if (activated) {
this.storageService.store(DEBUG_BREAKPOINTS_ACTIVATED_KEY, 'false', StorageScope.WORKSPACE);
} else {
this.storageService.remove(DEBUG_BREAKPOINTS_ACTIVATED_KEY, StorageScope.WORKSPACE);
}
return this.sendAllBreakpoints();
}
addFunctionBreakpoint(name?: string, id?: string): void {
const newFunctionBreakpoint = this.model.addFunctionBreakpoint(name || '', id);
this.viewModel.setSelectedFunctionBreakpoint(newFunctionBreakpoint);
}
async renameFunctionBreakpoint(id: string, newFunctionName: string): Promise<void> {
this.model.renameFunctionBreakpoint(id, newFunctionName);
await this.sendFunctionBreakpoints();
this.storeBreakpoints();
}
async removeFunctionBreakpoints(id?: string): Promise<void> {
this.model.removeFunctionBreakpoints(id);
await this.sendFunctionBreakpoints();
this.storeBreakpoints();
}
async addDataBreakpoint(label: string, dataId: string, canPersist: boolean): Promise<void> {
this.model.addDataBreakpoint(label, dataId, canPersist);
await this.sendDataBreakpoints();
this.storeBreakpoints();
}
async removeDataBreakpoints(id?: string): Promise<void> {
this.model.removeDataBreakpoints(id);
await this.sendDataBreakpoints();
this.storeBreakpoints();
}
sendAllBreakpoints(session?: IDebugSession): Promise<any> {
return Promise.all(distinct(this.model.getBreakpoints(), bp => bp.uri.toString()).map(bp => this.sendBreakpoints(bp.uri, false, session)))
.then(() => this.sendFunctionBreakpoints(session))
// send exception breakpoints at the end since some debug adapters rely on the order
.then(() => this.sendExceptionBreakpoints(session));
}
private sendBreakpoints(modelUri: uri, sourceModified = false, session?: IDebugSession): Promise<void> {
const breakpointsToSend = this.model.getBreakpoints({ uri: modelUri, enabledOnly: true });
return this.sendToOneOrAllSessions(session, s =>
s.sendBreakpoints(modelUri, breakpointsToSend, sourceModified)
);
}
private sendFunctionBreakpoints(session?: IDebugSession): Promise<void> {
const breakpointsToSend = this.model.getFunctionBreakpoints().filter(fbp => fbp.enabled && this.model.areBreakpointsActivated());
return this.sendToOneOrAllSessions(session, s => {
return s.capabilities.supportsFunctionBreakpoints ? s.sendFunctionBreakpoints(breakpointsToSend) : Promise.resolve(undefined);
});
}
private sendDataBreakpoints(session?: IDebugSession): Promise<void> {
const breakpointsToSend = this.model.getDataBreakpoints().filter(fbp => fbp.enabled && this.model.areBreakpointsActivated());
return this.sendToOneOrAllSessions(session, s => {
return s.capabilities.supportsDataBreakpoints ? s.sendDataBreakpoints(breakpointsToSend) : Promise.resolve(undefined);
});
}
private sendExceptionBreakpoints(session?: IDebugSession): Promise<void> {
const enabledExceptionBps = this.model.getExceptionBreakpoints().filter(exb => exb.enabled);
return this.sendToOneOrAllSessions(session, s => {
return s.sendExceptionBreakpoints(enabledExceptionBps);
});
}
private sendToOneOrAllSessions(session: IDebugSession | undefined, send: (session: IDebugSession) => Promise<void>): Promise<void> {
if (session) {
return send(session);
}
return Promise.all(this.model.getSessions().map(s => send(s))).then(() => undefined);
}
private onFileChanges(fileChangesEvent: FileChangesEvent): void {
const toRemove = this.model.getBreakpoints().filter(bp =>
fileChangesEvent.contains(bp.uri, FileChangeType.DELETED));
if (toRemove.length) {
this.model.removeBreakpoints(toRemove);
}
fileChangesEvent.getUpdated().forEach(event => {
if (this.breakpointsToSendOnResourceSaved.delete(event.resource.toString())) {
this.sendBreakpoints(event.resource, true);
}
});
}
private loadBreakpoints(): Breakpoint[] {
let result: Breakpoint[] | undefined;
try {
result = JSON.parse(this.storageService.get(DEBUG_BREAKPOINTS_KEY, StorageScope.WORKSPACE, '[]')).map((breakpoint: any) => {
return new Breakpoint(uri.parse(breakpoint.uri.external || breakpoint.source.uri.external), breakpoint.lineNumber, breakpoint.column, breakpoint.enabled, breakpoint.condition, breakpoint.hitCondition, breakpoint.logMessage, breakpoint.adapterData, this.textFileService);
});
} catch (e) { }
return result || [];
}
private loadFunctionBreakpoints(): FunctionBreakpoint[] {
let result: FunctionBreakpoint[] | undefined;
try {
result = JSON.parse(this.storageService.get(DEBUG_FUNCTION_BREAKPOINTS_KEY, StorageScope.WORKSPACE, '[]')).map((fb: any) => {
return new FunctionBreakpoint(fb.name, fb.enabled, fb.hitCondition, fb.condition, fb.logMessage);
});
} catch (e) { }
return result || [];
}
private loadExceptionBreakpoints(): ExceptionBreakpoint[] {
let result: ExceptionBreakpoint[] | undefined;
try {
result = JSON.parse(this.storageService.get(DEBUG_EXCEPTION_BREAKPOINTS_KEY, StorageScope.WORKSPACE, '[]')).map((exBreakpoint: any) => {
return new ExceptionBreakpoint(exBreakpoint.filter, exBreakpoint.label, exBreakpoint.enabled);
});
} catch (e) { }
return result || [];
}
private loadDataBreakpoints(): DataBreakpoint[] {
let result: DataBreakpoint[] | undefined;
try {
result = JSON.parse(this.storageService.get(DEBUG_DATA_BREAKPOINTS_KEY, StorageScope.WORKSPACE, '[]')).map((dbp: any) => {
return new DataBreakpoint(dbp.label, dbp.dataId, true, dbp.enabled, dbp.hitCondition, dbp.condition, dbp.logMessage);
});
} catch (e) { }
return result || [];
}
private loadWatchExpressions(): Expression[] {
let result: Expression[] | undefined;
try {
result = JSON.parse(this.storageService.get(DEBUG_WATCH_EXPRESSIONS_KEY, StorageScope.WORKSPACE, '[]')).map((watchStoredData: { name: string, id: string }) => {
return new Expression(watchStoredData.name, watchStoredData.id);
});
} catch (e) { }
return result || [];
}
private storeWatchExpressions(): void {
const watchExpressions = this.model.getWatchExpressions();
if (watchExpressions.length) {
this.storageService.store(DEBUG_WATCH_EXPRESSIONS_KEY, JSON.stringify(watchExpressions.map(we => ({ name: we.name, id: we.getId() }))), StorageScope.WORKSPACE);
} else {
this.storageService.remove(DEBUG_WATCH_EXPRESSIONS_KEY, StorageScope.WORKSPACE);
}
}
private storeBreakpoints(): void {
const breakpoints = this.model.getBreakpoints();
if (breakpoints.length) {
this.storageService.store(DEBUG_BREAKPOINTS_KEY, JSON.stringify(breakpoints), StorageScope.WORKSPACE);
} else {
this.storageService.remove(DEBUG_BREAKPOINTS_KEY, StorageScope.WORKSPACE);
}
const functionBreakpoints = this.model.getFunctionBreakpoints();
if (functionBreakpoints.length) {
this.storageService.store(DEBUG_FUNCTION_BREAKPOINTS_KEY, JSON.stringify(functionBreakpoints), StorageScope.WORKSPACE);
} else {
this.storageService.remove(DEBUG_FUNCTION_BREAKPOINTS_KEY, StorageScope.WORKSPACE);
}
const dataBreakpoints = this.model.getDataBreakpoints().filter(dbp => dbp.canPersist);
if (dataBreakpoints.length) {
this.storageService.store(DEBUG_DATA_BREAKPOINTS_KEY, JSON.stringify(dataBreakpoints), StorageScope.WORKSPACE);
} else {
this.storageService.remove(DEBUG_DATA_BREAKPOINTS_KEY, StorageScope.WORKSPACE);
}
const exceptionBreakpoints = this.model.getExceptionBreakpoints();
if (exceptionBreakpoints.length) {
this.storageService.store(DEBUG_EXCEPTION_BREAKPOINTS_KEY, JSON.stringify(exceptionBreakpoints), StorageScope.WORKSPACE);
} else {
this.storageService.remove(DEBUG_EXCEPTION_BREAKPOINTS_KEY, StorageScope.WORKSPACE);
}
}
//---- telemetry
private telemetryDebugSessionStart(root: IWorkspaceFolder | undefined, type: string): Promise<void> {
const dbgr = this.configurationManager.getDebugger(type);
if (!dbgr) {
return Promise.resolve();
}
const extension = dbgr.getMainExtensionDescriptor();
/* __GDPR__
"debugSessionStart" : {
"type": { "classification": "SystemMetaData", "purpose": "FeatureInsight" },
"breakpointCount": { "classification": "SystemMetaData", "purpose": "FeatureInsight", "isMeasurement": true },
"exceptionBreakpoints": { "classification": "SystemMetaData", "purpose": "FeatureInsight" },
"watchExpressionsCount": { "classification": "SystemMetaData", "purpose": "FeatureInsight", "isMeasurement": true },
"extensionName": { "classification": "PublicNonPersonalData", "purpose": "FeatureInsight" },
"isBuiltin": { "classification": "SystemMetaData", "purpose": "FeatureInsight", "isMeasurement": true},
"launchJsonExists": { "classification": "SystemMetaData", "purpose": "FeatureInsight", "isMeasurement": true }
}
*/
return this.telemetryService.publicLog('debugSessionStart', {
type: type,
breakpointCount: this.model.getBreakpoints().length,
exceptionBreakpoints: this.model.getExceptionBreakpoints(),
watchExpressionsCount: this.model.getWatchExpressions().length,
extensionName: extension.identifier.value,
isBuiltin: extension.isBuiltin,
launchJsonExists: root && !!this.configurationService.getValue<IGlobalConfig>('launch', { resource: root.uri })
});
}
private telemetryDebugSessionStop(session: IDebugSession, adapterExitEvent: AdapterEndEvent): Promise<any> {
const breakpoints = this.model.getBreakpoints();
/* __GDPR__
"debugSessionStop" : {
"type" : { "classification": "SystemMetaData", "purpose": "FeatureInsight" },
"success": { "classification": "SystemMetaData", "purpose": "FeatureInsight", "isMeasurement": true },
"sessionLengthInSeconds": { "classification": "SystemMetaData", "purpose": "FeatureInsight", "isMeasurement": true },
"breakpointCount": { "classification": "SystemMetaData", "purpose": "FeatureInsight", "isMeasurement": true },
"watchExpressionsCount": { "classification": "SystemMetaData", "purpose": "FeatureInsight", "isMeasurement": true }
}
*/
return this.telemetryService.publicLog('debugSessionStop', {
type: session && session.configuration.type,
success: adapterExitEvent.emittedStopped || breakpoints.length === 0,
sessionLengthInSeconds: adapterExitEvent.sessionLengthInSeconds,
breakpointCount: breakpoints.length,
watchExpressionsCount: this.model.getWatchExpressions().length
});
}
private telemetryDebugMisconfiguration(debugType: string | undefined, message: string): Promise<any> {
/* __GDPR__
"debugMisconfiguration" : {
"type" : { "classification": "SystemMetaData", "purpose": "FeatureInsight" },
"error": { "classification": "CallstackOrException", "purpose": "FeatureInsight" }
}
*/
return this.telemetryService.publicLog('debugMisconfiguration', {
type: debugType,
error: message
});
}
private telemetryDebugAddBreakpoint(breakpoint: IBreakpoint, context: string): Promise<any> {
/* __GDPR__
"debugAddBreakpoint" : {
"context": { "classification": "SystemMetaData", "purpose": "FeatureInsight" },
"hasCondition": { "classification": "SystemMetaData", "purpose": "FeatureInsight", "isMeasurement": true },
"hasHitCondition": { "classification": "SystemMetaData", "purpose": "FeatureInsight", "isMeasurement": true },
"hasLogMessage": { "classification": "SystemMetaData", "purpose": "FeatureInsight", "isMeasurement": true }
}
*/
return this.telemetryService.publicLog('debugAddBreakpoint', {
context: context,
hasCondition: !!breakpoint.condition,
hasHitCondition: !!breakpoint.hitCondition,
hasLogMessage: !!breakpoint.logMessage
});
}
}
| src/vs/workbench/contrib/debug/browser/debugService.ts | 1 | https://github.com/microsoft/vscode/commit/38aa4766107555dce5e16e15c94135a3c681e497 | [
0.9992080330848694,
0.06849534064531326,
0.00016616897482890636,
0.00040096029988490045,
0.22540229558944702
] |
{
"id": 0,
"code_window": [
"\t\t});\n",
"\t}\n",
"\n",
"\tprivate launchOrAttachToSession(session: IDebugSession, focus = true): Promise<void> {\n",
"\t\tconst dbgr = this.configurationManager.getDebugger(session.configuration.type);\n",
"\t\treturn session.initialize(dbgr!).then(() => {\n",
"\t\t\treturn session.launchOrAttach(session.configuration).then(() => {\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
"\tprivate launchOrAttachToSession(session: IDebugSession, forceFocus = false): Promise<void> {\n"
],
"file_path": "src/vs/workbench/contrib/debug/browser/debugService.ts",
"type": "replace",
"edit_start_line_idx": 481
} | <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="M8.62132 8.08578L7.91421 7.37868L6.5 8.79289L5.08579 7.37868L4.37868 8.08578L5.79289 9.5L4.37868 10.9142L5.08579 11.6213L6.5 10.2071L7.91421 11.6213L8.62132 10.9142L7.20711 9.5L8.62132 8.08578Z" fill="#424242"/>
<path fill-rule="evenodd" clip-rule="evenodd" d="M5 3L6 2H13L14 3V10L13 11H11V13L10 14H3L2 13V6L3 5H5V3ZM6 5H10L11 6V10H13V3H6V5ZM10 6H3V13H10V6Z" fill="#424242"/>
</svg>
| src/vs/workbench/browser/parts/editor/media/close-all-light.svg | 0 | https://github.com/microsoft/vscode/commit/38aa4766107555dce5e16e15c94135a3c681e497 | [
0.00016984129615593702,
0.00016984129615593702,
0.00016984129615593702,
0.00016984129615593702,
0
] |
{
"id": 0,
"code_window": [
"\t\t});\n",
"\t}\n",
"\n",
"\tprivate launchOrAttachToSession(session: IDebugSession, focus = true): Promise<void> {\n",
"\t\tconst dbgr = this.configurationManager.getDebugger(session.configuration.type);\n",
"\t\treturn session.initialize(dbgr!).then(() => {\n",
"\t\t\treturn session.launchOrAttach(session.configuration).then(() => {\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
"\tprivate launchOrAttachToSession(session: IDebugSession, forceFocus = false): Promise<void> {\n"
],
"file_path": "src/vs/workbench/contrib/debug/browser/debugService.ts",
"type": "replace",
"edit_start_line_idx": 481
} | /*---------------------------------------------------------------------------------------------
* 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 { TerminalConfigHelper } from 'vs/workbench/contrib/terminal/browser/terminalConfigHelper';
import { EDITOR_FONT_DEFAULTS } from 'vs/editor/common/config/editorOptions';
import { TestConfigurationService } from 'vs/platform/configuration/test/common/testConfigurationService';
import { LinuxDistro } from 'vs/workbench/contrib/terminal/common/terminal';
suite('Workbench - TerminalConfigHelper', () => {
let fixture: HTMLElement;
setup(() => {
fixture = document.body;
});
test('TerminalConfigHelper - getFont fontFamily', function () {
const configurationService = new TestConfigurationService();
configurationService.setUserConfiguration('editor', { fontFamily: 'foo' });
configurationService.setUserConfiguration('terminal', { integrated: { fontFamily: 'bar' } });
const configHelper = new TerminalConfigHelper(LinuxDistro.Unknown, configurationService, null!, null!, null!);
configHelper.panelContainer = fixture;
assert.equal(configHelper.getFont().fontFamily, 'bar', 'terminal.integrated.fontFamily should be selected over editor.fontFamily');
});
test('TerminalConfigHelper - getFont fontFamily (Linux Fedora)', function () {
const configurationService = new TestConfigurationService();
configurationService.setUserConfiguration('editor', { fontFamily: 'foo' });
configurationService.setUserConfiguration('terminal', { integrated: { fontFamily: null } });
const configHelper = new TerminalConfigHelper(LinuxDistro.Fedora, configurationService, null!, null!, null!);
configHelper.panelContainer = fixture;
assert.equal(configHelper.getFont().fontFamily, '\'DejaVu Sans Mono\', monospace', 'Fedora should have its font overridden when terminal.integrated.fontFamily not set');
});
test('TerminalConfigHelper - getFont fontFamily (Linux Ubuntu)', function () {
const configurationService = new TestConfigurationService();
configurationService.setUserConfiguration('editor', { fontFamily: 'foo' });
configurationService.setUserConfiguration('terminal', { integrated: { fontFamily: null } });
const configHelper = new TerminalConfigHelper(LinuxDistro.Ubuntu, configurationService, null!, null!, null!);
configHelper.panelContainer = fixture;
assert.equal(configHelper.getFont().fontFamily, '\'Ubuntu Mono\', monospace', 'Ubuntu should have its font overridden when terminal.integrated.fontFamily not set');
});
test('TerminalConfigHelper - getFont fontFamily (Linux Unknown)', function () {
const configurationService = new TestConfigurationService();
configurationService.setUserConfiguration('editor', { fontFamily: 'foo' });
configurationService.setUserConfiguration('terminal', { integrated: { fontFamily: null } });
const configHelper = new TerminalConfigHelper(LinuxDistro.Unknown, configurationService, null!, null!, null!);
configHelper.panelContainer = fixture;
assert.equal(configHelper.getFont().fontFamily, 'foo', 'editor.fontFamily should be the fallback when terminal.integrated.fontFamily not set');
});
test('TerminalConfigHelper - getFont fontSize', function () {
const configurationService = new TestConfigurationService();
configurationService.setUserConfiguration('editor', {
fontFamily: 'foo',
fontSize: 9
});
configurationService.setUserConfiguration('terminal', {
integrated: {
fontFamily: 'bar',
fontSize: 10
}
});
let configHelper = new TerminalConfigHelper(LinuxDistro.Unknown, configurationService, null!, null!, null!);
configHelper.panelContainer = fixture;
assert.equal(configHelper.getFont().fontSize, 10, 'terminal.integrated.fontSize should be selected over editor.fontSize');
configurationService.setUserConfiguration('editor', {
fontFamily: 'foo'
});
configurationService.setUserConfiguration('terminal', {
integrated: {
fontFamily: null,
fontSize: 0
}
});
configHelper = new TerminalConfigHelper(LinuxDistro.Ubuntu, configurationService, null!, null!, null!);
configHelper.panelContainer = fixture;
assert.equal(configHelper.getFont().fontSize, 8, 'The minimum terminal font size (with adjustment) should be used when terminal.integrated.fontSize less than it');
configHelper = new TerminalConfigHelper(LinuxDistro.Unknown, configurationService, null!, null!, null!);
configHelper.panelContainer = fixture;
assert.equal(configHelper.getFont().fontSize, 6, 'The minimum terminal font size should be used when terminal.integrated.fontSize less than it');
configurationService.setUserConfiguration('editor', {
fontFamily: 'foo'
});
configurationService.setUserConfiguration('terminal', {
integrated: {
fontFamily: 0,
fontSize: 1500
}
});
configHelper = new TerminalConfigHelper(LinuxDistro.Unknown, configurationService, null!, null!, null!);
configHelper.panelContainer = fixture;
assert.equal(configHelper.getFont().fontSize, 25, 'The maximum terminal font size should be used when terminal.integrated.fontSize more than it');
configurationService.setUserConfiguration('editor', {
fontFamily: 'foo'
});
configurationService.setUserConfiguration('terminal', {
integrated: {
fontFamily: 0,
fontSize: null
}
});
configHelper = new TerminalConfigHelper(LinuxDistro.Ubuntu, configurationService, null!, null!, null!);
configHelper.panelContainer = fixture;
assert.equal(configHelper.getFont().fontSize, EDITOR_FONT_DEFAULTS.fontSize + 2, 'The default editor font size (with adjustment) should be used when terminal.integrated.fontSize is not set');
configHelper = new TerminalConfigHelper(LinuxDistro.Unknown, configurationService, null!, null!, null!);
configHelper.panelContainer = fixture;
assert.equal(configHelper.getFont().fontSize, EDITOR_FONT_DEFAULTS.fontSize, 'The default editor font size should be used when terminal.integrated.fontSize is not set');
});
test('TerminalConfigHelper - getFont lineHeight', function () {
const configurationService = new TestConfigurationService();
configurationService.setUserConfiguration('editor', {
fontFamily: 'foo',
lineHeight: 1
});
configurationService.setUserConfiguration('terminal', {
integrated: {
fontFamily: 0,
lineHeight: 2
}
});
let configHelper = new TerminalConfigHelper(LinuxDistro.Unknown, configurationService, null!, null!, null!);
configHelper.panelContainer = fixture;
assert.equal(configHelper.getFont().lineHeight, 2, 'terminal.integrated.lineHeight should be selected over editor.lineHeight');
configurationService.setUserConfiguration('editor', {
fontFamily: 'foo',
lineHeight: 1
});
configurationService.setUserConfiguration('terminal', {
integrated: {
fontFamily: 0,
lineHeight: 0
}
});
configHelper = new TerminalConfigHelper(LinuxDistro.Unknown, configurationService, null!, null!, null!);
configHelper.panelContainer = fixture;
assert.equal(configHelper.getFont().lineHeight, 1, 'editor.lineHeight should be 1 when terminal.integrated.lineHeight not set');
});
test('TerminalConfigHelper - isMonospace monospace', function () {
const configurationService = new TestConfigurationService();
configurationService.setUserConfiguration('terminal', {
integrated: {
fontFamily: 'monospace'
}
});
let configHelper = new TerminalConfigHelper(LinuxDistro.Unknown, configurationService, null!, null!, null!);
configHelper.panelContainer = fixture;
assert.equal(configHelper.configFontIsMonospace(), true, 'monospace is monospaced');
});
test('TerminalConfigHelper - isMonospace sans-serif', function () {
const configurationService = new TestConfigurationService();
configurationService.setUserConfiguration('terminal', {
integrated: {
fontFamily: 'sans-serif'
}
});
let configHelper = new TerminalConfigHelper(LinuxDistro.Unknown, configurationService, null!, null!, null!);
configHelper.panelContainer = fixture;
assert.equal(configHelper.configFontIsMonospace(), false, 'sans-serif is not monospaced');
});
test('TerminalConfigHelper - isMonospace serif', function () {
const configurationService = new TestConfigurationService();
configurationService.setUserConfiguration('terminal', {
integrated: {
fontFamily: 'serif'
}
});
let configHelper = new TerminalConfigHelper(LinuxDistro.Unknown, configurationService, null!, null!, null!);
configHelper.panelContainer = fixture;
assert.equal(configHelper.configFontIsMonospace(), false, 'serif is not monospaced');
});
test('TerminalConfigHelper - isMonospace monospace falls back to editor.fontFamily', function () {
const configurationService = new TestConfigurationService();
configurationService.setUserConfiguration('editor', {
fontFamily: 'monospace'
});
configurationService.setUserConfiguration('terminal', {
integrated: {
fontFamily: null
}
});
let configHelper = new TerminalConfigHelper(LinuxDistro.Unknown, configurationService, null!, null!, null!);
configHelper.panelContainer = fixture;
assert.equal(configHelper.configFontIsMonospace(), true, 'monospace is monospaced');
});
test('TerminalConfigHelper - isMonospace sans-serif falls back to editor.fontFamily', function () {
const configurationService = new TestConfigurationService();
configurationService.setUserConfiguration('editor', {
fontFamily: 'sans-serif'
});
configurationService.setUserConfiguration('terminal', {
integrated: {
fontFamily: null
}
});
let configHelper = new TerminalConfigHelper(LinuxDistro.Unknown, configurationService, null!, null!, null!);
configHelper.panelContainer = fixture;
assert.equal(configHelper.configFontIsMonospace(), false, 'sans-serif is not monospaced');
});
test('TerminalConfigHelper - isMonospace serif falls back to editor.fontFamily', function () {
const configurationService = new TestConfigurationService();
configurationService.setUserConfiguration('editor', {
fontFamily: 'serif'
});
configurationService.setUserConfiguration('terminal', {
integrated: {
fontFamily: null
}
});
let configHelper = new TerminalConfigHelper(LinuxDistro.Unknown, configurationService, null!, null!, null!);
configHelper.panelContainer = fixture;
assert.equal(configHelper.configFontIsMonospace(), false, 'serif is not monospaced');
});
}); | src/vs/workbench/contrib/terminal/test/electron-browser/terminalConfigHelper.test.ts | 0 | https://github.com/microsoft/vscode/commit/38aa4766107555dce5e16e15c94135a3c681e497 | [
0.00020967885211575776,
0.00017074444622267038,
0.00016609657905064523,
0.00016858115850482136,
0.000008416637683694717
] |
{
"id": 0,
"code_window": [
"\t\t});\n",
"\t}\n",
"\n",
"\tprivate launchOrAttachToSession(session: IDebugSession, focus = true): Promise<void> {\n",
"\t\tconst dbgr = this.configurationManager.getDebugger(session.configuration.type);\n",
"\t\treturn session.initialize(dbgr!).then(() => {\n",
"\t\t\treturn session.launchOrAttach(session.configuration).then(() => {\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
"\tprivate launchOrAttachToSession(session: IDebugSession, forceFocus = false): Promise<void> {\n"
],
"file_path": "src/vs/workbench/contrib/debug/browser/debugService.ts",
"type": "replace",
"edit_start_line_idx": 481
} | /*---------------------------------------------------------------------------------------------
* 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';
export const ITunnelService = createDecorator<ITunnelService>('tunnelService');
export interface RemoteTunnel {
readonly tunnelRemotePort: number;
readonly tunnelLocalPort: number;
dispose(): void;
}
export interface ITunnelService {
_serviceBrand: any;
openTunnel(remotePort: number): Promise<RemoteTunnel> | undefined;
}
| src/vs/platform/remote/common/tunnel.ts | 0 | https://github.com/microsoft/vscode/commit/38aa4766107555dce5e16e15c94135a3c681e497 | [
0.00017606141045689583,
0.00017183351155836135,
0.00016739810234867036,
0.00017204105097334832,
0.000003539823865139624
] |
{
"id": 1,
"code_window": [
"\t\tconst dbgr = this.configurationManager.getDebugger(session.configuration.type);\n",
"\t\treturn session.initialize(dbgr!).then(() => {\n",
"\t\t\treturn session.launchOrAttach(session.configuration).then(() => {\n",
"\t\t\t\tif (focus) {\n",
"\t\t\t\t\tthis.focusStackFrame(undefined, undefined, session);\n",
"\t\t\t\t}\n",
"\t\t\t});\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\t\t\tif (forceFocus || !this.viewModel.focusedSession) {\n"
],
"file_path": "src/vs/workbench/contrib/debug/browser/debugService.ts",
"type": "replace",
"edit_start_line_idx": 485
} | /*---------------------------------------------------------------------------------------------
* 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 { Event, Emitter } from 'vs/base/common/event';
import { URI as uri } from 'vs/base/common/uri';
import { first, distinct } from 'vs/base/common/arrays';
import * as errors from 'vs/base/common/errors';
import severity from 'vs/base/common/severity';
import * as aria from 'vs/base/browser/ui/aria/aria';
import { IContextKeyService, IContextKey } from 'vs/platform/contextkey/common/contextkey';
import { IMarkerService } from 'vs/platform/markers/common/markers';
import { ILifecycleService } from 'vs/platform/lifecycle/common/lifecycle';
import { IExtensionService } from 'vs/workbench/services/extensions/common/extensions';
import { IInstantiationService } from 'vs/platform/instantiation/common/instantiation';
import { FileChangesEvent, FileChangeType, IFileService } from 'vs/platform/files/common/files';
import { ITelemetryService } from 'vs/platform/telemetry/common/telemetry';
import { IStorageService, StorageScope } from 'vs/platform/storage/common/storage';
import { DebugModel, ExceptionBreakpoint, FunctionBreakpoint, Breakpoint, Expression, DataBreakpoint } from 'vs/workbench/contrib/debug/common/debugModel';
import { ViewModel } from 'vs/workbench/contrib/debug/common/debugViewModel';
import * as debugactions from 'vs/workbench/contrib/debug/browser/debugActions';
import { ConfigurationManager } from 'vs/workbench/contrib/debug/browser/debugConfigurationManager';
import Constants from 'vs/workbench/contrib/markers/browser/constants';
import { ITaskService, ITaskSummary } from 'vs/workbench/contrib/tasks/common/taskService';
import { TaskError } from 'vs/workbench/contrib/tasks/common/taskSystem';
import { VIEWLET_ID as EXPLORER_VIEWLET_ID } from 'vs/workbench/contrib/files/common/files';
import { IViewletService } from 'vs/workbench/services/viewlet/browser/viewlet';
import { IPanelService } from 'vs/workbench/services/panel/common/panelService';
import { IWorkbenchLayoutService, Parts } from 'vs/workbench/services/layout/browser/layoutService';
import { ITextFileService } from 'vs/workbench/services/textfile/common/textfiles';
import { IConfigurationService } from 'vs/platform/configuration/common/configuration';
import { IWorkspaceContextService, WorkbenchState, IWorkspaceFolder } from 'vs/platform/workspace/common/workspace';
import { IEditorService } from 'vs/workbench/services/editor/common/editorService';
import { parse, getFirstFrame } from 'vs/base/common/console';
import { TaskEvent, TaskEventKind, TaskIdentifier } from 'vs/workbench/contrib/tasks/common/tasks';
import { IDialogService } from 'vs/platform/dialogs/common/dialogs';
import { INotificationService } from 'vs/platform/notification/common/notification';
import { IAction, Action } from 'vs/base/common/actions';
import { deepClone, equals } from 'vs/base/common/objects';
import { DebugSession } from 'vs/workbench/contrib/debug/browser/debugSession';
import { dispose, IDisposable } from 'vs/base/common/lifecycle';
import { IDebugService, State, IDebugSession, CONTEXT_DEBUG_TYPE, CONTEXT_DEBUG_STATE, CONTEXT_IN_DEBUG_MODE, IThread, IDebugConfiguration, VIEWLET_ID, REPL_ID, IConfig, ILaunch, IViewModel, IConfigurationManager, IDebugModel, IEnablement, IBreakpoint, IBreakpointData, ICompound, IGlobalConfig, IStackFrame, AdapterEndEvent, getStateLabel } from 'vs/workbench/contrib/debug/common/debug';
import { isExtensionHostDebugging } from 'vs/workbench/contrib/debug/common/debugUtils';
import { isErrorWithActions, createErrorWithActions } from 'vs/base/common/errorsWithActions';
import { RunOnceScheduler } from 'vs/base/common/async';
import { IExtensionHostDebugService } from 'vs/platform/debug/common/extensionHostDebug';
import { isCodeEditor } from 'vs/editor/browser/editorBrowser';
import { CancellationTokenSource } from 'vs/base/common/cancellation';
const DEBUG_BREAKPOINTS_KEY = 'debug.breakpoint';
const DEBUG_BREAKPOINTS_ACTIVATED_KEY = 'debug.breakpointactivated';
const DEBUG_FUNCTION_BREAKPOINTS_KEY = 'debug.functionbreakpoint';
const DEBUG_DATA_BREAKPOINTS_KEY = 'debug.databreakpoint';
const DEBUG_EXCEPTION_BREAKPOINTS_KEY = 'debug.exceptionbreakpoint';
const DEBUG_WATCH_EXPRESSIONS_KEY = 'debug.watchexpressions';
function once(match: (e: TaskEvent) => boolean, event: Event<TaskEvent>): Event<TaskEvent> {
return (listener, thisArgs = null, disposables?) => {
const result = event(e => {
if (match(e)) {
result.dispose();
return listener.call(thisArgs, e);
}
}, null, disposables);
return result;
};
}
const enum TaskRunResult {
Failure,
Success
}
export class DebugService implements IDebugService {
_serviceBrand: any;
private readonly _onDidChangeState: Emitter<State>;
private readonly _onDidNewSession: Emitter<IDebugSession>;
private readonly _onWillNewSession: Emitter<IDebugSession>;
private readonly _onDidEndSession: Emitter<IDebugSession>;
private model: DebugModel;
private viewModel: ViewModel;
private configurationManager: ConfigurationManager;
private toDispose: IDisposable[];
private debugType: IContextKey<string>;
private debugState: IContextKey<string>;
private inDebugMode: IContextKey<boolean>;
private breakpointsToSendOnResourceSaved: Set<string>;
private initializing = false;
private previousState: State | undefined;
private initCancellationToken: CancellationTokenSource | undefined;
constructor(
@IStorageService private readonly storageService: IStorageService,
@IEditorService private readonly editorService: IEditorService,
@ITextFileService private readonly textFileService: ITextFileService,
@IViewletService private readonly viewletService: IViewletService,
@IPanelService private readonly panelService: IPanelService,
@INotificationService private readonly notificationService: INotificationService,
@IDialogService private readonly dialogService: IDialogService,
@IWorkbenchLayoutService private readonly layoutService: IWorkbenchLayoutService,
@ITelemetryService private readonly telemetryService: ITelemetryService,
@IWorkspaceContextService private readonly contextService: IWorkspaceContextService,
@IContextKeyService contextKeyService: IContextKeyService,
@ILifecycleService private readonly lifecycleService: ILifecycleService,
@IInstantiationService private readonly instantiationService: IInstantiationService,
@IExtensionService private readonly extensionService: IExtensionService,
@IMarkerService private readonly markerService: IMarkerService,
@ITaskService private readonly taskService: ITaskService,
@IFileService private readonly fileService: IFileService,
@IConfigurationService private readonly configurationService: IConfigurationService,
@IExtensionHostDebugService private readonly extensionHostDebugService: IExtensionHostDebugService
) {
this.toDispose = [];
this.breakpointsToSendOnResourceSaved = new Set<string>();
this._onDidChangeState = new Emitter<State>();
this._onDidNewSession = new Emitter<IDebugSession>();
this._onWillNewSession = new Emitter<IDebugSession>();
this._onDidEndSession = new Emitter<IDebugSession>();
this.configurationManager = this.instantiationService.createInstance(ConfigurationManager, this);
this.toDispose.push(this.configurationManager);
this.debugType = CONTEXT_DEBUG_TYPE.bindTo(contextKeyService);
this.debugState = CONTEXT_DEBUG_STATE.bindTo(contextKeyService);
this.inDebugMode = CONTEXT_IN_DEBUG_MODE.bindTo(contextKeyService);
this.model = new DebugModel(this.loadBreakpoints(), this.storageService.getBoolean(DEBUG_BREAKPOINTS_ACTIVATED_KEY, StorageScope.WORKSPACE, true), this.loadFunctionBreakpoints(),
this.loadExceptionBreakpoints(), this.loadDataBreakpoints(), this.loadWatchExpressions(), this.textFileService);
this.toDispose.push(this.model);
this.viewModel = new ViewModel(contextKeyService);
this.toDispose.push(this.fileService.onFileChanges(e => this.onFileChanges(e)));
this.lifecycleService.onShutdown(this.dispose, this);
this.toDispose.push(this.extensionHostDebugService.onAttachSession(event => {
const session = this.model.getSession(event.sessionId, true);
if (session) {
// EH was started in debug mode -> attach to it
session.configuration.request = 'attach';
session.configuration.port = event.port;
session.setSubId(event.subId);
this.launchOrAttachToSession(session).then(undefined, errors.onUnexpectedError);
}
}));
this.toDispose.push(this.extensionHostDebugService.onTerminateSession(event => {
const session = this.model.getSession(event.sessionId);
if (session && session.subId === event.subId) {
session.disconnect().then(undefined, errors.onUnexpectedError);
}
}));
this.toDispose.push(this.extensionHostDebugService.onLogToSession(event => {
const session = this.model.getSession(event.sessionId, true);
if (session) {
// extension logged output -> show it in REPL
const sev = event.log.severity === 'warn' ? severity.Warning : event.log.severity === 'error' ? severity.Error : severity.Info;
const { args, stack } = parse(event.log);
const frame = !!stack ? getFirstFrame(stack) : undefined;
session.logToRepl(sev, args, frame);
}
}));
this.toDispose.push(this.viewModel.onDidFocusStackFrame(() => {
this.onStateChange();
}));
this.toDispose.push(this.viewModel.onDidFocusSession(session => {
const id = session ? session.getId() : undefined;
this.model.setBreakpointsSessionId(id);
this.onStateChange();
}));
}
getModel(): IDebugModel {
return this.model;
}
getViewModel(): IViewModel {
return this.viewModel;
}
getConfigurationManager(): IConfigurationManager {
return this.configurationManager;
}
sourceIsNotAvailable(uri: uri): void {
this.model.sourceIsNotAvailable(uri);
}
dispose(): void {
this.toDispose = dispose(this.toDispose);
}
//---- state management
get state(): State {
const focusedSession = this.viewModel.focusedSession;
if (focusedSession) {
return focusedSession.state;
}
return this.initializing ? State.Initializing : State.Inactive;
}
private startInitializingState() {
if (!this.initializing) {
this.initializing = true;
this.onStateChange();
}
}
private endInitializingState() {
if (this.initCancellationToken) {
this.initCancellationToken.cancel();
this.initCancellationToken = undefined;
}
if (this.initializing) {
this.initializing = false;
this.onStateChange();
}
}
private onStateChange(): void {
const state = this.state;
if (this.previousState !== state) {
this.debugState.set(getStateLabel(state));
this.inDebugMode.set(state !== State.Inactive);
this.previousState = state;
this._onDidChangeState.fire(state);
}
}
get onDidChangeState(): Event<State> {
return this._onDidChangeState.event;
}
get onDidNewSession(): Event<IDebugSession> {
return this._onDidNewSession.event;
}
get onWillNewSession(): Event<IDebugSession> {
return this._onWillNewSession.event;
}
get onDidEndSession(): Event<IDebugSession> {
return this._onDidEndSession.event;
}
//---- life cycle management
/**
* main entry point
* properly manages compounds, checks for errors and handles the initializing state.
*/
startDebugging(launch: ILaunch | undefined, configOrName?: IConfig | string, noDebug = false, parentSession?: IDebugSession): Promise<boolean> {
this.startInitializingState();
// make sure to save all files and that the configuration is up to date
return this.extensionService.activateByEvent('onDebug').then(() => {
return this.textFileService.saveAll().then(() => this.configurationService.reloadConfiguration(launch ? launch.workspace : undefined).then(() => {
return this.extensionService.whenInstalledExtensionsRegistered().then(() => {
let config: IConfig | undefined;
let compound: ICompound | undefined;
if (!configOrName) {
configOrName = this.configurationManager.selectedConfiguration.name;
}
if (typeof configOrName === 'string' && launch) {
config = launch.getConfiguration(configOrName);
compound = launch.getCompound(configOrName);
const sessions = this.model.getSessions();
const alreadyRunningMessage = nls.localize('configurationAlreadyRunning', "There is already a debug configuration \"{0}\" running.", configOrName);
if (sessions.some(s => s.configuration.name === configOrName && (!launch || !launch.workspace || !s.root || s.root.uri.toString() === launch.workspace.uri.toString()))) {
return Promise.reject(new Error(alreadyRunningMessage));
}
if (compound && compound.configurations && sessions.some(p => compound!.configurations.indexOf(p.configuration.name) !== -1)) {
return Promise.reject(new Error(alreadyRunningMessage));
}
} else if (typeof configOrName !== 'string') {
config = configOrName;
}
if (compound) {
// we are starting a compound debug, first do some error checking and than start each configuration in the compound
if (!compound.configurations) {
return Promise.reject(new Error(nls.localize({ key: 'compoundMustHaveConfigurations', comment: ['compound indicates a "compounds" configuration item', '"configurations" is an attribute and should not be localized'] },
"Compound must have \"configurations\" attribute set in order to start multiple configurations.")));
}
return Promise.all(compound.configurations.map(configData => {
const name = typeof configData === 'string' ? configData : configData.name;
if (name === compound!.name) {
return Promise.resolve(false);
}
let launchForName: ILaunch | undefined;
if (typeof configData === 'string') {
const launchesContainingName = this.configurationManager.getLaunches().filter(l => !!l.getConfiguration(name));
if (launchesContainingName.length === 1) {
launchForName = launchesContainingName[0];
} else if (launch && launchesContainingName.length > 1 && launchesContainingName.indexOf(launch) >= 0) {
// If there are multiple launches containing the configuration give priority to the configuration in the current launch
launchForName = launch;
} else {
return Promise.reject(new Error(launchesContainingName.length === 0 ? nls.localize('noConfigurationNameInWorkspace', "Could not find launch configuration '{0}' in the workspace.", name)
: nls.localize('multipleConfigurationNamesInWorkspace', "There are multiple launch configurations '{0}' in the workspace. Use folder name to qualify the configuration.", name)));
}
} else if (configData.folder) {
const launchesMatchingConfigData = this.configurationManager.getLaunches().filter(l => l.workspace && l.workspace.name === configData.folder && !!l.getConfiguration(configData.name));
if (launchesMatchingConfigData.length === 1) {
launchForName = launchesMatchingConfigData[0];
} else {
return Promise.reject(new Error(nls.localize('noFolderWithName', "Can not find folder with name '{0}' for configuration '{1}' in compound '{2}'.", configData.folder, configData.name, compound!.name)));
}
}
return this.createSession(launchForName, launchForName!.getConfiguration(name), noDebug, parentSession);
})).then(values => values.every(success => !!success)); // Compound launch is a success only if each configuration launched successfully
}
if (configOrName && !config) {
const message = !!launch ? nls.localize('configMissing', "Configuration '{0}' is missing in 'launch.json'.", typeof configOrName === 'string' ? configOrName : JSON.stringify(configOrName)) :
nls.localize('launchJsonDoesNotExist', "'launch.json' does not exist.");
return Promise.reject(new Error(message));
}
return this.createSession(launch, config, noDebug, parentSession);
});
}));
}).then(success => {
// make sure to get out of initializing state, and propagate the result
this.endInitializingState();
return success;
}, err => {
this.endInitializingState();
return Promise.reject(err);
});
}
/**
* gets the debugger for the type, resolves configurations by providers, substitutes variables and runs prelaunch tasks
*/
private createSession(launch: ILaunch | undefined, config: IConfig | undefined, noDebug: boolean, parentSession?: IDebugSession): Promise<boolean> {
// We keep the debug type in a separate variable 'type' so that a no-folder config has no attributes.
// Storing the type in the config would break extensions that assume that the no-folder case is indicated by an empty config.
let type: string | undefined;
if (config) {
type = config.type;
} else {
// a no-folder workspace has no launch.config
config = Object.create(null);
}
const unresolvedConfig = deepClone(config);
if (noDebug) {
config!.noDebug = true;
}
const debuggerThenable: Promise<void> = type ? Promise.resolve() : this.configurationManager.guessDebugger().then(dbgr => { type = dbgr && dbgr.type; });
return debuggerThenable.then(() => {
this.initCancellationToken = new CancellationTokenSource();
return this.configurationManager.resolveConfigurationByProviders(launch && launch.workspace ? launch.workspace.uri : undefined, type, config!, this.initCancellationToken.token).then(config => {
// a falsy config indicates an aborted launch
if (config && config.type) {
return this.substituteVariables(launch, config).then(resolvedConfig => {
if (!resolvedConfig) {
// User canceled resolving of interactive variables, silently return
return false;
}
if (!this.configurationManager.getDebugger(resolvedConfig.type) || (config.request !== 'attach' && config.request !== 'launch')) {
let message: string;
if (config.request !== 'attach' && config.request !== 'launch') {
message = config.request ? nls.localize('debugRequestNotSupported', "Attribute '{0}' has an unsupported value '{1}' in the chosen debug configuration.", 'request', config.request)
: nls.localize('debugRequesMissing', "Attribute '{0}' is missing from the chosen debug configuration.", 'request');
} else {
message = resolvedConfig.type ? nls.localize('debugTypeNotSupported', "Configured debug type '{0}' is not supported.", resolvedConfig.type) :
nls.localize('debugTypeMissing', "Missing property 'type' for the chosen launch configuration.");
}
return this.showError(message).then(() => false);
}
const workspace = launch ? launch.workspace : undefined;
return this.runTaskAndCheckErrors(workspace, resolvedConfig.preLaunchTask).then(result => {
if (result === TaskRunResult.Success) {
return this.doCreateSession(workspace, { resolved: resolvedConfig, unresolved: unresolvedConfig }, parentSession);
}
return false;
});
}, err => {
if (err && err.message) {
return this.showError(err.message).then(() => false);
}
if (this.contextService.getWorkbenchState() === WorkbenchState.EMPTY) {
return this.showError(nls.localize('noFolderWorkspaceDebugError', "The active file can not be debugged. Make sure it is saved and that you have a debug extension installed for that file type."))
.then(() => false);
}
return !!launch && launch.openConfigFile(false, true, undefined, this.initCancellationToken ? this.initCancellationToken.token : undefined).then(() => false);
});
}
if (launch && type && config === null) { // show launch.json only for "config" being "null".
return launch.openConfigFile(false, true, type, this.initCancellationToken ? this.initCancellationToken.token : undefined).then(() => false);
}
return false;
});
});
}
/**
* instantiates the new session, initializes the session, registers session listeners and reports telemetry
*/
private doCreateSession(root: IWorkspaceFolder | undefined, configuration: { resolved: IConfig, unresolved: IConfig | undefined }, parentSession?: IDebugSession): Promise<boolean> {
const session = this.instantiationService.createInstance(DebugSession, configuration, root, this.model, parentSession);
this.model.addSession(session);
// register listeners as the very first thing!
this.registerSessionListeners(session);
// since the Session is now properly registered under its ID and hooked, we can announce it
// this event doesn't go to extensions
this._onWillNewSession.fire(session);
const openDebug = this.configurationService.getValue<IDebugConfiguration>('debug').openDebug;
// Open debug viewlet based on the visibility of the side bar and openDebug setting. Do not open for 'run without debug'
if (!configuration.resolved.noDebug && (openDebug === 'openOnSessionStart' || (openDebug === 'openOnFirstSessionStart' && this.viewModel.firstSessionStart))) {
this.viewletService.openViewlet(VIEWLET_ID).then(undefined, errors.onUnexpectedError);
}
return this.launchOrAttachToSession(session).then(() => {
const internalConsoleOptions = session.configuration.internalConsoleOptions || this.configurationService.getValue<IDebugConfiguration>('debug').internalConsoleOptions;
if (internalConsoleOptions === 'openOnSessionStart' || (this.viewModel.firstSessionStart && internalConsoleOptions === 'openOnFirstSessionStart')) {
this.panelService.openPanel(REPL_ID, false);
}
this.viewModel.firstSessionStart = false;
const showSubSessions = this.configurationService.getValue<IDebugConfiguration>('debug').showSubSessionsInToolBar;
const sessions = this.model.getSessions();
const shownSessions = showSubSessions ? sessions : sessions.filter(s => !s.parentSession);
if (shownSessions.length > 1) {
this.viewModel.setMultiSessionView(true);
}
// since the initialized response has arrived announce the new Session (including extensions)
this._onDidNewSession.fire(session);
return this.telemetryDebugSessionStart(root, session.configuration.type);
}).then(() => true, (error: Error | string) => {
if (errors.isPromiseCanceledError(error)) {
// don't show 'canceled' error messages to the user #7906
return Promise.resolve(false);
}
// Show the repl if some error got logged there #5870
if (session && session.getReplElements().length > 0) {
this.panelService.openPanel(REPL_ID, false);
}
if (session.configuration && session.configuration.request === 'attach' && session.configuration.__autoAttach) {
// ignore attach timeouts in auto attach mode
return Promise.resolve(false);
}
const errorMessage = error instanceof Error ? error.message : error;
this.telemetryDebugMisconfiguration(session.configuration ? session.configuration.type : undefined, errorMessage);
return this.showError(errorMessage, isErrorWithActions(error) ? error.actions : []).then(() => false);
});
}
private launchOrAttachToSession(session: IDebugSession, focus = true): Promise<void> {
const dbgr = this.configurationManager.getDebugger(session.configuration.type);
return session.initialize(dbgr!).then(() => {
return session.launchOrAttach(session.configuration).then(() => {
if (focus) {
this.focusStackFrame(undefined, undefined, session);
}
});
}).then(undefined, err => {
session.shutdown();
return Promise.reject(err);
});
}
private registerSessionListeners(session: IDebugSession): void {
const sessionRunningScheduler = new RunOnceScheduler(() => {
// Do not immediatly defocus the stack frame if the session is running
if (session.state === State.Running && this.viewModel.focusedSession === session) {
this.viewModel.setFocus(undefined, this.viewModel.focusedThread, session, false);
}
}, 200);
this.toDispose.push(session.onDidChangeState(() => {
if (session.state === State.Running && this.viewModel.focusedSession === session) {
sessionRunningScheduler.schedule();
}
if (session === this.viewModel.focusedSession) {
this.onStateChange();
}
}));
this.toDispose.push(session.onDidEndAdapter(adapterExitEvent => {
if (adapterExitEvent.error) {
this.notificationService.error(nls.localize('debugAdapterCrash', "Debug adapter process has terminated unexpectedly ({0})", adapterExitEvent.error.message || adapterExitEvent.error.toString()));
}
// 'Run without debugging' mode VSCode must terminate the extension host. More details: #3905
if (isExtensionHostDebugging(session.configuration) && session.state === State.Running && session.configuration.noDebug) {
this.extensionHostDebugService.close(session.getId());
}
this.telemetryDebugSessionStop(session, adapterExitEvent);
if (session.configuration.postDebugTask) {
this.runTask(session.root, session.configuration.postDebugTask).then(undefined, err =>
this.notificationService.error(err)
);
}
session.shutdown();
this.endInitializingState();
this._onDidEndSession.fire(session);
const focusedSession = this.viewModel.focusedSession;
if (focusedSession && focusedSession.getId() === session.getId()) {
this.focusStackFrame(undefined);
}
if (this.model.getSessions().length === 0) {
this.viewModel.setMultiSessionView(false);
if (this.layoutService.isVisible(Parts.SIDEBAR_PART) && this.configurationService.getValue<IDebugConfiguration>('debug').openExplorerOnEnd) {
this.viewletService.openViewlet(EXPLORER_VIEWLET_ID);
}
// Data breakpoints that can not be persisted should be cleared when a session ends
const dataBreakpoints = this.model.getDataBreakpoints().filter(dbp => !dbp.canPersist);
dataBreakpoints.forEach(dbp => this.model.removeDataBreakpoints(dbp.getId()));
}
}));
}
restartSession(session: IDebugSession, restartData?: any): Promise<any> {
return this.textFileService.saveAll().then(() => {
const isAutoRestart = !!restartData;
const runTasks: () => Promise<TaskRunResult> = () => {
if (isAutoRestart) {
// Do not run preLaunch and postDebug tasks for automatic restarts
return Promise.resolve(TaskRunResult.Success);
}
return this.runTask(session.root, session.configuration.postDebugTask)
.then(() => this.runTaskAndCheckErrors(session.root, session.configuration.preLaunchTask));
};
if (session.capabilities.supportsRestartRequest) {
return runTasks().then(taskResult => taskResult === TaskRunResult.Success ? session.restart() : undefined);
}
if (isExtensionHostDebugging(session.configuration)) {
return runTasks().then(taskResult => taskResult === TaskRunResult.Success ? this.extensionHostDebugService.reload(session.getId()) : undefined);
}
const shouldFocus = this.viewModel.focusedSession && session.getId() === this.viewModel.focusedSession.getId();
// If the restart is automatic -> disconnect, otherwise -> terminate #55064
return (isAutoRestart ? session.disconnect(true) : session.terminate(true)).then(() => {
return new Promise<void>((c, e) => {
setTimeout(() => {
runTasks().then(taskResult => {
if (taskResult !== TaskRunResult.Success) {
return;
}
// Read the configuration again if a launch.json has been changed, if not just use the inmemory configuration
let needsToSubstitute = false;
let unresolved: IConfig | undefined;
const launch = session.root ? this.configurationManager.getLaunch(session.root.uri) : undefined;
if (launch) {
unresolved = launch.getConfiguration(session.configuration.name);
if (unresolved && !equals(unresolved, session.unresolvedConfiguration)) {
// Take the type from the session since the debug extension might overwrite it #21316
unresolved.type = session.configuration.type;
unresolved.noDebug = session.configuration.noDebug;
needsToSubstitute = true;
}
}
let substitutionThenable: Promise<IConfig | null | undefined> = Promise.resolve(session.configuration);
if (launch && needsToSubstitute && unresolved) {
this.initCancellationToken = new CancellationTokenSource();
substitutionThenable = this.configurationManager.resolveConfigurationByProviders(launch.workspace ? launch.workspace.uri : undefined, unresolved.type, unresolved, this.initCancellationToken.token)
.then(resolved => {
if (resolved) {
// start debugging
return this.substituteVariables(launch, resolved);
} else if (resolved === null) {
// abort debugging silently and open launch.json
return Promise.resolve(null);
} else {
// abort debugging silently
return Promise.resolve(undefined);
}
});
}
substitutionThenable.then(resolved => {
if (!resolved) {
return c(undefined);
}
session.setConfiguration({ resolved, unresolved });
session.configuration.__restart = restartData;
this.launchOrAttachToSession(session, shouldFocus).then(() => {
this._onDidNewSession.fire(session);
c(undefined);
}, err => e(err));
});
});
}, 300);
});
});
});
}
stopSession(session: IDebugSession): Promise<any> {
if (session) {
return session.terminate();
}
const sessions = this.model.getSessions();
if (sessions.length === 0) {
this.endInitializingState();
}
return Promise.all(sessions.map(s => s.terminate()));
}
private substituteVariables(launch: ILaunch | undefined, config: IConfig): Promise<IConfig | undefined> {
const dbg = this.configurationManager.getDebugger(config.type);
if (dbg) {
let folder: IWorkspaceFolder | undefined = undefined;
if (launch && launch.workspace) {
folder = launch.workspace;
} else {
const folders = this.contextService.getWorkspace().folders;
if (folders.length === 1) {
folder = folders[0];
}
}
return dbg.substituteVariables(folder, config).then(config => {
return config;
}, (err: Error) => {
this.showError(err.message);
return undefined; // bail out
});
}
return Promise.resolve(config);
}
private showError(message: string, errorActions: ReadonlyArray<IAction> = []): Promise<void> {
const configureAction = this.instantiationService.createInstance(debugactions.ConfigureAction, debugactions.ConfigureAction.ID, debugactions.ConfigureAction.LABEL);
const actions = [...errorActions, configureAction];
return this.dialogService.show(severity.Error, message, actions.map(a => a.label).concat(nls.localize('cancel', "Cancel")), { cancelId: actions.length }).then(choice => {
if (choice < actions.length) {
return actions[choice].run();
}
return undefined;
});
}
//---- task management
private runTaskAndCheckErrors(root: IWorkspaceFolder | undefined, taskId: string | TaskIdentifier | undefined): Promise<TaskRunResult> {
const debugAnywayAction = new Action('debug.debugAnyway', nls.localize('debugAnyway', "Debug Anyway"), undefined, true, () => Promise.resolve(TaskRunResult.Success));
return this.runTask(root, taskId).then((taskSummary: ITaskSummary) => {
const errorCount = taskId ? this.markerService.getStatistics().errors : 0;
const successExitCode = taskSummary && taskSummary.exitCode === 0;
const failureExitCode = taskSummary && taskSummary.exitCode !== undefined && taskSummary.exitCode !== 0;
if (successExitCode || (errorCount === 0 && !failureExitCode)) {
return <any>TaskRunResult.Success;
}
const taskLabel = typeof taskId === 'string' ? taskId : taskId ? taskId.name : '';
const message = errorCount > 1
? nls.localize('preLaunchTaskErrors', "Errors exist after running preLaunchTask '{0}'.", taskLabel)
: errorCount === 1
? nls.localize('preLaunchTaskError', "Error exists after running preLaunchTask '{0}'.", taskLabel)
: nls.localize('preLaunchTaskExitCode', "The preLaunchTask '{0}' terminated with exit code {1}.", taskLabel, taskSummary.exitCode);
const showErrorsAction = new Action('debug.showErrors', nls.localize('showErrors', "Show Errors"), undefined, true, () => {
this.panelService.openPanel(Constants.MARKERS_PANEL_ID);
return Promise.resolve(TaskRunResult.Failure);
});
return this.showError(message, [debugAnywayAction, showErrorsAction]);
}, (err: TaskError) => {
return this.showError(err.message, [debugAnywayAction, this.taskService.configureAction()]);
});
}
private runTask(root: IWorkspaceFolder | undefined, taskId: string | TaskIdentifier | undefined): Promise<ITaskSummary | null> {
if (!taskId) {
return Promise.resolve(null);
}
if (!root) {
return Promise.reject(new Error(nls.localize('invalidTaskReference', "Task '{0}' can not be referenced from a launch configuration that is in a different workspace folder.", typeof taskId === 'string' ? taskId : taskId.type)));
}
// run a task before starting a debug session
return this.taskService.getTask(root, taskId).then(task => {
if (!task) {
const errorMessage = typeof taskId === 'string'
? nls.localize('DebugTaskNotFoundWithTaskId', "Could not find the task '{0}'.", taskId)
: nls.localize('DebugTaskNotFound', "Could not find the specified task.");
return Promise.reject(createErrorWithActions(errorMessage));
}
// If a task is missing the problem matcher the promise will never complete, so we need to have a workaround #35340
let taskStarted = false;
const promise: Promise<ITaskSummary | null> = this.taskService.getActiveTasks().then(tasks => {
if (tasks.filter(t => t._id === task._id).length) {
// task is already running - nothing to do.
return Promise.resolve(null);
}
once(e => ((e.kind === TaskEventKind.Active) || (e.kind === TaskEventKind.DependsOnStarted)) && e.taskId === task._id, this.taskService.onDidStateChange)(() => {
// Task is active, so everything seems to be fine, no need to prompt after 10 seconds
// Use case being a slow running task should not be prompted even though it takes more than 10 seconds
taskStarted = true;
});
const taskPromise = this.taskService.run(task);
if (task.configurationProperties.isBackground) {
return new Promise((c, e) => once(e => e.kind === TaskEventKind.Inactive && e.taskId === task._id, this.taskService.onDidStateChange)(() => {
taskStarted = true;
c(null);
}));
}
return taskPromise;
});
return new Promise((c, e) => {
promise.then(result => {
taskStarted = true;
c(result);
}, error => e(error));
setTimeout(() => {
if (!taskStarted) {
const errorMessage = typeof taskId === 'string'
? nls.localize('taskNotTrackedWithTaskId', "The specified task cannot be tracked.")
: nls.localize('taskNotTracked', "The task '{0}' cannot be tracked.", JSON.stringify(taskId));
e({ severity: severity.Error, message: errorMessage });
}
}, 10000);
});
});
}
//---- focus management
focusStackFrame(stackFrame: IStackFrame | undefined, thread?: IThread, session?: IDebugSession, explicit?: boolean): void {
if (!session) {
if (stackFrame || thread) {
session = stackFrame ? stackFrame.thread.session : thread!.session;
} else {
const sessions = this.model.getSessions();
const stoppedSession = sessions.filter(s => s.state === State.Stopped).shift();
session = stoppedSession || (sessions.length ? sessions[0] : undefined);
}
}
if (!thread) {
if (stackFrame) {
thread = stackFrame.thread;
} else {
const threads = session ? session.getAllThreads() : undefined;
const stoppedThread = threads && threads.filter(t => t.stopped).shift();
thread = stoppedThread || (threads && threads.length ? threads[0] : undefined);
}
}
if (!stackFrame) {
if (thread) {
const callStack = thread.getCallStack();
stackFrame = first(callStack, sf => !!(sf && sf.source && sf.source.available && sf.source.presentationHint !== 'deemphasize'), undefined);
}
}
if (stackFrame) {
stackFrame.openInEditor(this.editorService, true).then(editor => {
if (editor) {
const control = editor.getControl();
if (stackFrame && isCodeEditor(control) && control.hasModel()) {
const model = control.getModel();
if (stackFrame.range.startLineNumber <= model.getLineCount()) {
const lineContent = control.getModel().getLineContent(stackFrame.range.startLineNumber);
aria.alert(nls.localize('debuggingPaused', "Debugging paused {0}, {1} {2} {3}", thread && thread.stoppedDetails ? `, reason ${thread.stoppedDetails.reason}` : '', stackFrame.source ? stackFrame.source.name : '', stackFrame.range.startLineNumber, lineContent));
}
}
}
});
}
if (session) {
this.debugType.set(session.configuration.type);
} else {
this.debugType.reset();
}
this.viewModel.setFocus(stackFrame, thread, session, !!explicit);
}
//---- watches
addWatchExpression(name: string): void {
const we = this.model.addWatchExpression(name);
this.viewModel.setSelectedExpression(we);
this.storeWatchExpressions();
}
renameWatchExpression(id: string, newName: string): void {
this.model.renameWatchExpression(id, newName);
this.storeWatchExpressions();
}
moveWatchExpression(id: string, position: number): void {
this.model.moveWatchExpression(id, position);
this.storeWatchExpressions();
}
removeWatchExpressions(id?: string): void {
this.model.removeWatchExpressions(id);
this.storeWatchExpressions();
}
//---- breakpoints
async enableOrDisableBreakpoints(enable: boolean, breakpoint?: IEnablement): Promise<void> {
if (breakpoint) {
this.model.setEnablement(breakpoint, enable);
if (breakpoint instanceof Breakpoint) {
await this.sendBreakpoints(breakpoint.uri);
} else if (breakpoint instanceof FunctionBreakpoint) {
await this.sendFunctionBreakpoints();
} else if (breakpoint instanceof DataBreakpoint) {
await this.sendDataBreakpoints();
} else {
await this.sendExceptionBreakpoints();
}
} else {
this.model.enableOrDisableAllBreakpoints(enable);
await this.sendAllBreakpoints();
}
this.storeBreakpoints();
}
async addBreakpoints(uri: uri, rawBreakpoints: IBreakpointData[], context: string): Promise<IBreakpoint[]> {
const breakpoints = this.model.addBreakpoints(uri, rawBreakpoints);
breakpoints.forEach(bp => aria.status(nls.localize('breakpointAdded', "Added breakpoint, line {0}, file {1}", bp.lineNumber, uri.fsPath)));
breakpoints.forEach(bp => this.telemetryDebugAddBreakpoint(bp, context));
await this.sendBreakpoints(uri);
this.storeBreakpoints();
return breakpoints;
}
async updateBreakpoints(uri: uri, data: Map<string, DebugProtocol.Breakpoint>, sendOnResourceSaved: boolean): Promise<void> {
this.model.updateBreakpoints(data);
if (sendOnResourceSaved) {
this.breakpointsToSendOnResourceSaved.add(uri.toString());
} else {
await this.sendBreakpoints(uri);
}
this.storeBreakpoints();
}
async removeBreakpoints(id?: string): Promise<void> {
const toRemove = this.model.getBreakpoints().filter(bp => !id || bp.getId() === id);
toRemove.forEach(bp => aria.status(nls.localize('breakpointRemoved', "Removed breakpoint, line {0}, file {1}", bp.lineNumber, bp.uri.fsPath)));
const urisToClear = distinct(toRemove, bp => bp.uri.toString()).map(bp => bp.uri);
this.model.removeBreakpoints(toRemove);
await Promise.all(urisToClear.map(uri => this.sendBreakpoints(uri)));
this.storeBreakpoints();
}
setBreakpointsActivated(activated: boolean): Promise<void> {
this.model.setBreakpointsActivated(activated);
if (activated) {
this.storageService.store(DEBUG_BREAKPOINTS_ACTIVATED_KEY, 'false', StorageScope.WORKSPACE);
} else {
this.storageService.remove(DEBUG_BREAKPOINTS_ACTIVATED_KEY, StorageScope.WORKSPACE);
}
return this.sendAllBreakpoints();
}
addFunctionBreakpoint(name?: string, id?: string): void {
const newFunctionBreakpoint = this.model.addFunctionBreakpoint(name || '', id);
this.viewModel.setSelectedFunctionBreakpoint(newFunctionBreakpoint);
}
async renameFunctionBreakpoint(id: string, newFunctionName: string): Promise<void> {
this.model.renameFunctionBreakpoint(id, newFunctionName);
await this.sendFunctionBreakpoints();
this.storeBreakpoints();
}
async removeFunctionBreakpoints(id?: string): Promise<void> {
this.model.removeFunctionBreakpoints(id);
await this.sendFunctionBreakpoints();
this.storeBreakpoints();
}
async addDataBreakpoint(label: string, dataId: string, canPersist: boolean): Promise<void> {
this.model.addDataBreakpoint(label, dataId, canPersist);
await this.sendDataBreakpoints();
this.storeBreakpoints();
}
async removeDataBreakpoints(id?: string): Promise<void> {
this.model.removeDataBreakpoints(id);
await this.sendDataBreakpoints();
this.storeBreakpoints();
}
sendAllBreakpoints(session?: IDebugSession): Promise<any> {
return Promise.all(distinct(this.model.getBreakpoints(), bp => bp.uri.toString()).map(bp => this.sendBreakpoints(bp.uri, false, session)))
.then(() => this.sendFunctionBreakpoints(session))
// send exception breakpoints at the end since some debug adapters rely on the order
.then(() => this.sendExceptionBreakpoints(session));
}
private sendBreakpoints(modelUri: uri, sourceModified = false, session?: IDebugSession): Promise<void> {
const breakpointsToSend = this.model.getBreakpoints({ uri: modelUri, enabledOnly: true });
return this.sendToOneOrAllSessions(session, s =>
s.sendBreakpoints(modelUri, breakpointsToSend, sourceModified)
);
}
private sendFunctionBreakpoints(session?: IDebugSession): Promise<void> {
const breakpointsToSend = this.model.getFunctionBreakpoints().filter(fbp => fbp.enabled && this.model.areBreakpointsActivated());
return this.sendToOneOrAllSessions(session, s => {
return s.capabilities.supportsFunctionBreakpoints ? s.sendFunctionBreakpoints(breakpointsToSend) : Promise.resolve(undefined);
});
}
private sendDataBreakpoints(session?: IDebugSession): Promise<void> {
const breakpointsToSend = this.model.getDataBreakpoints().filter(fbp => fbp.enabled && this.model.areBreakpointsActivated());
return this.sendToOneOrAllSessions(session, s => {
return s.capabilities.supportsDataBreakpoints ? s.sendDataBreakpoints(breakpointsToSend) : Promise.resolve(undefined);
});
}
private sendExceptionBreakpoints(session?: IDebugSession): Promise<void> {
const enabledExceptionBps = this.model.getExceptionBreakpoints().filter(exb => exb.enabled);
return this.sendToOneOrAllSessions(session, s => {
return s.sendExceptionBreakpoints(enabledExceptionBps);
});
}
private sendToOneOrAllSessions(session: IDebugSession | undefined, send: (session: IDebugSession) => Promise<void>): Promise<void> {
if (session) {
return send(session);
}
return Promise.all(this.model.getSessions().map(s => send(s))).then(() => undefined);
}
private onFileChanges(fileChangesEvent: FileChangesEvent): void {
const toRemove = this.model.getBreakpoints().filter(bp =>
fileChangesEvent.contains(bp.uri, FileChangeType.DELETED));
if (toRemove.length) {
this.model.removeBreakpoints(toRemove);
}
fileChangesEvent.getUpdated().forEach(event => {
if (this.breakpointsToSendOnResourceSaved.delete(event.resource.toString())) {
this.sendBreakpoints(event.resource, true);
}
});
}
private loadBreakpoints(): Breakpoint[] {
let result: Breakpoint[] | undefined;
try {
result = JSON.parse(this.storageService.get(DEBUG_BREAKPOINTS_KEY, StorageScope.WORKSPACE, '[]')).map((breakpoint: any) => {
return new Breakpoint(uri.parse(breakpoint.uri.external || breakpoint.source.uri.external), breakpoint.lineNumber, breakpoint.column, breakpoint.enabled, breakpoint.condition, breakpoint.hitCondition, breakpoint.logMessage, breakpoint.adapterData, this.textFileService);
});
} catch (e) { }
return result || [];
}
private loadFunctionBreakpoints(): FunctionBreakpoint[] {
let result: FunctionBreakpoint[] | undefined;
try {
result = JSON.parse(this.storageService.get(DEBUG_FUNCTION_BREAKPOINTS_KEY, StorageScope.WORKSPACE, '[]')).map((fb: any) => {
return new FunctionBreakpoint(fb.name, fb.enabled, fb.hitCondition, fb.condition, fb.logMessage);
});
} catch (e) { }
return result || [];
}
private loadExceptionBreakpoints(): ExceptionBreakpoint[] {
let result: ExceptionBreakpoint[] | undefined;
try {
result = JSON.parse(this.storageService.get(DEBUG_EXCEPTION_BREAKPOINTS_KEY, StorageScope.WORKSPACE, '[]')).map((exBreakpoint: any) => {
return new ExceptionBreakpoint(exBreakpoint.filter, exBreakpoint.label, exBreakpoint.enabled);
});
} catch (e) { }
return result || [];
}
private loadDataBreakpoints(): DataBreakpoint[] {
let result: DataBreakpoint[] | undefined;
try {
result = JSON.parse(this.storageService.get(DEBUG_DATA_BREAKPOINTS_KEY, StorageScope.WORKSPACE, '[]')).map((dbp: any) => {
return new DataBreakpoint(dbp.label, dbp.dataId, true, dbp.enabled, dbp.hitCondition, dbp.condition, dbp.logMessage);
});
} catch (e) { }
return result || [];
}
private loadWatchExpressions(): Expression[] {
let result: Expression[] | undefined;
try {
result = JSON.parse(this.storageService.get(DEBUG_WATCH_EXPRESSIONS_KEY, StorageScope.WORKSPACE, '[]')).map((watchStoredData: { name: string, id: string }) => {
return new Expression(watchStoredData.name, watchStoredData.id);
});
} catch (e) { }
return result || [];
}
private storeWatchExpressions(): void {
const watchExpressions = this.model.getWatchExpressions();
if (watchExpressions.length) {
this.storageService.store(DEBUG_WATCH_EXPRESSIONS_KEY, JSON.stringify(watchExpressions.map(we => ({ name: we.name, id: we.getId() }))), StorageScope.WORKSPACE);
} else {
this.storageService.remove(DEBUG_WATCH_EXPRESSIONS_KEY, StorageScope.WORKSPACE);
}
}
private storeBreakpoints(): void {
const breakpoints = this.model.getBreakpoints();
if (breakpoints.length) {
this.storageService.store(DEBUG_BREAKPOINTS_KEY, JSON.stringify(breakpoints), StorageScope.WORKSPACE);
} else {
this.storageService.remove(DEBUG_BREAKPOINTS_KEY, StorageScope.WORKSPACE);
}
const functionBreakpoints = this.model.getFunctionBreakpoints();
if (functionBreakpoints.length) {
this.storageService.store(DEBUG_FUNCTION_BREAKPOINTS_KEY, JSON.stringify(functionBreakpoints), StorageScope.WORKSPACE);
} else {
this.storageService.remove(DEBUG_FUNCTION_BREAKPOINTS_KEY, StorageScope.WORKSPACE);
}
const dataBreakpoints = this.model.getDataBreakpoints().filter(dbp => dbp.canPersist);
if (dataBreakpoints.length) {
this.storageService.store(DEBUG_DATA_BREAKPOINTS_KEY, JSON.stringify(dataBreakpoints), StorageScope.WORKSPACE);
} else {
this.storageService.remove(DEBUG_DATA_BREAKPOINTS_KEY, StorageScope.WORKSPACE);
}
const exceptionBreakpoints = this.model.getExceptionBreakpoints();
if (exceptionBreakpoints.length) {
this.storageService.store(DEBUG_EXCEPTION_BREAKPOINTS_KEY, JSON.stringify(exceptionBreakpoints), StorageScope.WORKSPACE);
} else {
this.storageService.remove(DEBUG_EXCEPTION_BREAKPOINTS_KEY, StorageScope.WORKSPACE);
}
}
//---- telemetry
private telemetryDebugSessionStart(root: IWorkspaceFolder | undefined, type: string): Promise<void> {
const dbgr = this.configurationManager.getDebugger(type);
if (!dbgr) {
return Promise.resolve();
}
const extension = dbgr.getMainExtensionDescriptor();
/* __GDPR__
"debugSessionStart" : {
"type": { "classification": "SystemMetaData", "purpose": "FeatureInsight" },
"breakpointCount": { "classification": "SystemMetaData", "purpose": "FeatureInsight", "isMeasurement": true },
"exceptionBreakpoints": { "classification": "SystemMetaData", "purpose": "FeatureInsight" },
"watchExpressionsCount": { "classification": "SystemMetaData", "purpose": "FeatureInsight", "isMeasurement": true },
"extensionName": { "classification": "PublicNonPersonalData", "purpose": "FeatureInsight" },
"isBuiltin": { "classification": "SystemMetaData", "purpose": "FeatureInsight", "isMeasurement": true},
"launchJsonExists": { "classification": "SystemMetaData", "purpose": "FeatureInsight", "isMeasurement": true }
}
*/
return this.telemetryService.publicLog('debugSessionStart', {
type: type,
breakpointCount: this.model.getBreakpoints().length,
exceptionBreakpoints: this.model.getExceptionBreakpoints(),
watchExpressionsCount: this.model.getWatchExpressions().length,
extensionName: extension.identifier.value,
isBuiltin: extension.isBuiltin,
launchJsonExists: root && !!this.configurationService.getValue<IGlobalConfig>('launch', { resource: root.uri })
});
}
private telemetryDebugSessionStop(session: IDebugSession, adapterExitEvent: AdapterEndEvent): Promise<any> {
const breakpoints = this.model.getBreakpoints();
/* __GDPR__
"debugSessionStop" : {
"type" : { "classification": "SystemMetaData", "purpose": "FeatureInsight" },
"success": { "classification": "SystemMetaData", "purpose": "FeatureInsight", "isMeasurement": true },
"sessionLengthInSeconds": { "classification": "SystemMetaData", "purpose": "FeatureInsight", "isMeasurement": true },
"breakpointCount": { "classification": "SystemMetaData", "purpose": "FeatureInsight", "isMeasurement": true },
"watchExpressionsCount": { "classification": "SystemMetaData", "purpose": "FeatureInsight", "isMeasurement": true }
}
*/
return this.telemetryService.publicLog('debugSessionStop', {
type: session && session.configuration.type,
success: adapterExitEvent.emittedStopped || breakpoints.length === 0,
sessionLengthInSeconds: adapterExitEvent.sessionLengthInSeconds,
breakpointCount: breakpoints.length,
watchExpressionsCount: this.model.getWatchExpressions().length
});
}
private telemetryDebugMisconfiguration(debugType: string | undefined, message: string): Promise<any> {
/* __GDPR__
"debugMisconfiguration" : {
"type" : { "classification": "SystemMetaData", "purpose": "FeatureInsight" },
"error": { "classification": "CallstackOrException", "purpose": "FeatureInsight" }
}
*/
return this.telemetryService.publicLog('debugMisconfiguration', {
type: debugType,
error: message
});
}
private telemetryDebugAddBreakpoint(breakpoint: IBreakpoint, context: string): Promise<any> {
/* __GDPR__
"debugAddBreakpoint" : {
"context": { "classification": "SystemMetaData", "purpose": "FeatureInsight" },
"hasCondition": { "classification": "SystemMetaData", "purpose": "FeatureInsight", "isMeasurement": true },
"hasHitCondition": { "classification": "SystemMetaData", "purpose": "FeatureInsight", "isMeasurement": true },
"hasLogMessage": { "classification": "SystemMetaData", "purpose": "FeatureInsight", "isMeasurement": true }
}
*/
return this.telemetryService.publicLog('debugAddBreakpoint', {
context: context,
hasCondition: !!breakpoint.condition,
hasHitCondition: !!breakpoint.hitCondition,
hasLogMessage: !!breakpoint.logMessage
});
}
}
| src/vs/workbench/contrib/debug/browser/debugService.ts | 1 | https://github.com/microsoft/vscode/commit/38aa4766107555dce5e16e15c94135a3c681e497 | [
0.9984160661697388,
0.0119698541238904,
0.00016184367996174842,
0.0001931295555550605,
0.09328096359968185
] |
{
"id": 1,
"code_window": [
"\t\tconst dbgr = this.configurationManager.getDebugger(session.configuration.type);\n",
"\t\treturn session.initialize(dbgr!).then(() => {\n",
"\t\t\treturn session.launchOrAttach(session.configuration).then(() => {\n",
"\t\t\t\tif (focus) {\n",
"\t\t\t\t\tthis.focusStackFrame(undefined, undefined, session);\n",
"\t\t\t\t}\n",
"\t\t\t});\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\t\t\tif (forceFocus || !this.viewModel.focusedSession) {\n"
],
"file_path": "src/vs/workbench/contrib/debug/browser/debugService.ts",
"type": "replace",
"edit_start_line_idx": 485
} | ## Setup
- Clone [Microsoft/vscode](https://github.com/microsoft/vscode)
- Run `yarn` at `/`, this will install
- Dependencies for `/extension/html-language-features/`
- Dependencies for `/extension/html-language-features/server/`
- devDependencies such as `gulp`
- Open `/extensions/html-language-features/` as the workspace in VS Code
- Run the [`Launch Extension`](https://github.com/Microsoft/vscode/blob/master/extensions/html-language-features/.vscode/launch.json) debug target in the Debug View. This will:
- Launch the `preLaunchTask` task to compile the extension
- Launch a new VS Code instance with the `html-language-features` extension loaded
- You should see a notification saying the development version of `html-language-features` overwrites the bundled version of `html-language-features`
- Test the behavior of this extension by editing html files
- Run `Reload Window` command in the launched instance to reload the extension
### Contribute to vscode-html-languageservice
[Microsoft/vscode-html-languageservice](https://github.com/Microsoft/vscode-html-languageservice) contains the language smarts for html.
This extension wraps the html language service into a Language Server for VS Code.
If you want to fix html issues or make improvements, you should make changes at [Microsoft/vscode-html-languageservice](https://github.com/Microsoft/vscode-html-languageservice).
However, within this extension, you can run a development version of `vscode-html-languageservice` to debug code or test language features interactively:
#### Linking `vscode-html-languageservice` in `html-language-features/server/`
- Clone [Microsoft/vscode-html-languageservice](https://github.com/Microsoft/vscode-html-languageservice)
- Run `yarn` in `vscode-html-languageservice`
- Run `yarn link` in `vscode-html-languageservice`. This will compile and link `vscode-html-languageservice`
- In `html-language-features/server/`, run `npm link vscode-html-languageservice`
#### Testing the development version of `vscode-html-languageservice`
- Open both `vscode-html-languageservice` and this extension in a single workspace with [multi-root workspace](https://code.visualstudio.com/docs/editor/multi-root-workspaces) feature
- Run `yarn watch` at `html-languagefeatures/server/` to recompile this extension with the linked version of `vscode-html-languageservice`
- Make some changes in `vscode-html-languageservice`
- Now when you run `Launch Extension` debug target, the launched instance will use your development version of `vscode-html-languageservice`. You can interactively test the language features.
- You can also run the `Debug Extension and Language Server` debug target, which will launch the extension and attach the debugger to the language server. After successful attach, you should be able to hit breakpoints in both `vscode-html-languageservice` and `html-language-features/server/` | extensions/html-language-features/CONTRIBUTING.md | 0 | https://github.com/microsoft/vscode/commit/38aa4766107555dce5e16e15c94135a3c681e497 | [
0.00016525978571735322,
0.0001633555511943996,
0.00016177562065422535,
0.0001631933992030099,
0.0000012573725598485908
] |
{
"id": 1,
"code_window": [
"\t\tconst dbgr = this.configurationManager.getDebugger(session.configuration.type);\n",
"\t\treturn session.initialize(dbgr!).then(() => {\n",
"\t\t\treturn session.launchOrAttach(session.configuration).then(() => {\n",
"\t\t\t\tif (focus) {\n",
"\t\t\t\t\tthis.focusStackFrame(undefined, undefined, session);\n",
"\t\t\t\t}\n",
"\t\t\t});\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\t\t\tif (forceFocus || !this.viewModel.focusedSession) {\n"
],
"file_path": "src/vs/workbench/contrib/debug/browser/debugService.ts",
"type": "replace",
"edit_start_line_idx": 485
} | 'use strict';
var Conway;
(function (Conway) {
var Cell = (function () {
function Cell() {
}
return Cell;
})();
(function (property, number, property, number, property, boolean) {
if (property === undefined) { property = row; }
if (property === undefined) { property = col; }
if (property === undefined) { property = live; }
});
var GameOfLife = (function () {
function GameOfLife() {
}
return GameOfLife;
})();
(function () {
property;
gridSize = 50;
property;
canvasSize = 600;
property;
lineColor = '#cdcdcd';
property;
liveColor = '#666';
property;
deadColor = '#eee';
property;
initialLifeProbability = 0.5;
property;
animationRate = 60;
property;
cellSize = 0;
property;
context: ICanvasRenderingContext2D;
property;
world = createWorld();
circleOfLife();
function createWorld() {
return travelWorld(function (cell) {
cell.live = Math.random() < initialLifeProbability;
return cell;
});
}
function circleOfLife() {
world = travelWorld(function (cell) {
cell = world[cell.row][cell.col];
draw(cell);
return resolveNextGeneration(cell);
});
setTimeout(function () { circleOfLife(); }, animationRate);
}
function resolveNextGeneration(cell) {
var count = countNeighbors(cell);
var newCell = new Cell(cell.row, cell.col, cell.live);
if (count < 2 || count > 3)
newCell.live = false;
else if (count == 3)
newCell.live = true;
return newCell;
}
function countNeighbors(cell) {
var neighbors = 0;
for (var row = -1; row <= 1; row++) {
for (var col = -1; col <= 1; col++) {
if (row == 0 && col == 0)
continue;
if (isAlive(cell.row + row, cell.col + col)) {
neighbors++;
}
}
}
return neighbors;
}
function isAlive(row, col) {
// todo - need to guard with worl[row] exists?
if (row < 0 || col < 0 || row >= gridSize || col >= gridSize)
return false;
return world[row][col].live;
}
function travelWorld(callback) {
var result = [];
for (var row = 0; row < gridSize; row++) {
var rowData = [];
for (var col = 0; col < gridSize; col++) {
rowData.push(callback(new Cell(row, col, false)));
}
result.push(rowData);
}
return result;
}
function draw(cell) {
if (context == null)
context = createDrawingContext();
if (cellSize == 0)
cellSize = canvasSize / gridSize;
context.strokeStyle = lineColor;
context.strokeRect(cell.row * cellSize, cell.col * cellSize, cellSize, cellSize);
context.fillStyle = cell.live ? liveColor : deadColor;
context.fillRect(cell.row * cellSize, cell.col * cellSize, cellSize, cellSize);
}
function createDrawingContext() {
var canvas = document.getElementById('conway-canvas');
if (canvas == null) {
canvas = document.createElement('canvas');
canvas.id = "conway-canvas";
canvas.width = canvasSize;
canvas.height = canvasSize;
document.body.appendChild(canvas);
}
return canvas.getContext('2d');
}
});
})(Conway || (Conway = {}));
var game = new Conway.GameOfLife();
| src/vs/platform/files/test/node/fixtures/resolver/other/deep/conway.js | 0 | https://github.com/microsoft/vscode/commit/38aa4766107555dce5e16e15c94135a3c681e497 | [
0.00017164139717351645,
0.00016834326379466802,
0.00016475896700285375,
0.00016805436462163925,
0.000002035226316365879
] |
{
"id": 1,
"code_window": [
"\t\tconst dbgr = this.configurationManager.getDebugger(session.configuration.type);\n",
"\t\treturn session.initialize(dbgr!).then(() => {\n",
"\t\t\treturn session.launchOrAttach(session.configuration).then(() => {\n",
"\t\t\t\tif (focus) {\n",
"\t\t\t\t\tthis.focusStackFrame(undefined, undefined, session);\n",
"\t\t\t\t}\n",
"\t\t\t});\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\t\t\tif (forceFocus || !this.viewModel.focusedSession) {\n"
],
"file_path": "src/vs/workbench/contrib/debug/browser/debugService.ts",
"type": "replace",
"edit_start_line_idx": 485
} | {
"registrations": [
{
"component": {
"type": "git",
"git": {
"name": "Colorsublime-Themes",
"repositoryUrl": "https://github.com/Colorsublime/Colorsublime-Themes",
"commitHash": "c10fdd8b144486b7a4f3cb4e2251c66df222a825"
}
},
"version": "0.1.0"
}
],
"version": 1
}
| extensions/theme-tomorrow-night-blue/cgmanifest.json | 0 | https://github.com/microsoft/vscode/commit/38aa4766107555dce5e16e15c94135a3c681e497 | [
0.00016993573808576912,
0.00016835704445838928,
0.00016677836538292468,
0.00016835704445838928,
0.0000015786863514222205
] |
{
"id": 2,
"code_window": [
"\n",
"\t\t\tif (isExtensionHostDebugging(session.configuration)) {\n",
"\t\t\t\treturn runTasks().then(taskResult => taskResult === TaskRunResult.Success ? this.extensionHostDebugService.reload(session.getId()) : undefined);\n",
"\t\t\t}\n",
"\n",
"\t\t\tconst shouldFocus = this.viewModel.focusedSession && session.getId() === this.viewModel.focusedSession.getId();\n",
"\t\t\t// If the restart is automatic -> disconnect, otherwise -> terminate #55064\n",
"\t\t\treturn (isAutoRestart ? session.disconnect(true) : session.terminate(true)).then(() => {\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\t\tconst shouldFocus = !!this.viewModel.focusedSession && session.getId() === this.viewModel.focusedSession.getId();\n"
],
"file_path": "src/vs/workbench/contrib/debug/browser/debugService.ts",
"type": "replace",
"edit_start_line_idx": 574
} | /*---------------------------------------------------------------------------------------------
* 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 { Event, Emitter } from 'vs/base/common/event';
import { URI as uri } from 'vs/base/common/uri';
import { first, distinct } from 'vs/base/common/arrays';
import * as errors from 'vs/base/common/errors';
import severity from 'vs/base/common/severity';
import * as aria from 'vs/base/browser/ui/aria/aria';
import { IContextKeyService, IContextKey } from 'vs/platform/contextkey/common/contextkey';
import { IMarkerService } from 'vs/platform/markers/common/markers';
import { ILifecycleService } from 'vs/platform/lifecycle/common/lifecycle';
import { IExtensionService } from 'vs/workbench/services/extensions/common/extensions';
import { IInstantiationService } from 'vs/platform/instantiation/common/instantiation';
import { FileChangesEvent, FileChangeType, IFileService } from 'vs/platform/files/common/files';
import { ITelemetryService } from 'vs/platform/telemetry/common/telemetry';
import { IStorageService, StorageScope } from 'vs/platform/storage/common/storage';
import { DebugModel, ExceptionBreakpoint, FunctionBreakpoint, Breakpoint, Expression, DataBreakpoint } from 'vs/workbench/contrib/debug/common/debugModel';
import { ViewModel } from 'vs/workbench/contrib/debug/common/debugViewModel';
import * as debugactions from 'vs/workbench/contrib/debug/browser/debugActions';
import { ConfigurationManager } from 'vs/workbench/contrib/debug/browser/debugConfigurationManager';
import Constants from 'vs/workbench/contrib/markers/browser/constants';
import { ITaskService, ITaskSummary } from 'vs/workbench/contrib/tasks/common/taskService';
import { TaskError } from 'vs/workbench/contrib/tasks/common/taskSystem';
import { VIEWLET_ID as EXPLORER_VIEWLET_ID } from 'vs/workbench/contrib/files/common/files';
import { IViewletService } from 'vs/workbench/services/viewlet/browser/viewlet';
import { IPanelService } from 'vs/workbench/services/panel/common/panelService';
import { IWorkbenchLayoutService, Parts } from 'vs/workbench/services/layout/browser/layoutService';
import { ITextFileService } from 'vs/workbench/services/textfile/common/textfiles';
import { IConfigurationService } from 'vs/platform/configuration/common/configuration';
import { IWorkspaceContextService, WorkbenchState, IWorkspaceFolder } from 'vs/platform/workspace/common/workspace';
import { IEditorService } from 'vs/workbench/services/editor/common/editorService';
import { parse, getFirstFrame } from 'vs/base/common/console';
import { TaskEvent, TaskEventKind, TaskIdentifier } from 'vs/workbench/contrib/tasks/common/tasks';
import { IDialogService } from 'vs/platform/dialogs/common/dialogs';
import { INotificationService } from 'vs/platform/notification/common/notification';
import { IAction, Action } from 'vs/base/common/actions';
import { deepClone, equals } from 'vs/base/common/objects';
import { DebugSession } from 'vs/workbench/contrib/debug/browser/debugSession';
import { dispose, IDisposable } from 'vs/base/common/lifecycle';
import { IDebugService, State, IDebugSession, CONTEXT_DEBUG_TYPE, CONTEXT_DEBUG_STATE, CONTEXT_IN_DEBUG_MODE, IThread, IDebugConfiguration, VIEWLET_ID, REPL_ID, IConfig, ILaunch, IViewModel, IConfigurationManager, IDebugModel, IEnablement, IBreakpoint, IBreakpointData, ICompound, IGlobalConfig, IStackFrame, AdapterEndEvent, getStateLabel } from 'vs/workbench/contrib/debug/common/debug';
import { isExtensionHostDebugging } from 'vs/workbench/contrib/debug/common/debugUtils';
import { isErrorWithActions, createErrorWithActions } from 'vs/base/common/errorsWithActions';
import { RunOnceScheduler } from 'vs/base/common/async';
import { IExtensionHostDebugService } from 'vs/platform/debug/common/extensionHostDebug';
import { isCodeEditor } from 'vs/editor/browser/editorBrowser';
import { CancellationTokenSource } from 'vs/base/common/cancellation';
const DEBUG_BREAKPOINTS_KEY = 'debug.breakpoint';
const DEBUG_BREAKPOINTS_ACTIVATED_KEY = 'debug.breakpointactivated';
const DEBUG_FUNCTION_BREAKPOINTS_KEY = 'debug.functionbreakpoint';
const DEBUG_DATA_BREAKPOINTS_KEY = 'debug.databreakpoint';
const DEBUG_EXCEPTION_BREAKPOINTS_KEY = 'debug.exceptionbreakpoint';
const DEBUG_WATCH_EXPRESSIONS_KEY = 'debug.watchexpressions';
function once(match: (e: TaskEvent) => boolean, event: Event<TaskEvent>): Event<TaskEvent> {
return (listener, thisArgs = null, disposables?) => {
const result = event(e => {
if (match(e)) {
result.dispose();
return listener.call(thisArgs, e);
}
}, null, disposables);
return result;
};
}
const enum TaskRunResult {
Failure,
Success
}
export class DebugService implements IDebugService {
_serviceBrand: any;
private readonly _onDidChangeState: Emitter<State>;
private readonly _onDidNewSession: Emitter<IDebugSession>;
private readonly _onWillNewSession: Emitter<IDebugSession>;
private readonly _onDidEndSession: Emitter<IDebugSession>;
private model: DebugModel;
private viewModel: ViewModel;
private configurationManager: ConfigurationManager;
private toDispose: IDisposable[];
private debugType: IContextKey<string>;
private debugState: IContextKey<string>;
private inDebugMode: IContextKey<boolean>;
private breakpointsToSendOnResourceSaved: Set<string>;
private initializing = false;
private previousState: State | undefined;
private initCancellationToken: CancellationTokenSource | undefined;
constructor(
@IStorageService private readonly storageService: IStorageService,
@IEditorService private readonly editorService: IEditorService,
@ITextFileService private readonly textFileService: ITextFileService,
@IViewletService private readonly viewletService: IViewletService,
@IPanelService private readonly panelService: IPanelService,
@INotificationService private readonly notificationService: INotificationService,
@IDialogService private readonly dialogService: IDialogService,
@IWorkbenchLayoutService private readonly layoutService: IWorkbenchLayoutService,
@ITelemetryService private readonly telemetryService: ITelemetryService,
@IWorkspaceContextService private readonly contextService: IWorkspaceContextService,
@IContextKeyService contextKeyService: IContextKeyService,
@ILifecycleService private readonly lifecycleService: ILifecycleService,
@IInstantiationService private readonly instantiationService: IInstantiationService,
@IExtensionService private readonly extensionService: IExtensionService,
@IMarkerService private readonly markerService: IMarkerService,
@ITaskService private readonly taskService: ITaskService,
@IFileService private readonly fileService: IFileService,
@IConfigurationService private readonly configurationService: IConfigurationService,
@IExtensionHostDebugService private readonly extensionHostDebugService: IExtensionHostDebugService
) {
this.toDispose = [];
this.breakpointsToSendOnResourceSaved = new Set<string>();
this._onDidChangeState = new Emitter<State>();
this._onDidNewSession = new Emitter<IDebugSession>();
this._onWillNewSession = new Emitter<IDebugSession>();
this._onDidEndSession = new Emitter<IDebugSession>();
this.configurationManager = this.instantiationService.createInstance(ConfigurationManager, this);
this.toDispose.push(this.configurationManager);
this.debugType = CONTEXT_DEBUG_TYPE.bindTo(contextKeyService);
this.debugState = CONTEXT_DEBUG_STATE.bindTo(contextKeyService);
this.inDebugMode = CONTEXT_IN_DEBUG_MODE.bindTo(contextKeyService);
this.model = new DebugModel(this.loadBreakpoints(), this.storageService.getBoolean(DEBUG_BREAKPOINTS_ACTIVATED_KEY, StorageScope.WORKSPACE, true), this.loadFunctionBreakpoints(),
this.loadExceptionBreakpoints(), this.loadDataBreakpoints(), this.loadWatchExpressions(), this.textFileService);
this.toDispose.push(this.model);
this.viewModel = new ViewModel(contextKeyService);
this.toDispose.push(this.fileService.onFileChanges(e => this.onFileChanges(e)));
this.lifecycleService.onShutdown(this.dispose, this);
this.toDispose.push(this.extensionHostDebugService.onAttachSession(event => {
const session = this.model.getSession(event.sessionId, true);
if (session) {
// EH was started in debug mode -> attach to it
session.configuration.request = 'attach';
session.configuration.port = event.port;
session.setSubId(event.subId);
this.launchOrAttachToSession(session).then(undefined, errors.onUnexpectedError);
}
}));
this.toDispose.push(this.extensionHostDebugService.onTerminateSession(event => {
const session = this.model.getSession(event.sessionId);
if (session && session.subId === event.subId) {
session.disconnect().then(undefined, errors.onUnexpectedError);
}
}));
this.toDispose.push(this.extensionHostDebugService.onLogToSession(event => {
const session = this.model.getSession(event.sessionId, true);
if (session) {
// extension logged output -> show it in REPL
const sev = event.log.severity === 'warn' ? severity.Warning : event.log.severity === 'error' ? severity.Error : severity.Info;
const { args, stack } = parse(event.log);
const frame = !!stack ? getFirstFrame(stack) : undefined;
session.logToRepl(sev, args, frame);
}
}));
this.toDispose.push(this.viewModel.onDidFocusStackFrame(() => {
this.onStateChange();
}));
this.toDispose.push(this.viewModel.onDidFocusSession(session => {
const id = session ? session.getId() : undefined;
this.model.setBreakpointsSessionId(id);
this.onStateChange();
}));
}
getModel(): IDebugModel {
return this.model;
}
getViewModel(): IViewModel {
return this.viewModel;
}
getConfigurationManager(): IConfigurationManager {
return this.configurationManager;
}
sourceIsNotAvailable(uri: uri): void {
this.model.sourceIsNotAvailable(uri);
}
dispose(): void {
this.toDispose = dispose(this.toDispose);
}
//---- state management
get state(): State {
const focusedSession = this.viewModel.focusedSession;
if (focusedSession) {
return focusedSession.state;
}
return this.initializing ? State.Initializing : State.Inactive;
}
private startInitializingState() {
if (!this.initializing) {
this.initializing = true;
this.onStateChange();
}
}
private endInitializingState() {
if (this.initCancellationToken) {
this.initCancellationToken.cancel();
this.initCancellationToken = undefined;
}
if (this.initializing) {
this.initializing = false;
this.onStateChange();
}
}
private onStateChange(): void {
const state = this.state;
if (this.previousState !== state) {
this.debugState.set(getStateLabel(state));
this.inDebugMode.set(state !== State.Inactive);
this.previousState = state;
this._onDidChangeState.fire(state);
}
}
get onDidChangeState(): Event<State> {
return this._onDidChangeState.event;
}
get onDidNewSession(): Event<IDebugSession> {
return this._onDidNewSession.event;
}
get onWillNewSession(): Event<IDebugSession> {
return this._onWillNewSession.event;
}
get onDidEndSession(): Event<IDebugSession> {
return this._onDidEndSession.event;
}
//---- life cycle management
/**
* main entry point
* properly manages compounds, checks for errors and handles the initializing state.
*/
startDebugging(launch: ILaunch | undefined, configOrName?: IConfig | string, noDebug = false, parentSession?: IDebugSession): Promise<boolean> {
this.startInitializingState();
// make sure to save all files and that the configuration is up to date
return this.extensionService.activateByEvent('onDebug').then(() => {
return this.textFileService.saveAll().then(() => this.configurationService.reloadConfiguration(launch ? launch.workspace : undefined).then(() => {
return this.extensionService.whenInstalledExtensionsRegistered().then(() => {
let config: IConfig | undefined;
let compound: ICompound | undefined;
if (!configOrName) {
configOrName = this.configurationManager.selectedConfiguration.name;
}
if (typeof configOrName === 'string' && launch) {
config = launch.getConfiguration(configOrName);
compound = launch.getCompound(configOrName);
const sessions = this.model.getSessions();
const alreadyRunningMessage = nls.localize('configurationAlreadyRunning', "There is already a debug configuration \"{0}\" running.", configOrName);
if (sessions.some(s => s.configuration.name === configOrName && (!launch || !launch.workspace || !s.root || s.root.uri.toString() === launch.workspace.uri.toString()))) {
return Promise.reject(new Error(alreadyRunningMessage));
}
if (compound && compound.configurations && sessions.some(p => compound!.configurations.indexOf(p.configuration.name) !== -1)) {
return Promise.reject(new Error(alreadyRunningMessage));
}
} else if (typeof configOrName !== 'string') {
config = configOrName;
}
if (compound) {
// we are starting a compound debug, first do some error checking and than start each configuration in the compound
if (!compound.configurations) {
return Promise.reject(new Error(nls.localize({ key: 'compoundMustHaveConfigurations', comment: ['compound indicates a "compounds" configuration item', '"configurations" is an attribute and should not be localized'] },
"Compound must have \"configurations\" attribute set in order to start multiple configurations.")));
}
return Promise.all(compound.configurations.map(configData => {
const name = typeof configData === 'string' ? configData : configData.name;
if (name === compound!.name) {
return Promise.resolve(false);
}
let launchForName: ILaunch | undefined;
if (typeof configData === 'string') {
const launchesContainingName = this.configurationManager.getLaunches().filter(l => !!l.getConfiguration(name));
if (launchesContainingName.length === 1) {
launchForName = launchesContainingName[0];
} else if (launch && launchesContainingName.length > 1 && launchesContainingName.indexOf(launch) >= 0) {
// If there are multiple launches containing the configuration give priority to the configuration in the current launch
launchForName = launch;
} else {
return Promise.reject(new Error(launchesContainingName.length === 0 ? nls.localize('noConfigurationNameInWorkspace', "Could not find launch configuration '{0}' in the workspace.", name)
: nls.localize('multipleConfigurationNamesInWorkspace', "There are multiple launch configurations '{0}' in the workspace. Use folder name to qualify the configuration.", name)));
}
} else if (configData.folder) {
const launchesMatchingConfigData = this.configurationManager.getLaunches().filter(l => l.workspace && l.workspace.name === configData.folder && !!l.getConfiguration(configData.name));
if (launchesMatchingConfigData.length === 1) {
launchForName = launchesMatchingConfigData[0];
} else {
return Promise.reject(new Error(nls.localize('noFolderWithName', "Can not find folder with name '{0}' for configuration '{1}' in compound '{2}'.", configData.folder, configData.name, compound!.name)));
}
}
return this.createSession(launchForName, launchForName!.getConfiguration(name), noDebug, parentSession);
})).then(values => values.every(success => !!success)); // Compound launch is a success only if each configuration launched successfully
}
if (configOrName && !config) {
const message = !!launch ? nls.localize('configMissing', "Configuration '{0}' is missing in 'launch.json'.", typeof configOrName === 'string' ? configOrName : JSON.stringify(configOrName)) :
nls.localize('launchJsonDoesNotExist', "'launch.json' does not exist.");
return Promise.reject(new Error(message));
}
return this.createSession(launch, config, noDebug, parentSession);
});
}));
}).then(success => {
// make sure to get out of initializing state, and propagate the result
this.endInitializingState();
return success;
}, err => {
this.endInitializingState();
return Promise.reject(err);
});
}
/**
* gets the debugger for the type, resolves configurations by providers, substitutes variables and runs prelaunch tasks
*/
private createSession(launch: ILaunch | undefined, config: IConfig | undefined, noDebug: boolean, parentSession?: IDebugSession): Promise<boolean> {
// We keep the debug type in a separate variable 'type' so that a no-folder config has no attributes.
// Storing the type in the config would break extensions that assume that the no-folder case is indicated by an empty config.
let type: string | undefined;
if (config) {
type = config.type;
} else {
// a no-folder workspace has no launch.config
config = Object.create(null);
}
const unresolvedConfig = deepClone(config);
if (noDebug) {
config!.noDebug = true;
}
const debuggerThenable: Promise<void> = type ? Promise.resolve() : this.configurationManager.guessDebugger().then(dbgr => { type = dbgr && dbgr.type; });
return debuggerThenable.then(() => {
this.initCancellationToken = new CancellationTokenSource();
return this.configurationManager.resolveConfigurationByProviders(launch && launch.workspace ? launch.workspace.uri : undefined, type, config!, this.initCancellationToken.token).then(config => {
// a falsy config indicates an aborted launch
if (config && config.type) {
return this.substituteVariables(launch, config).then(resolvedConfig => {
if (!resolvedConfig) {
// User canceled resolving of interactive variables, silently return
return false;
}
if (!this.configurationManager.getDebugger(resolvedConfig.type) || (config.request !== 'attach' && config.request !== 'launch')) {
let message: string;
if (config.request !== 'attach' && config.request !== 'launch') {
message = config.request ? nls.localize('debugRequestNotSupported', "Attribute '{0}' has an unsupported value '{1}' in the chosen debug configuration.", 'request', config.request)
: nls.localize('debugRequesMissing', "Attribute '{0}' is missing from the chosen debug configuration.", 'request');
} else {
message = resolvedConfig.type ? nls.localize('debugTypeNotSupported', "Configured debug type '{0}' is not supported.", resolvedConfig.type) :
nls.localize('debugTypeMissing', "Missing property 'type' for the chosen launch configuration.");
}
return this.showError(message).then(() => false);
}
const workspace = launch ? launch.workspace : undefined;
return this.runTaskAndCheckErrors(workspace, resolvedConfig.preLaunchTask).then(result => {
if (result === TaskRunResult.Success) {
return this.doCreateSession(workspace, { resolved: resolvedConfig, unresolved: unresolvedConfig }, parentSession);
}
return false;
});
}, err => {
if (err && err.message) {
return this.showError(err.message).then(() => false);
}
if (this.contextService.getWorkbenchState() === WorkbenchState.EMPTY) {
return this.showError(nls.localize('noFolderWorkspaceDebugError', "The active file can not be debugged. Make sure it is saved and that you have a debug extension installed for that file type."))
.then(() => false);
}
return !!launch && launch.openConfigFile(false, true, undefined, this.initCancellationToken ? this.initCancellationToken.token : undefined).then(() => false);
});
}
if (launch && type && config === null) { // show launch.json only for "config" being "null".
return launch.openConfigFile(false, true, type, this.initCancellationToken ? this.initCancellationToken.token : undefined).then(() => false);
}
return false;
});
});
}
/**
* instantiates the new session, initializes the session, registers session listeners and reports telemetry
*/
private doCreateSession(root: IWorkspaceFolder | undefined, configuration: { resolved: IConfig, unresolved: IConfig | undefined }, parentSession?: IDebugSession): Promise<boolean> {
const session = this.instantiationService.createInstance(DebugSession, configuration, root, this.model, parentSession);
this.model.addSession(session);
// register listeners as the very first thing!
this.registerSessionListeners(session);
// since the Session is now properly registered under its ID and hooked, we can announce it
// this event doesn't go to extensions
this._onWillNewSession.fire(session);
const openDebug = this.configurationService.getValue<IDebugConfiguration>('debug').openDebug;
// Open debug viewlet based on the visibility of the side bar and openDebug setting. Do not open for 'run without debug'
if (!configuration.resolved.noDebug && (openDebug === 'openOnSessionStart' || (openDebug === 'openOnFirstSessionStart' && this.viewModel.firstSessionStart))) {
this.viewletService.openViewlet(VIEWLET_ID).then(undefined, errors.onUnexpectedError);
}
return this.launchOrAttachToSession(session).then(() => {
const internalConsoleOptions = session.configuration.internalConsoleOptions || this.configurationService.getValue<IDebugConfiguration>('debug').internalConsoleOptions;
if (internalConsoleOptions === 'openOnSessionStart' || (this.viewModel.firstSessionStart && internalConsoleOptions === 'openOnFirstSessionStart')) {
this.panelService.openPanel(REPL_ID, false);
}
this.viewModel.firstSessionStart = false;
const showSubSessions = this.configurationService.getValue<IDebugConfiguration>('debug').showSubSessionsInToolBar;
const sessions = this.model.getSessions();
const shownSessions = showSubSessions ? sessions : sessions.filter(s => !s.parentSession);
if (shownSessions.length > 1) {
this.viewModel.setMultiSessionView(true);
}
// since the initialized response has arrived announce the new Session (including extensions)
this._onDidNewSession.fire(session);
return this.telemetryDebugSessionStart(root, session.configuration.type);
}).then(() => true, (error: Error | string) => {
if (errors.isPromiseCanceledError(error)) {
// don't show 'canceled' error messages to the user #7906
return Promise.resolve(false);
}
// Show the repl if some error got logged there #5870
if (session && session.getReplElements().length > 0) {
this.panelService.openPanel(REPL_ID, false);
}
if (session.configuration && session.configuration.request === 'attach' && session.configuration.__autoAttach) {
// ignore attach timeouts in auto attach mode
return Promise.resolve(false);
}
const errorMessage = error instanceof Error ? error.message : error;
this.telemetryDebugMisconfiguration(session.configuration ? session.configuration.type : undefined, errorMessage);
return this.showError(errorMessage, isErrorWithActions(error) ? error.actions : []).then(() => false);
});
}
private launchOrAttachToSession(session: IDebugSession, focus = true): Promise<void> {
const dbgr = this.configurationManager.getDebugger(session.configuration.type);
return session.initialize(dbgr!).then(() => {
return session.launchOrAttach(session.configuration).then(() => {
if (focus) {
this.focusStackFrame(undefined, undefined, session);
}
});
}).then(undefined, err => {
session.shutdown();
return Promise.reject(err);
});
}
private registerSessionListeners(session: IDebugSession): void {
const sessionRunningScheduler = new RunOnceScheduler(() => {
// Do not immediatly defocus the stack frame if the session is running
if (session.state === State.Running && this.viewModel.focusedSession === session) {
this.viewModel.setFocus(undefined, this.viewModel.focusedThread, session, false);
}
}, 200);
this.toDispose.push(session.onDidChangeState(() => {
if (session.state === State.Running && this.viewModel.focusedSession === session) {
sessionRunningScheduler.schedule();
}
if (session === this.viewModel.focusedSession) {
this.onStateChange();
}
}));
this.toDispose.push(session.onDidEndAdapter(adapterExitEvent => {
if (adapterExitEvent.error) {
this.notificationService.error(nls.localize('debugAdapterCrash', "Debug adapter process has terminated unexpectedly ({0})", adapterExitEvent.error.message || adapterExitEvent.error.toString()));
}
// 'Run without debugging' mode VSCode must terminate the extension host. More details: #3905
if (isExtensionHostDebugging(session.configuration) && session.state === State.Running && session.configuration.noDebug) {
this.extensionHostDebugService.close(session.getId());
}
this.telemetryDebugSessionStop(session, adapterExitEvent);
if (session.configuration.postDebugTask) {
this.runTask(session.root, session.configuration.postDebugTask).then(undefined, err =>
this.notificationService.error(err)
);
}
session.shutdown();
this.endInitializingState();
this._onDidEndSession.fire(session);
const focusedSession = this.viewModel.focusedSession;
if (focusedSession && focusedSession.getId() === session.getId()) {
this.focusStackFrame(undefined);
}
if (this.model.getSessions().length === 0) {
this.viewModel.setMultiSessionView(false);
if (this.layoutService.isVisible(Parts.SIDEBAR_PART) && this.configurationService.getValue<IDebugConfiguration>('debug').openExplorerOnEnd) {
this.viewletService.openViewlet(EXPLORER_VIEWLET_ID);
}
// Data breakpoints that can not be persisted should be cleared when a session ends
const dataBreakpoints = this.model.getDataBreakpoints().filter(dbp => !dbp.canPersist);
dataBreakpoints.forEach(dbp => this.model.removeDataBreakpoints(dbp.getId()));
}
}));
}
restartSession(session: IDebugSession, restartData?: any): Promise<any> {
return this.textFileService.saveAll().then(() => {
const isAutoRestart = !!restartData;
const runTasks: () => Promise<TaskRunResult> = () => {
if (isAutoRestart) {
// Do not run preLaunch and postDebug tasks for automatic restarts
return Promise.resolve(TaskRunResult.Success);
}
return this.runTask(session.root, session.configuration.postDebugTask)
.then(() => this.runTaskAndCheckErrors(session.root, session.configuration.preLaunchTask));
};
if (session.capabilities.supportsRestartRequest) {
return runTasks().then(taskResult => taskResult === TaskRunResult.Success ? session.restart() : undefined);
}
if (isExtensionHostDebugging(session.configuration)) {
return runTasks().then(taskResult => taskResult === TaskRunResult.Success ? this.extensionHostDebugService.reload(session.getId()) : undefined);
}
const shouldFocus = this.viewModel.focusedSession && session.getId() === this.viewModel.focusedSession.getId();
// If the restart is automatic -> disconnect, otherwise -> terminate #55064
return (isAutoRestart ? session.disconnect(true) : session.terminate(true)).then(() => {
return new Promise<void>((c, e) => {
setTimeout(() => {
runTasks().then(taskResult => {
if (taskResult !== TaskRunResult.Success) {
return;
}
// Read the configuration again if a launch.json has been changed, if not just use the inmemory configuration
let needsToSubstitute = false;
let unresolved: IConfig | undefined;
const launch = session.root ? this.configurationManager.getLaunch(session.root.uri) : undefined;
if (launch) {
unresolved = launch.getConfiguration(session.configuration.name);
if (unresolved && !equals(unresolved, session.unresolvedConfiguration)) {
// Take the type from the session since the debug extension might overwrite it #21316
unresolved.type = session.configuration.type;
unresolved.noDebug = session.configuration.noDebug;
needsToSubstitute = true;
}
}
let substitutionThenable: Promise<IConfig | null | undefined> = Promise.resolve(session.configuration);
if (launch && needsToSubstitute && unresolved) {
this.initCancellationToken = new CancellationTokenSource();
substitutionThenable = this.configurationManager.resolveConfigurationByProviders(launch.workspace ? launch.workspace.uri : undefined, unresolved.type, unresolved, this.initCancellationToken.token)
.then(resolved => {
if (resolved) {
// start debugging
return this.substituteVariables(launch, resolved);
} else if (resolved === null) {
// abort debugging silently and open launch.json
return Promise.resolve(null);
} else {
// abort debugging silently
return Promise.resolve(undefined);
}
});
}
substitutionThenable.then(resolved => {
if (!resolved) {
return c(undefined);
}
session.setConfiguration({ resolved, unresolved });
session.configuration.__restart = restartData;
this.launchOrAttachToSession(session, shouldFocus).then(() => {
this._onDidNewSession.fire(session);
c(undefined);
}, err => e(err));
});
});
}, 300);
});
});
});
}
stopSession(session: IDebugSession): Promise<any> {
if (session) {
return session.terminate();
}
const sessions = this.model.getSessions();
if (sessions.length === 0) {
this.endInitializingState();
}
return Promise.all(sessions.map(s => s.terminate()));
}
private substituteVariables(launch: ILaunch | undefined, config: IConfig): Promise<IConfig | undefined> {
const dbg = this.configurationManager.getDebugger(config.type);
if (dbg) {
let folder: IWorkspaceFolder | undefined = undefined;
if (launch && launch.workspace) {
folder = launch.workspace;
} else {
const folders = this.contextService.getWorkspace().folders;
if (folders.length === 1) {
folder = folders[0];
}
}
return dbg.substituteVariables(folder, config).then(config => {
return config;
}, (err: Error) => {
this.showError(err.message);
return undefined; // bail out
});
}
return Promise.resolve(config);
}
private showError(message: string, errorActions: ReadonlyArray<IAction> = []): Promise<void> {
const configureAction = this.instantiationService.createInstance(debugactions.ConfigureAction, debugactions.ConfigureAction.ID, debugactions.ConfigureAction.LABEL);
const actions = [...errorActions, configureAction];
return this.dialogService.show(severity.Error, message, actions.map(a => a.label).concat(nls.localize('cancel', "Cancel")), { cancelId: actions.length }).then(choice => {
if (choice < actions.length) {
return actions[choice].run();
}
return undefined;
});
}
//---- task management
private runTaskAndCheckErrors(root: IWorkspaceFolder | undefined, taskId: string | TaskIdentifier | undefined): Promise<TaskRunResult> {
const debugAnywayAction = new Action('debug.debugAnyway', nls.localize('debugAnyway', "Debug Anyway"), undefined, true, () => Promise.resolve(TaskRunResult.Success));
return this.runTask(root, taskId).then((taskSummary: ITaskSummary) => {
const errorCount = taskId ? this.markerService.getStatistics().errors : 0;
const successExitCode = taskSummary && taskSummary.exitCode === 0;
const failureExitCode = taskSummary && taskSummary.exitCode !== undefined && taskSummary.exitCode !== 0;
if (successExitCode || (errorCount === 0 && !failureExitCode)) {
return <any>TaskRunResult.Success;
}
const taskLabel = typeof taskId === 'string' ? taskId : taskId ? taskId.name : '';
const message = errorCount > 1
? nls.localize('preLaunchTaskErrors', "Errors exist after running preLaunchTask '{0}'.", taskLabel)
: errorCount === 1
? nls.localize('preLaunchTaskError', "Error exists after running preLaunchTask '{0}'.", taskLabel)
: nls.localize('preLaunchTaskExitCode', "The preLaunchTask '{0}' terminated with exit code {1}.", taskLabel, taskSummary.exitCode);
const showErrorsAction = new Action('debug.showErrors', nls.localize('showErrors', "Show Errors"), undefined, true, () => {
this.panelService.openPanel(Constants.MARKERS_PANEL_ID);
return Promise.resolve(TaskRunResult.Failure);
});
return this.showError(message, [debugAnywayAction, showErrorsAction]);
}, (err: TaskError) => {
return this.showError(err.message, [debugAnywayAction, this.taskService.configureAction()]);
});
}
private runTask(root: IWorkspaceFolder | undefined, taskId: string | TaskIdentifier | undefined): Promise<ITaskSummary | null> {
if (!taskId) {
return Promise.resolve(null);
}
if (!root) {
return Promise.reject(new Error(nls.localize('invalidTaskReference', "Task '{0}' can not be referenced from a launch configuration that is in a different workspace folder.", typeof taskId === 'string' ? taskId : taskId.type)));
}
// run a task before starting a debug session
return this.taskService.getTask(root, taskId).then(task => {
if (!task) {
const errorMessage = typeof taskId === 'string'
? nls.localize('DebugTaskNotFoundWithTaskId', "Could not find the task '{0}'.", taskId)
: nls.localize('DebugTaskNotFound', "Could not find the specified task.");
return Promise.reject(createErrorWithActions(errorMessage));
}
// If a task is missing the problem matcher the promise will never complete, so we need to have a workaround #35340
let taskStarted = false;
const promise: Promise<ITaskSummary | null> = this.taskService.getActiveTasks().then(tasks => {
if (tasks.filter(t => t._id === task._id).length) {
// task is already running - nothing to do.
return Promise.resolve(null);
}
once(e => ((e.kind === TaskEventKind.Active) || (e.kind === TaskEventKind.DependsOnStarted)) && e.taskId === task._id, this.taskService.onDidStateChange)(() => {
// Task is active, so everything seems to be fine, no need to prompt after 10 seconds
// Use case being a slow running task should not be prompted even though it takes more than 10 seconds
taskStarted = true;
});
const taskPromise = this.taskService.run(task);
if (task.configurationProperties.isBackground) {
return new Promise((c, e) => once(e => e.kind === TaskEventKind.Inactive && e.taskId === task._id, this.taskService.onDidStateChange)(() => {
taskStarted = true;
c(null);
}));
}
return taskPromise;
});
return new Promise((c, e) => {
promise.then(result => {
taskStarted = true;
c(result);
}, error => e(error));
setTimeout(() => {
if (!taskStarted) {
const errorMessage = typeof taskId === 'string'
? nls.localize('taskNotTrackedWithTaskId', "The specified task cannot be tracked.")
: nls.localize('taskNotTracked', "The task '{0}' cannot be tracked.", JSON.stringify(taskId));
e({ severity: severity.Error, message: errorMessage });
}
}, 10000);
});
});
}
//---- focus management
focusStackFrame(stackFrame: IStackFrame | undefined, thread?: IThread, session?: IDebugSession, explicit?: boolean): void {
if (!session) {
if (stackFrame || thread) {
session = stackFrame ? stackFrame.thread.session : thread!.session;
} else {
const sessions = this.model.getSessions();
const stoppedSession = sessions.filter(s => s.state === State.Stopped).shift();
session = stoppedSession || (sessions.length ? sessions[0] : undefined);
}
}
if (!thread) {
if (stackFrame) {
thread = stackFrame.thread;
} else {
const threads = session ? session.getAllThreads() : undefined;
const stoppedThread = threads && threads.filter(t => t.stopped).shift();
thread = stoppedThread || (threads && threads.length ? threads[0] : undefined);
}
}
if (!stackFrame) {
if (thread) {
const callStack = thread.getCallStack();
stackFrame = first(callStack, sf => !!(sf && sf.source && sf.source.available && sf.source.presentationHint !== 'deemphasize'), undefined);
}
}
if (stackFrame) {
stackFrame.openInEditor(this.editorService, true).then(editor => {
if (editor) {
const control = editor.getControl();
if (stackFrame && isCodeEditor(control) && control.hasModel()) {
const model = control.getModel();
if (stackFrame.range.startLineNumber <= model.getLineCount()) {
const lineContent = control.getModel().getLineContent(stackFrame.range.startLineNumber);
aria.alert(nls.localize('debuggingPaused', "Debugging paused {0}, {1} {2} {3}", thread && thread.stoppedDetails ? `, reason ${thread.stoppedDetails.reason}` : '', stackFrame.source ? stackFrame.source.name : '', stackFrame.range.startLineNumber, lineContent));
}
}
}
});
}
if (session) {
this.debugType.set(session.configuration.type);
} else {
this.debugType.reset();
}
this.viewModel.setFocus(stackFrame, thread, session, !!explicit);
}
//---- watches
addWatchExpression(name: string): void {
const we = this.model.addWatchExpression(name);
this.viewModel.setSelectedExpression(we);
this.storeWatchExpressions();
}
renameWatchExpression(id: string, newName: string): void {
this.model.renameWatchExpression(id, newName);
this.storeWatchExpressions();
}
moveWatchExpression(id: string, position: number): void {
this.model.moveWatchExpression(id, position);
this.storeWatchExpressions();
}
removeWatchExpressions(id?: string): void {
this.model.removeWatchExpressions(id);
this.storeWatchExpressions();
}
//---- breakpoints
async enableOrDisableBreakpoints(enable: boolean, breakpoint?: IEnablement): Promise<void> {
if (breakpoint) {
this.model.setEnablement(breakpoint, enable);
if (breakpoint instanceof Breakpoint) {
await this.sendBreakpoints(breakpoint.uri);
} else if (breakpoint instanceof FunctionBreakpoint) {
await this.sendFunctionBreakpoints();
} else if (breakpoint instanceof DataBreakpoint) {
await this.sendDataBreakpoints();
} else {
await this.sendExceptionBreakpoints();
}
} else {
this.model.enableOrDisableAllBreakpoints(enable);
await this.sendAllBreakpoints();
}
this.storeBreakpoints();
}
async addBreakpoints(uri: uri, rawBreakpoints: IBreakpointData[], context: string): Promise<IBreakpoint[]> {
const breakpoints = this.model.addBreakpoints(uri, rawBreakpoints);
breakpoints.forEach(bp => aria.status(nls.localize('breakpointAdded', "Added breakpoint, line {0}, file {1}", bp.lineNumber, uri.fsPath)));
breakpoints.forEach(bp => this.telemetryDebugAddBreakpoint(bp, context));
await this.sendBreakpoints(uri);
this.storeBreakpoints();
return breakpoints;
}
async updateBreakpoints(uri: uri, data: Map<string, DebugProtocol.Breakpoint>, sendOnResourceSaved: boolean): Promise<void> {
this.model.updateBreakpoints(data);
if (sendOnResourceSaved) {
this.breakpointsToSendOnResourceSaved.add(uri.toString());
} else {
await this.sendBreakpoints(uri);
}
this.storeBreakpoints();
}
async removeBreakpoints(id?: string): Promise<void> {
const toRemove = this.model.getBreakpoints().filter(bp => !id || bp.getId() === id);
toRemove.forEach(bp => aria.status(nls.localize('breakpointRemoved', "Removed breakpoint, line {0}, file {1}", bp.lineNumber, bp.uri.fsPath)));
const urisToClear = distinct(toRemove, bp => bp.uri.toString()).map(bp => bp.uri);
this.model.removeBreakpoints(toRemove);
await Promise.all(urisToClear.map(uri => this.sendBreakpoints(uri)));
this.storeBreakpoints();
}
setBreakpointsActivated(activated: boolean): Promise<void> {
this.model.setBreakpointsActivated(activated);
if (activated) {
this.storageService.store(DEBUG_BREAKPOINTS_ACTIVATED_KEY, 'false', StorageScope.WORKSPACE);
} else {
this.storageService.remove(DEBUG_BREAKPOINTS_ACTIVATED_KEY, StorageScope.WORKSPACE);
}
return this.sendAllBreakpoints();
}
addFunctionBreakpoint(name?: string, id?: string): void {
const newFunctionBreakpoint = this.model.addFunctionBreakpoint(name || '', id);
this.viewModel.setSelectedFunctionBreakpoint(newFunctionBreakpoint);
}
async renameFunctionBreakpoint(id: string, newFunctionName: string): Promise<void> {
this.model.renameFunctionBreakpoint(id, newFunctionName);
await this.sendFunctionBreakpoints();
this.storeBreakpoints();
}
async removeFunctionBreakpoints(id?: string): Promise<void> {
this.model.removeFunctionBreakpoints(id);
await this.sendFunctionBreakpoints();
this.storeBreakpoints();
}
async addDataBreakpoint(label: string, dataId: string, canPersist: boolean): Promise<void> {
this.model.addDataBreakpoint(label, dataId, canPersist);
await this.sendDataBreakpoints();
this.storeBreakpoints();
}
async removeDataBreakpoints(id?: string): Promise<void> {
this.model.removeDataBreakpoints(id);
await this.sendDataBreakpoints();
this.storeBreakpoints();
}
sendAllBreakpoints(session?: IDebugSession): Promise<any> {
return Promise.all(distinct(this.model.getBreakpoints(), bp => bp.uri.toString()).map(bp => this.sendBreakpoints(bp.uri, false, session)))
.then(() => this.sendFunctionBreakpoints(session))
// send exception breakpoints at the end since some debug adapters rely on the order
.then(() => this.sendExceptionBreakpoints(session));
}
private sendBreakpoints(modelUri: uri, sourceModified = false, session?: IDebugSession): Promise<void> {
const breakpointsToSend = this.model.getBreakpoints({ uri: modelUri, enabledOnly: true });
return this.sendToOneOrAllSessions(session, s =>
s.sendBreakpoints(modelUri, breakpointsToSend, sourceModified)
);
}
private sendFunctionBreakpoints(session?: IDebugSession): Promise<void> {
const breakpointsToSend = this.model.getFunctionBreakpoints().filter(fbp => fbp.enabled && this.model.areBreakpointsActivated());
return this.sendToOneOrAllSessions(session, s => {
return s.capabilities.supportsFunctionBreakpoints ? s.sendFunctionBreakpoints(breakpointsToSend) : Promise.resolve(undefined);
});
}
private sendDataBreakpoints(session?: IDebugSession): Promise<void> {
const breakpointsToSend = this.model.getDataBreakpoints().filter(fbp => fbp.enabled && this.model.areBreakpointsActivated());
return this.sendToOneOrAllSessions(session, s => {
return s.capabilities.supportsDataBreakpoints ? s.sendDataBreakpoints(breakpointsToSend) : Promise.resolve(undefined);
});
}
private sendExceptionBreakpoints(session?: IDebugSession): Promise<void> {
const enabledExceptionBps = this.model.getExceptionBreakpoints().filter(exb => exb.enabled);
return this.sendToOneOrAllSessions(session, s => {
return s.sendExceptionBreakpoints(enabledExceptionBps);
});
}
private sendToOneOrAllSessions(session: IDebugSession | undefined, send: (session: IDebugSession) => Promise<void>): Promise<void> {
if (session) {
return send(session);
}
return Promise.all(this.model.getSessions().map(s => send(s))).then(() => undefined);
}
private onFileChanges(fileChangesEvent: FileChangesEvent): void {
const toRemove = this.model.getBreakpoints().filter(bp =>
fileChangesEvent.contains(bp.uri, FileChangeType.DELETED));
if (toRemove.length) {
this.model.removeBreakpoints(toRemove);
}
fileChangesEvent.getUpdated().forEach(event => {
if (this.breakpointsToSendOnResourceSaved.delete(event.resource.toString())) {
this.sendBreakpoints(event.resource, true);
}
});
}
private loadBreakpoints(): Breakpoint[] {
let result: Breakpoint[] | undefined;
try {
result = JSON.parse(this.storageService.get(DEBUG_BREAKPOINTS_KEY, StorageScope.WORKSPACE, '[]')).map((breakpoint: any) => {
return new Breakpoint(uri.parse(breakpoint.uri.external || breakpoint.source.uri.external), breakpoint.lineNumber, breakpoint.column, breakpoint.enabled, breakpoint.condition, breakpoint.hitCondition, breakpoint.logMessage, breakpoint.adapterData, this.textFileService);
});
} catch (e) { }
return result || [];
}
private loadFunctionBreakpoints(): FunctionBreakpoint[] {
let result: FunctionBreakpoint[] | undefined;
try {
result = JSON.parse(this.storageService.get(DEBUG_FUNCTION_BREAKPOINTS_KEY, StorageScope.WORKSPACE, '[]')).map((fb: any) => {
return new FunctionBreakpoint(fb.name, fb.enabled, fb.hitCondition, fb.condition, fb.logMessage);
});
} catch (e) { }
return result || [];
}
private loadExceptionBreakpoints(): ExceptionBreakpoint[] {
let result: ExceptionBreakpoint[] | undefined;
try {
result = JSON.parse(this.storageService.get(DEBUG_EXCEPTION_BREAKPOINTS_KEY, StorageScope.WORKSPACE, '[]')).map((exBreakpoint: any) => {
return new ExceptionBreakpoint(exBreakpoint.filter, exBreakpoint.label, exBreakpoint.enabled);
});
} catch (e) { }
return result || [];
}
private loadDataBreakpoints(): DataBreakpoint[] {
let result: DataBreakpoint[] | undefined;
try {
result = JSON.parse(this.storageService.get(DEBUG_DATA_BREAKPOINTS_KEY, StorageScope.WORKSPACE, '[]')).map((dbp: any) => {
return new DataBreakpoint(dbp.label, dbp.dataId, true, dbp.enabled, dbp.hitCondition, dbp.condition, dbp.logMessage);
});
} catch (e) { }
return result || [];
}
private loadWatchExpressions(): Expression[] {
let result: Expression[] | undefined;
try {
result = JSON.parse(this.storageService.get(DEBUG_WATCH_EXPRESSIONS_KEY, StorageScope.WORKSPACE, '[]')).map((watchStoredData: { name: string, id: string }) => {
return new Expression(watchStoredData.name, watchStoredData.id);
});
} catch (e) { }
return result || [];
}
private storeWatchExpressions(): void {
const watchExpressions = this.model.getWatchExpressions();
if (watchExpressions.length) {
this.storageService.store(DEBUG_WATCH_EXPRESSIONS_KEY, JSON.stringify(watchExpressions.map(we => ({ name: we.name, id: we.getId() }))), StorageScope.WORKSPACE);
} else {
this.storageService.remove(DEBUG_WATCH_EXPRESSIONS_KEY, StorageScope.WORKSPACE);
}
}
private storeBreakpoints(): void {
const breakpoints = this.model.getBreakpoints();
if (breakpoints.length) {
this.storageService.store(DEBUG_BREAKPOINTS_KEY, JSON.stringify(breakpoints), StorageScope.WORKSPACE);
} else {
this.storageService.remove(DEBUG_BREAKPOINTS_KEY, StorageScope.WORKSPACE);
}
const functionBreakpoints = this.model.getFunctionBreakpoints();
if (functionBreakpoints.length) {
this.storageService.store(DEBUG_FUNCTION_BREAKPOINTS_KEY, JSON.stringify(functionBreakpoints), StorageScope.WORKSPACE);
} else {
this.storageService.remove(DEBUG_FUNCTION_BREAKPOINTS_KEY, StorageScope.WORKSPACE);
}
const dataBreakpoints = this.model.getDataBreakpoints().filter(dbp => dbp.canPersist);
if (dataBreakpoints.length) {
this.storageService.store(DEBUG_DATA_BREAKPOINTS_KEY, JSON.stringify(dataBreakpoints), StorageScope.WORKSPACE);
} else {
this.storageService.remove(DEBUG_DATA_BREAKPOINTS_KEY, StorageScope.WORKSPACE);
}
const exceptionBreakpoints = this.model.getExceptionBreakpoints();
if (exceptionBreakpoints.length) {
this.storageService.store(DEBUG_EXCEPTION_BREAKPOINTS_KEY, JSON.stringify(exceptionBreakpoints), StorageScope.WORKSPACE);
} else {
this.storageService.remove(DEBUG_EXCEPTION_BREAKPOINTS_KEY, StorageScope.WORKSPACE);
}
}
//---- telemetry
private telemetryDebugSessionStart(root: IWorkspaceFolder | undefined, type: string): Promise<void> {
const dbgr = this.configurationManager.getDebugger(type);
if (!dbgr) {
return Promise.resolve();
}
const extension = dbgr.getMainExtensionDescriptor();
/* __GDPR__
"debugSessionStart" : {
"type": { "classification": "SystemMetaData", "purpose": "FeatureInsight" },
"breakpointCount": { "classification": "SystemMetaData", "purpose": "FeatureInsight", "isMeasurement": true },
"exceptionBreakpoints": { "classification": "SystemMetaData", "purpose": "FeatureInsight" },
"watchExpressionsCount": { "classification": "SystemMetaData", "purpose": "FeatureInsight", "isMeasurement": true },
"extensionName": { "classification": "PublicNonPersonalData", "purpose": "FeatureInsight" },
"isBuiltin": { "classification": "SystemMetaData", "purpose": "FeatureInsight", "isMeasurement": true},
"launchJsonExists": { "classification": "SystemMetaData", "purpose": "FeatureInsight", "isMeasurement": true }
}
*/
return this.telemetryService.publicLog('debugSessionStart', {
type: type,
breakpointCount: this.model.getBreakpoints().length,
exceptionBreakpoints: this.model.getExceptionBreakpoints(),
watchExpressionsCount: this.model.getWatchExpressions().length,
extensionName: extension.identifier.value,
isBuiltin: extension.isBuiltin,
launchJsonExists: root && !!this.configurationService.getValue<IGlobalConfig>('launch', { resource: root.uri })
});
}
private telemetryDebugSessionStop(session: IDebugSession, adapterExitEvent: AdapterEndEvent): Promise<any> {
const breakpoints = this.model.getBreakpoints();
/* __GDPR__
"debugSessionStop" : {
"type" : { "classification": "SystemMetaData", "purpose": "FeatureInsight" },
"success": { "classification": "SystemMetaData", "purpose": "FeatureInsight", "isMeasurement": true },
"sessionLengthInSeconds": { "classification": "SystemMetaData", "purpose": "FeatureInsight", "isMeasurement": true },
"breakpointCount": { "classification": "SystemMetaData", "purpose": "FeatureInsight", "isMeasurement": true },
"watchExpressionsCount": { "classification": "SystemMetaData", "purpose": "FeatureInsight", "isMeasurement": true }
}
*/
return this.telemetryService.publicLog('debugSessionStop', {
type: session && session.configuration.type,
success: adapterExitEvent.emittedStopped || breakpoints.length === 0,
sessionLengthInSeconds: adapterExitEvent.sessionLengthInSeconds,
breakpointCount: breakpoints.length,
watchExpressionsCount: this.model.getWatchExpressions().length
});
}
private telemetryDebugMisconfiguration(debugType: string | undefined, message: string): Promise<any> {
/* __GDPR__
"debugMisconfiguration" : {
"type" : { "classification": "SystemMetaData", "purpose": "FeatureInsight" },
"error": { "classification": "CallstackOrException", "purpose": "FeatureInsight" }
}
*/
return this.telemetryService.publicLog('debugMisconfiguration', {
type: debugType,
error: message
});
}
private telemetryDebugAddBreakpoint(breakpoint: IBreakpoint, context: string): Promise<any> {
/* __GDPR__
"debugAddBreakpoint" : {
"context": { "classification": "SystemMetaData", "purpose": "FeatureInsight" },
"hasCondition": { "classification": "SystemMetaData", "purpose": "FeatureInsight", "isMeasurement": true },
"hasHitCondition": { "classification": "SystemMetaData", "purpose": "FeatureInsight", "isMeasurement": true },
"hasLogMessage": { "classification": "SystemMetaData", "purpose": "FeatureInsight", "isMeasurement": true }
}
*/
return this.telemetryService.publicLog('debugAddBreakpoint', {
context: context,
hasCondition: !!breakpoint.condition,
hasHitCondition: !!breakpoint.hitCondition,
hasLogMessage: !!breakpoint.logMessage
});
}
}
| src/vs/workbench/contrib/debug/browser/debugService.ts | 1 | https://github.com/microsoft/vscode/commit/38aa4766107555dce5e16e15c94135a3c681e497 | [
0.9987732768058777,
0.017562054097652435,
0.000153787768795155,
0.00017314744764007628,
0.12828977406024933
] |
{
"id": 2,
"code_window": [
"\n",
"\t\t\tif (isExtensionHostDebugging(session.configuration)) {\n",
"\t\t\t\treturn runTasks().then(taskResult => taskResult === TaskRunResult.Success ? this.extensionHostDebugService.reload(session.getId()) : undefined);\n",
"\t\t\t}\n",
"\n",
"\t\t\tconst shouldFocus = this.viewModel.focusedSession && session.getId() === this.viewModel.focusedSession.getId();\n",
"\t\t\t// If the restart is automatic -> disconnect, otherwise -> terminate #55064\n",
"\t\t\treturn (isAutoRestart ? session.disconnect(true) : session.terminate(true)).then(() => {\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\t\tconst shouldFocus = !!this.viewModel.focusedSession && session.getId() === this.viewModel.focusedSession.getId();\n"
],
"file_path": "src/vs/workbench/contrib/debug/browser/debugService.ts",
"type": "replace",
"edit_start_line_idx": 574
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import { Widget } from 'vs/base/browser/ui/widget';
import { IOverlayWidget, ICodeEditor, IOverlayWidgetPosition, OverlayWidgetPositionPreference } from 'vs/editor/browser/editorBrowser';
import { Event, Emitter } from 'vs/base/common/event';
import { IKeybindingService } from 'vs/platform/keybinding/common/keybinding';
import { IThemeService } from 'vs/platform/theme/common/themeService';
import { $, append } from 'vs/base/browser/dom';
import { attachStylerCallback } from 'vs/platform/theme/common/styler';
import { buttonBackground, buttonForeground, editorBackground, editorForeground, contrastBorder } from 'vs/platform/theme/common/colorRegistry';
import { IInstantiationService } from 'vs/platform/instantiation/common/instantiation';
import { IWindowService } from 'vs/platform/windows/common/windows';
import { IWorkspaceContextService, WorkbenchState } from 'vs/platform/workspace/common/workspace';
import { hasWorkspaceFileExtension } from 'vs/platform/workspaces/common/workspaces';
import { Disposable, dispose } from 'vs/base/common/lifecycle';
import { localize } from 'vs/nls';
import { IEditorContribution } from 'vs/editor/common/editorCommon';
import { isEqual } from 'vs/base/common/resources';
import { IFileService } from 'vs/platform/files/common/files';
export class FloatingClickWidget extends Widget implements IOverlayWidget {
private readonly _onClick: Emitter<void> = this._register(new Emitter<void>());
readonly onClick: Event<void> = this._onClick.event;
private _domNode: HTMLElement;
constructor(
private editor: ICodeEditor,
private label: string,
keyBindingAction: string,
@IKeybindingService keybindingService: IKeybindingService,
@IThemeService private readonly themeService: IThemeService
) {
super();
if (keyBindingAction) {
const keybinding = keybindingService.lookupKeybinding(keyBindingAction);
if (keybinding) {
this.label += ` (${keybinding.getLabel()})`;
}
}
}
getId(): string {
return 'editor.overlayWidget.floatingClickWidget';
}
getDomNode(): HTMLElement {
return this._domNode;
}
getPosition(): IOverlayWidgetPosition {
return {
preference: OverlayWidgetPositionPreference.BOTTOM_RIGHT_CORNER
};
}
render() {
this._domNode = $('.floating-click-widget');
this._register(attachStylerCallback(this.themeService, { buttonBackground, buttonForeground, editorBackground, editorForeground, contrastBorder }, colors => {
const backgroundColor = colors.buttonBackground ? colors.buttonBackground : colors.editorBackground;
if (backgroundColor) {
this._domNode.style.backgroundColor = backgroundColor.toString();
}
const foregroundColor = colors.buttonForeground ? colors.buttonForeground : colors.editorForeground;
if (foregroundColor) {
this._domNode.style.color = foregroundColor.toString();
}
const borderColor = colors.contrastBorder ? colors.contrastBorder.toString() : null;
this._domNode.style.borderWidth = borderColor ? '1px' : null;
this._domNode.style.borderStyle = borderColor ? 'solid' : null;
this._domNode.style.borderColor = borderColor;
}));
append(this._domNode, $('')).textContent = this.label;
this.onclick(this._domNode, e => this._onClick.fire());
this.editor.addOverlayWidget(this);
}
dispose(): void {
this.editor.removeOverlayWidget(this);
super.dispose();
}
}
export class OpenWorkspaceButtonContribution extends Disposable implements IEditorContribution {
static get(editor: ICodeEditor): OpenWorkspaceButtonContribution {
return editor.getContribution<OpenWorkspaceButtonContribution>(OpenWorkspaceButtonContribution.ID);
}
private static readonly ID = 'editor.contrib.openWorkspaceButton';
private openWorkspaceButton: FloatingClickWidget | undefined;
constructor(
private editor: ICodeEditor,
@IInstantiationService private readonly instantiationService: IInstantiationService,
@IWindowService private readonly windowService: IWindowService,
@IWorkspaceContextService private readonly contextService: IWorkspaceContextService,
@IFileService private readonly fileService: IFileService
) {
super();
this.update();
this.registerListeners();
}
private registerListeners(): void {
this._register(this.editor.onDidChangeModel(e => this.update()));
}
getId(): string {
return OpenWorkspaceButtonContribution.ID;
}
private update(): void {
if (!this.shouldShowButton(this.editor)) {
this.disposeOpenWorkspaceWidgetRenderer();
return;
}
this.createOpenWorkspaceWidgetRenderer();
}
private shouldShowButton(editor: ICodeEditor): boolean {
const model = editor.getModel();
if (!model) {
return false; // we need a model
}
if (!hasWorkspaceFileExtension(model.uri)) {
return false; // we need a workspace file
}
if (!this.fileService.canHandleResource(model.uri)) {
return false; // needs to be backed by a file service
}
if (this.contextService.getWorkbenchState() === WorkbenchState.WORKSPACE) {
const workspaceConfiguration = this.contextService.getWorkspace().configuration;
if (workspaceConfiguration && isEqual(workspaceConfiguration, model.uri)) {
return false; // already inside workspace
}
}
return true;
}
private createOpenWorkspaceWidgetRenderer(): void {
if (!this.openWorkspaceButton) {
this.openWorkspaceButton = this.instantiationService.createInstance(FloatingClickWidget, this.editor, localize('openWorkspace', "Open Workspace"), null);
this._register(this.openWorkspaceButton.onClick(() => {
const model = this.editor.getModel();
if (model) {
this.windowService.openWindow([{ workspaceUri: model.uri }]);
}
}));
this.openWorkspaceButton.render();
}
}
private disposeOpenWorkspaceWidgetRenderer(): void {
dispose(this.openWorkspaceButton);
this.openWorkspaceButton = undefined;
}
dispose(): void {
this.disposeOpenWorkspaceWidgetRenderer();
super.dispose();
}
} | src/vs/workbench/browser/parts/editor/editorWidgets.ts | 0 | https://github.com/microsoft/vscode/commit/38aa4766107555dce5e16e15c94135a3c681e497 | [
0.00039946852484717965,
0.0001867059472715482,
0.00015874394739512354,
0.00017112305795308203,
0.000054207070206757635
] |
{
"id": 2,
"code_window": [
"\n",
"\t\t\tif (isExtensionHostDebugging(session.configuration)) {\n",
"\t\t\t\treturn runTasks().then(taskResult => taskResult === TaskRunResult.Success ? this.extensionHostDebugService.reload(session.getId()) : undefined);\n",
"\t\t\t}\n",
"\n",
"\t\t\tconst shouldFocus = this.viewModel.focusedSession && session.getId() === this.viewModel.focusedSession.getId();\n",
"\t\t\t// If the restart is automatic -> disconnect, otherwise -> terminate #55064\n",
"\t\t\treturn (isAutoRestart ? session.disconnect(true) : session.terminate(true)).then(() => {\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\t\tconst shouldFocus = !!this.viewModel.focusedSession && session.getId() === this.viewModel.focusedSession.getId();\n"
],
"file_path": "src/vs/workbench/contrib/debug/browser/debugService.ts",
"type": "replace",
"edit_start_line_idx": 574
} | /*---------------------------------------------------------------------------------------------
* 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 { IssueReporterModel } from 'vs/code/electron-browser/issue/issueReporterModel';
import { normalizeGitHubUrl } from 'vs/code/electron-browser/issue/issueReporterUtil';
import { IssueType } from 'vs/platform/issue/node/issue';
suite('IssueReporter', () => {
test('sets defaults to include all data', () => {
const issueReporterModel = new IssueReporterModel();
assert.deepEqual(issueReporterModel.getData(), {
allExtensions: [],
includeSystemInfo: true,
includeWorkspaceInfo: true,
includeProcessInfo: true,
includeExtensions: true,
includeSearchedExtensions: true,
includeSettingsSearchDetails: true,
issueType: 0
});
});
test('serializes model skeleton when no data is provided', () => {
const issueReporterModel = new IssueReporterModel({});
assert.equal(issueReporterModel.serialize(),
`
Issue Type: <b>Bug</b>
undefined
VS Code version: undefined
OS version: undefined
Extensions: none
<!-- generated by issue reporter -->`);
});
test('serializes GPU information when data is provided', () => {
const issueReporterModel = new IssueReporterModel({
issueType: 0,
systemInfo: {
os: 'Darwin',
cpus: 'Intel(R) Core(TM) i7-7700HQ CPU @ 2.80GHz (8 x 2800)',
memory: '16.00GB',
vmHint: '0%',
processArgs: '',
screenReader: 'no',
remoteData: [],
gpuStatus: {
'2d_canvas': 'enabled',
'checker_imaging': 'disabled_off'
}
}
});
assert.equal(issueReporterModel.serialize(),
`
Issue Type: <b>Bug</b>
undefined
VS Code version: undefined
OS version: undefined
<details>
<summary>System Info</summary>
|Item|Value|
|---|---|
|CPUs|Intel(R) Core(TM) i7-7700HQ CPU @ 2.80GHz (8 x 2800)|
|GPU Status|2d_canvas: enabled<br>checker_imaging: disabled_off|
|Load (avg)|undefined|
|Memory (System)|16.00GB|
|Process Argv||
|Screen Reader|no|
|VM|0%|
</details>Extensions: none
<!-- generated by issue reporter -->`);
});
test('serializes remote information when data is provided', () => {
const issueReporterModel = new IssueReporterModel({
issueType: 0,
systemInfo: {
os: 'Darwin',
cpus: 'Intel(R) Core(TM) i7-7700HQ CPU @ 2.80GHz (8 x 2800)',
memory: '16.00GB',
vmHint: '0%',
processArgs: '',
screenReader: 'no',
gpuStatus: {
'2d_canvas': 'enabled',
'checker_imaging': 'disabled_off'
},
remoteData: [
{
hostName: 'SSH: Pineapple',
machineInfo: {
os: 'Linux x64 4.18.0',
cpus: 'Intel(R) Xeon(R) CPU E5-2673 v4 @ 2.30GHz (2 x 2294)',
memory: '8GB',
vmHint: '100%'
}
}
]
}
});
assert.equal(issueReporterModel.serialize(),
`
Issue Type: <b>Bug</b>
undefined
VS Code version: undefined
OS version: undefined
Remote OS version: Linux x64 4.18.0
<details>
<summary>System Info</summary>
|Item|Value|
|---|---|
|CPUs|Intel(R) Core(TM) i7-7700HQ CPU @ 2.80GHz (8 x 2800)|
|GPU Status|2d_canvas: enabled<br>checker_imaging: disabled_off|
|Load (avg)|undefined|
|Memory (System)|16.00GB|
|Process Argv||
|Screen Reader|no|
|VM|0%|
|Item|Value|
|---|---|
|Remote|SSH: Pineapple|
|OS|Linux x64 4.18.0|
|CPUs|Intel(R) Xeon(R) CPU E5-2673 v4 @ 2.30GHz (2 x 2294)|
|Memory (System)|8GB|
|VM|100%|
</details>Extensions: none
<!-- generated by issue reporter -->`);
});
test('should normalize GitHub urls', () => {
[
'https://github.com/repo',
'https://github.com/repo/',
'https://github.com/repo.git',
'https://github.com/repo/issues',
'https://github.com/repo/issues/',
'https://github.com/repo/issues/new',
'https://github.com/repo/issues/new/'
].forEach(url => {
assert.equal('https://github.com/repo', normalizeGitHubUrl(url));
});
});
test('should have support for filing on extensions for bugs, performance issues, and feature requests', () => {
[
IssueType.Bug,
IssueType.FeatureRequest,
IssueType.PerformanceIssue
].forEach(type => {
const issueReporterModel = new IssueReporterModel({
issueType: type,
fileOnExtension: true
});
assert.equal(issueReporterModel.fileOnExtension(), true);
});
[
IssueType.SettingsSearchIssue
].forEach(type => {
const issueReporterModel = new IssueReporterModel({
issueType: type,
fileOnExtension: true
});
assert.equal(issueReporterModel.fileOnExtension(), false);
});
});
});
| src/vs/code/electron-browser/issue/test/testReporterModel.test.ts | 0 | https://github.com/microsoft/vscode/commit/38aa4766107555dce5e16e15c94135a3c681e497 | [
0.0001749902730807662,
0.00017135837697423995,
0.00016851966211106628,
0.0001710584620013833,
0.0000017112267869379139
] |
{
"id": 2,
"code_window": [
"\n",
"\t\t\tif (isExtensionHostDebugging(session.configuration)) {\n",
"\t\t\t\treturn runTasks().then(taskResult => taskResult === TaskRunResult.Success ? this.extensionHostDebugService.reload(session.getId()) : undefined);\n",
"\t\t\t}\n",
"\n",
"\t\t\tconst shouldFocus = this.viewModel.focusedSession && session.getId() === this.viewModel.focusedSession.getId();\n",
"\t\t\t// If the restart is automatic -> disconnect, otherwise -> terminate #55064\n",
"\t\t\treturn (isAutoRestart ? session.disconnect(true) : session.terminate(true)).then(() => {\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\t\tconst shouldFocus = !!this.viewModel.focusedSession && session.getId() === this.viewModel.focusedSession.getId();\n"
],
"file_path": "src/vs/workbench/contrib/debug/browser/debugService.ts",
"type": "replace",
"edit_start_line_idx": 574
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import * as arrays from 'vs/base/common/arrays';
import { CancellationToken } from 'vs/base/common/cancellation';
import { canceled } from 'vs/base/common/errors';
import { Disposable, IDisposable, toDisposable } from 'vs/base/common/lifecycle';
import { keys, ResourceMap, values } from 'vs/base/common/map';
import { Schemas } from 'vs/base/common/network';
import { StopWatch } from 'vs/base/common/stopwatch';
import { URI as uri } from 'vs/base/common/uri';
import { IModelService } from 'vs/editor/common/services/modelService';
import { IFileService } from 'vs/platform/files/common/files';
import { ILogService } from 'vs/platform/log/common/log';
import { ITelemetryService } from 'vs/platform/telemetry/common/telemetry';
import { IEditorService } from 'vs/workbench/services/editor/common/editorService';
import { IExtensionService } from 'vs/workbench/services/extensions/common/extensions';
import { deserializeSearchError, FileMatch, ICachedSearchStats, IFileMatch, IFileQuery, IFileSearchStats, IFolderQuery, IProgressMessage, ISearchComplete, ISearchEngineStats, ISearchProgressItem, ISearchQuery, ISearchResultProvider, ISearchService, ITextQuery, pathIncludedInQuery, QueryType, SearchError, SearchErrorCode, SearchProviderType, isFileMatch, isProgressMessage } from 'vs/workbench/services/search/common/search';
import { addContextToEditorMatches, editorMatchesToTextSearchResults } from 'vs/workbench/services/search/common/searchHelpers';
import { IUntitledEditorService } from 'vs/workbench/services/untitled/common/untitledEditorService';
import { registerSingleton } from 'vs/platform/instantiation/common/extensions';
import { ServiceIdentifier } from 'vs/platform/instantiation/common/instantiation';
export class SearchService extends Disposable implements ISearchService {
_serviceBrand!: ServiceIdentifier<any>;
protected diskSearch: ISearchResultProvider;
private readonly fileSearchProviders = new Map<string, ISearchResultProvider>();
private readonly textSearchProviders = new Map<string, ISearchResultProvider>();
constructor(
private readonly modelService: IModelService,
private readonly untitledEditorService: IUntitledEditorService,
private readonly editorService: IEditorService,
private readonly telemetryService: ITelemetryService,
private readonly logService: ILogService,
private readonly extensionService: IExtensionService,
private readonly fileService: IFileService
) {
super();
}
registerSearchResultProvider(scheme: string, type: SearchProviderType, provider: ISearchResultProvider): IDisposable {
let list: Map<string, ISearchResultProvider>;
if (type === SearchProviderType.file) {
list = this.fileSearchProviders;
} else if (type === SearchProviderType.text) {
list = this.textSearchProviders;
} else {
throw new Error('Unknown SearchProviderType');
}
list.set(scheme, provider);
return toDisposable(() => {
list.delete(scheme);
});
}
textSearch(query: ITextQuery, token?: CancellationToken, onProgress?: (item: ISearchProgressItem) => void): Promise<ISearchComplete> {
// Get local results from dirty/untitled
const localResults = this.getLocalResults(query);
if (onProgress) {
arrays.coalesce(localResults.values()).forEach(onProgress);
}
const onProviderProgress = (progress: ISearchProgressItem) => {
if (isFileMatch(progress)) {
// Match
if (!localResults.has(progress.resource) && onProgress) { // don't override local results
onProgress(progress);
}
} else if (onProgress) {
// Progress
onProgress(<IProgressMessage>progress);
}
if (isProgressMessage(progress)) {
this.logService.debug('SearchService#search', progress.message);
}
};
return this.doSearch(query, token, onProviderProgress);
}
fileSearch(query: IFileQuery, token?: CancellationToken): Promise<ISearchComplete> {
return this.doSearch(query, token);
}
private doSearch(query: ISearchQuery, token?: CancellationToken, onProgress?: (item: ISearchProgressItem) => void): Promise<ISearchComplete> {
this.logService.trace('SearchService#search', JSON.stringify(query));
const schemesInQuery = this.getSchemesInQuery(query);
const providerActivations: Promise<any>[] = [Promise.resolve(null)];
schemesInQuery.forEach(scheme => providerActivations.push(this.extensionService.activateByEvent(`onSearch:${scheme}`)));
providerActivations.push(this.extensionService.activateByEvent('onSearch:file'));
const providerPromise = Promise.all(providerActivations)
.then(() => this.extensionService.whenInstalledExtensionsRegistered())
.then(() => {
// Cancel faster if search was canceled while waiting for extensions
if (token && token.isCancellationRequested) {
return Promise.reject(canceled());
}
const progressCallback = (item: ISearchProgressItem) => {
if (token && token.isCancellationRequested) {
return;
}
if (onProgress) {
onProgress(item);
}
};
return this.searchWithProviders(query, progressCallback, token);
})
.then(completes => {
completes = arrays.coalesce(completes);
if (!completes.length) {
return {
limitHit: false,
results: []
};
}
return <ISearchComplete>{
limitHit: completes[0] && completes[0].limitHit,
stats: completes[0].stats,
results: arrays.flatten(completes.map((c: ISearchComplete) => c.results))
};
});
return new Promise((resolve, reject) => {
if (token) {
token.onCancellationRequested(() => {
reject(canceled());
});
}
providerPromise.then(resolve, reject);
});
}
private getSchemesInQuery(query: ISearchQuery): Set<string> {
const schemes = new Set<string>();
if (query.folderQueries) {
query.folderQueries.forEach(fq => schemes.add(fq.folder.scheme));
}
if (query.extraFileResources) {
query.extraFileResources.forEach(extraFile => schemes.add(extraFile.scheme));
}
return schemes;
}
private searchWithProviders(query: ISearchQuery, onProviderProgress: (progress: ISearchProgressItem) => void, token?: CancellationToken) {
const e2eSW = StopWatch.create(false);
const diskSearchQueries: IFolderQuery[] = [];
const searchPs: Promise<ISearchComplete>[] = [];
const fqs = this.groupFolderQueriesByScheme(query);
keys(fqs).forEach(scheme => {
const schemeFQs = fqs.get(scheme)!;
const provider = query.type === QueryType.File ?
this.fileSearchProviders.get(scheme) :
this.textSearchProviders.get(scheme);
if (!provider && scheme === 'file') {
diskSearchQueries.push(...schemeFQs);
} else if (!provider) {
console.warn('No search provider registered for scheme: ' + scheme);
} else {
const oneSchemeQuery: ISearchQuery = {
...query,
...{
folderQueries: schemeFQs
}
};
searchPs.push(query.type === QueryType.File ?
provider.fileSearch(<IFileQuery>oneSchemeQuery, token) :
provider.textSearch(<ITextQuery>oneSchemeQuery, onProviderProgress, token));
}
});
const diskSearchExtraFileResources = query.extraFileResources && query.extraFileResources.filter(res => res.scheme === Schemas.file);
if (diskSearchQueries.length || diskSearchExtraFileResources) {
const diskSearchQuery: ISearchQuery = {
...query,
...{
folderQueries: diskSearchQueries
},
extraFileResources: diskSearchExtraFileResources
};
if (this.diskSearch) {
searchPs.push(diskSearchQuery.type === QueryType.File ?
this.diskSearch.fileSearch(diskSearchQuery, token) :
this.diskSearch.textSearch(diskSearchQuery, onProviderProgress, token));
}
}
return Promise.all(searchPs).then(completes => {
const endToEndTime = e2eSW.elapsed();
this.logService.trace(`SearchService#search: ${endToEndTime}ms`);
completes.forEach(complete => {
this.sendTelemetry(query, endToEndTime, complete);
});
return completes;
}, err => {
const endToEndTime = e2eSW.elapsed();
this.logService.trace(`SearchService#search: ${endToEndTime}ms`);
const searchError = deserializeSearchError(err.message);
this.sendTelemetry(query, endToEndTime, undefined, searchError);
throw searchError;
});
}
private groupFolderQueriesByScheme(query: ISearchQuery): Map<string, IFolderQuery[]> {
const queries = new Map<string, IFolderQuery[]>();
query.folderQueries.forEach(fq => {
const schemeFQs = queries.get(fq.folder.scheme) || [];
schemeFQs.push(fq);
queries.set(fq.folder.scheme, schemeFQs);
});
return queries;
}
private sendTelemetry(query: ISearchQuery, endToEndTime: number, complete?: ISearchComplete, err?: SearchError): void {
const fileSchemeOnly = query.folderQueries.every(fq => fq.folder.scheme === 'file');
const otherSchemeOnly = query.folderQueries.every(fq => fq.folder.scheme !== 'file');
const scheme = fileSchemeOnly ? 'file' :
otherSchemeOnly ? 'other' :
'mixed';
if (query.type === QueryType.File && complete && complete.stats) {
const fileSearchStats = complete.stats as IFileSearchStats;
if (fileSearchStats.fromCache) {
const cacheStats: ICachedSearchStats = fileSearchStats.detailStats as ICachedSearchStats;
type CachedSearchCompleteClassifcation = {
reason?: { classification: 'SystemMetaData', purpose: 'PerformanceAndHealth' };
resultCount: { classification: 'SystemMetaData', purpose: 'PerformanceAndHealth', isMeasurement: true };
workspaceFolderCount: { classification: 'SystemMetaData', purpose: 'PerformanceAndHealth', isMeasurement: true };
type: { classification: 'SystemMetaData', purpose: 'PerformanceAndHealth' };
endToEndTime: { classification: 'SystemMetaData', purpose: 'PerformanceAndHealth', isMeasurement: true };
sortingTime?: { classification: 'SystemMetaData', purpose: 'PerformanceAndHealth', isMeasurement: true };
cacheWasResolved: { classification: 'SystemMetaData', purpose: 'PerformanceAndHealth' };
cacheLookupTime: { classification: 'SystemMetaData', purpose: 'PerformanceAndHealth', isMeasurement: true };
cacheFilterTime: { classification: 'SystemMetaData', purpose: 'PerformanceAndHealth', isMeasurement: true };
cacheEntryCount: { classification: 'SystemMetaData', purpose: 'PerformanceAndHealth', isMeasurement: true };
scheme: { classification: 'SystemMetaData', purpose: 'PerformanceAndHealth' };
};
type CachedSearchCompleteEvent = {
reason?: string;
resultCount: number;
workspaceFolderCount: number;
type: 'fileSearchProvider' | 'searchProcess';
endToEndTime: number;
sortingTime?: number;
cacheWasResolved: boolean;
cacheLookupTime: number;
cacheFilterTime: number;
cacheEntryCount: number;
scheme: string;
};
this.telemetryService.publicLog2<CachedSearchCompleteEvent, CachedSearchCompleteClassifcation>('cachedSearchComplete', {
reason: query._reason,
resultCount: fileSearchStats.resultCount,
workspaceFolderCount: query.folderQueries.length,
type: fileSearchStats.type,
endToEndTime: endToEndTime,
sortingTime: fileSearchStats.sortingTime,
cacheWasResolved: cacheStats.cacheWasResolved,
cacheLookupTime: cacheStats.cacheLookupTime,
cacheFilterTime: cacheStats.cacheFilterTime,
cacheEntryCount: cacheStats.cacheEntryCount,
scheme
});
} else {
const searchEngineStats: ISearchEngineStats = fileSearchStats.detailStats as ISearchEngineStats;
type SearchCompleteClassification = {
reason?: { classification: 'SystemMetaData', purpose: 'PerformanceAndHealth' };
resultCount: { classification: 'SystemMetaData', purpose: 'PerformanceAndHealth', isMeasurement: true };
workspaceFolderCount: { classification: 'SystemMetaData', purpose: 'PerformanceAndHealth', isMeasurement: true };
type: { classification: 'SystemMetaData', purpose: 'PerformanceAndHealth' };
endToEndTime: { classification: 'SystemMetaData', purpose: 'PerformanceAndHealth', isMeasurement: true };
sortingTime?: { classification: 'SystemMetaData', purpose: 'PerformanceAndHealth', isMeasurement: true };
fileWalkTime: { classification: 'SystemMetaData', purpose: 'PerformanceAndHealth', isMeasurement: true };
directoriesWalked: { classification: 'SystemMetaData', purpose: 'PerformanceAndHealth', isMeasurement: true };
filesWalked: { classification: 'SystemMetaData', purpose: 'PerformanceAndHealth', isMeasurement: true };
cmdTime: { classification: 'SystemMetaData', purpose: 'PerformanceAndHealth', isMeasurement: true };
cmdResultCount?: { classification: 'SystemMetaData', purpose: 'PerformanceAndHealth', isMeasurement: true };
scheme: { classification: 'SystemMetaData', purpose: 'PerformanceAndHealth' };
};
type SearchCompleteEvent = {
reason?: string;
resultCount: number;
workspaceFolderCount: number;
type: 'fileSearchProvider' | 'searchProcess';
endToEndTime: number;
sortingTime?: number;
fileWalkTime: number
directoriesWalked: number;
filesWalked: number;
cmdTime: number;
cmdResultCount?: number;
scheme: string;
};
this.telemetryService.publicLog2<SearchCompleteEvent, SearchCompleteClassification>('searchComplete', {
reason: query._reason,
resultCount: fileSearchStats.resultCount,
workspaceFolderCount: query.folderQueries.length,
type: fileSearchStats.type,
endToEndTime: endToEndTime,
sortingTime: fileSearchStats.sortingTime,
fileWalkTime: searchEngineStats.fileWalkTime,
directoriesWalked: searchEngineStats.directoriesWalked,
filesWalked: searchEngineStats.filesWalked,
cmdTime: searchEngineStats.cmdTime,
cmdResultCount: searchEngineStats.cmdResultCount,
scheme
});
}
} else if (query.type === QueryType.Text) {
let errorType: string | undefined;
if (err) {
errorType = err.code === SearchErrorCode.regexParseError ? 'regex' :
err.code === SearchErrorCode.unknownEncoding ? 'encoding' :
err.code === SearchErrorCode.globParseError ? 'glob' :
err.code === SearchErrorCode.invalidLiteral ? 'literal' :
err.code === SearchErrorCode.other ? 'other' :
'unknown';
}
type TextSearchCompleteClassification = {
reason?: { classification: 'SystemMetaData', purpose: 'PerformanceAndHealth' };
workspaceFolderCount: { classification: 'SystemMetaData', purpose: 'PerformanceAndHealth', isMeasurement: true };
endToEndTime: { classification: 'SystemMetaData', purpose: 'PerformanceAndHealth', isMeasurement: true };
scheme: { classification: 'SystemMetaData', purpose: 'PerformanceAndHealth' };
error?: { classification: 'SystemMetaData', purpose: 'PerformanceAndHealth' };
usePCRE2: { classification: 'SystemMetaData', purpose: 'PerformanceAndHealth' };
};
type TextSearchCompleteEvent = {
reason?: string;
workspaceFolderCount: number;
endToEndTime: number;
scheme: string;
error?: string;
usePCRE2: boolean;
};
this.telemetryService.publicLog2<TextSearchCompleteEvent, TextSearchCompleteClassification>('textSearchComplete', {
reason: query._reason,
workspaceFolderCount: query.folderQueries.length,
endToEndTime: endToEndTime,
scheme,
error: errorType,
usePCRE2: !!query.usePCRE2
});
}
}
private getLocalResults(query: ITextQuery): ResourceMap<IFileMatch | null> {
const localResults = new ResourceMap<IFileMatch | null>();
if (query.type === QueryType.Text) {
const models = this.modelService.getModels();
models.forEach((model) => {
const resource = model.uri;
if (!resource) {
return;
}
if (!this.editorService.isOpen({ resource })) {
return;
}
// Support untitled files
if (resource.scheme === Schemas.untitled) {
if (!this.untitledEditorService.exists(resource)) {
return;
}
}
// Block walkthrough, webview, etc.
else if (!this.fileService.canHandleResource(resource)) {
return;
}
if (!this.matches(resource, query)) {
return; // respect user filters
}
// Use editor API to find matches
const matches = model.findMatches(query.contentPattern.pattern, false, !!query.contentPattern.isRegExp, !!query.contentPattern.isCaseSensitive, query.contentPattern.isWordMatch ? query.contentPattern.wordSeparators! : null, false, query.maxResults);
if (matches.length) {
const fileMatch = new FileMatch(resource);
localResults.set(resource, fileMatch);
const textSearchResults = editorMatchesToTextSearchResults(matches, model, query.previewOptions);
fileMatch.results = addContextToEditorMatches(textSearchResults, model, query);
} else {
localResults.set(resource, null);
}
});
}
return localResults;
}
private matches(resource: uri, query: ITextQuery): boolean {
return pathIncludedInQuery(query, resource.fsPath);
}
clearCache(cacheKey: string): Promise<void> {
const clearPs = [
this.diskSearch,
...values(this.fileSearchProviders)
].map(provider => provider && provider.clearCache(cacheKey));
return Promise.all(clearPs)
.then(() => { });
}
}
export class RemoteSearchService extends SearchService {
constructor(
@IModelService modelService: IModelService,
@IUntitledEditorService untitledEditorService: IUntitledEditorService,
@IEditorService editorService: IEditorService,
@ITelemetryService telemetryService: ITelemetryService,
@ILogService logService: ILogService,
@IExtensionService extensionService: IExtensionService,
@IFileService fileService: IFileService
) {
super(modelService, untitledEditorService, editorService, telemetryService, logService, extensionService, fileService);
}
}
registerSingleton(ISearchService, RemoteSearchService, true);
| src/vs/workbench/services/search/common/searchService.ts | 0 | https://github.com/microsoft/vscode/commit/38aa4766107555dce5e16e15c94135a3c681e497 | [
0.00019307120237499475,
0.00017251803365070373,
0.00016400426102336496,
0.0001724488101899624,
0.000003789634547501919
] |
{
"id": 3,
"code_window": [
"\t}\n",
"\n",
"\tprivate registerListeners(): void {\n",
"\t\tthis._register(this.debugService.onDidChangeState(() => this.updateScheduler.schedule()));\n",
"\t\tthis._register(this.debugService.getViewModel().onDidFocusSession(() => this.updateScheduler.schedule()));\n",
"\t\tthis._register(this.configurationService.onDidChangeConfiguration(e => this.onDidConfigurationChange(e)));\n",
"\t\tthis._register(this.actionBar.actionRunner.onDidRun((e: IRunEvent) => {\n",
"\t\t\t// check for error\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\tthis._register(this.debugService.onDidNewSession(() => this.updateScheduler.schedule()));\n"
],
"file_path": "src/vs/workbench/contrib/debug/browser/debugToolBar.ts",
"type": "add",
"edit_start_line_idx": 133
} | /*---------------------------------------------------------------------------------------------
* 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 { Event, Emitter } from 'vs/base/common/event';
import { URI as uri } from 'vs/base/common/uri';
import { first, distinct } from 'vs/base/common/arrays';
import * as errors from 'vs/base/common/errors';
import severity from 'vs/base/common/severity';
import * as aria from 'vs/base/browser/ui/aria/aria';
import { IContextKeyService, IContextKey } from 'vs/platform/contextkey/common/contextkey';
import { IMarkerService } from 'vs/platform/markers/common/markers';
import { ILifecycleService } from 'vs/platform/lifecycle/common/lifecycle';
import { IExtensionService } from 'vs/workbench/services/extensions/common/extensions';
import { IInstantiationService } from 'vs/platform/instantiation/common/instantiation';
import { FileChangesEvent, FileChangeType, IFileService } from 'vs/platform/files/common/files';
import { ITelemetryService } from 'vs/platform/telemetry/common/telemetry';
import { IStorageService, StorageScope } from 'vs/platform/storage/common/storage';
import { DebugModel, ExceptionBreakpoint, FunctionBreakpoint, Breakpoint, Expression, DataBreakpoint } from 'vs/workbench/contrib/debug/common/debugModel';
import { ViewModel } from 'vs/workbench/contrib/debug/common/debugViewModel';
import * as debugactions from 'vs/workbench/contrib/debug/browser/debugActions';
import { ConfigurationManager } from 'vs/workbench/contrib/debug/browser/debugConfigurationManager';
import Constants from 'vs/workbench/contrib/markers/browser/constants';
import { ITaskService, ITaskSummary } from 'vs/workbench/contrib/tasks/common/taskService';
import { TaskError } from 'vs/workbench/contrib/tasks/common/taskSystem';
import { VIEWLET_ID as EXPLORER_VIEWLET_ID } from 'vs/workbench/contrib/files/common/files';
import { IViewletService } from 'vs/workbench/services/viewlet/browser/viewlet';
import { IPanelService } from 'vs/workbench/services/panel/common/panelService';
import { IWorkbenchLayoutService, Parts } from 'vs/workbench/services/layout/browser/layoutService';
import { ITextFileService } from 'vs/workbench/services/textfile/common/textfiles';
import { IConfigurationService } from 'vs/platform/configuration/common/configuration';
import { IWorkspaceContextService, WorkbenchState, IWorkspaceFolder } from 'vs/platform/workspace/common/workspace';
import { IEditorService } from 'vs/workbench/services/editor/common/editorService';
import { parse, getFirstFrame } from 'vs/base/common/console';
import { TaskEvent, TaskEventKind, TaskIdentifier } from 'vs/workbench/contrib/tasks/common/tasks';
import { IDialogService } from 'vs/platform/dialogs/common/dialogs';
import { INotificationService } from 'vs/platform/notification/common/notification';
import { IAction, Action } from 'vs/base/common/actions';
import { deepClone, equals } from 'vs/base/common/objects';
import { DebugSession } from 'vs/workbench/contrib/debug/browser/debugSession';
import { dispose, IDisposable } from 'vs/base/common/lifecycle';
import { IDebugService, State, IDebugSession, CONTEXT_DEBUG_TYPE, CONTEXT_DEBUG_STATE, CONTEXT_IN_DEBUG_MODE, IThread, IDebugConfiguration, VIEWLET_ID, REPL_ID, IConfig, ILaunch, IViewModel, IConfigurationManager, IDebugModel, IEnablement, IBreakpoint, IBreakpointData, ICompound, IGlobalConfig, IStackFrame, AdapterEndEvent, getStateLabel } from 'vs/workbench/contrib/debug/common/debug';
import { isExtensionHostDebugging } from 'vs/workbench/contrib/debug/common/debugUtils';
import { isErrorWithActions, createErrorWithActions } from 'vs/base/common/errorsWithActions';
import { RunOnceScheduler } from 'vs/base/common/async';
import { IExtensionHostDebugService } from 'vs/platform/debug/common/extensionHostDebug';
import { isCodeEditor } from 'vs/editor/browser/editorBrowser';
import { CancellationTokenSource } from 'vs/base/common/cancellation';
const DEBUG_BREAKPOINTS_KEY = 'debug.breakpoint';
const DEBUG_BREAKPOINTS_ACTIVATED_KEY = 'debug.breakpointactivated';
const DEBUG_FUNCTION_BREAKPOINTS_KEY = 'debug.functionbreakpoint';
const DEBUG_DATA_BREAKPOINTS_KEY = 'debug.databreakpoint';
const DEBUG_EXCEPTION_BREAKPOINTS_KEY = 'debug.exceptionbreakpoint';
const DEBUG_WATCH_EXPRESSIONS_KEY = 'debug.watchexpressions';
function once(match: (e: TaskEvent) => boolean, event: Event<TaskEvent>): Event<TaskEvent> {
return (listener, thisArgs = null, disposables?) => {
const result = event(e => {
if (match(e)) {
result.dispose();
return listener.call(thisArgs, e);
}
}, null, disposables);
return result;
};
}
const enum TaskRunResult {
Failure,
Success
}
export class DebugService implements IDebugService {
_serviceBrand: any;
private readonly _onDidChangeState: Emitter<State>;
private readonly _onDidNewSession: Emitter<IDebugSession>;
private readonly _onWillNewSession: Emitter<IDebugSession>;
private readonly _onDidEndSession: Emitter<IDebugSession>;
private model: DebugModel;
private viewModel: ViewModel;
private configurationManager: ConfigurationManager;
private toDispose: IDisposable[];
private debugType: IContextKey<string>;
private debugState: IContextKey<string>;
private inDebugMode: IContextKey<boolean>;
private breakpointsToSendOnResourceSaved: Set<string>;
private initializing = false;
private previousState: State | undefined;
private initCancellationToken: CancellationTokenSource | undefined;
constructor(
@IStorageService private readonly storageService: IStorageService,
@IEditorService private readonly editorService: IEditorService,
@ITextFileService private readonly textFileService: ITextFileService,
@IViewletService private readonly viewletService: IViewletService,
@IPanelService private readonly panelService: IPanelService,
@INotificationService private readonly notificationService: INotificationService,
@IDialogService private readonly dialogService: IDialogService,
@IWorkbenchLayoutService private readonly layoutService: IWorkbenchLayoutService,
@ITelemetryService private readonly telemetryService: ITelemetryService,
@IWorkspaceContextService private readonly contextService: IWorkspaceContextService,
@IContextKeyService contextKeyService: IContextKeyService,
@ILifecycleService private readonly lifecycleService: ILifecycleService,
@IInstantiationService private readonly instantiationService: IInstantiationService,
@IExtensionService private readonly extensionService: IExtensionService,
@IMarkerService private readonly markerService: IMarkerService,
@ITaskService private readonly taskService: ITaskService,
@IFileService private readonly fileService: IFileService,
@IConfigurationService private readonly configurationService: IConfigurationService,
@IExtensionHostDebugService private readonly extensionHostDebugService: IExtensionHostDebugService
) {
this.toDispose = [];
this.breakpointsToSendOnResourceSaved = new Set<string>();
this._onDidChangeState = new Emitter<State>();
this._onDidNewSession = new Emitter<IDebugSession>();
this._onWillNewSession = new Emitter<IDebugSession>();
this._onDidEndSession = new Emitter<IDebugSession>();
this.configurationManager = this.instantiationService.createInstance(ConfigurationManager, this);
this.toDispose.push(this.configurationManager);
this.debugType = CONTEXT_DEBUG_TYPE.bindTo(contextKeyService);
this.debugState = CONTEXT_DEBUG_STATE.bindTo(contextKeyService);
this.inDebugMode = CONTEXT_IN_DEBUG_MODE.bindTo(contextKeyService);
this.model = new DebugModel(this.loadBreakpoints(), this.storageService.getBoolean(DEBUG_BREAKPOINTS_ACTIVATED_KEY, StorageScope.WORKSPACE, true), this.loadFunctionBreakpoints(),
this.loadExceptionBreakpoints(), this.loadDataBreakpoints(), this.loadWatchExpressions(), this.textFileService);
this.toDispose.push(this.model);
this.viewModel = new ViewModel(contextKeyService);
this.toDispose.push(this.fileService.onFileChanges(e => this.onFileChanges(e)));
this.lifecycleService.onShutdown(this.dispose, this);
this.toDispose.push(this.extensionHostDebugService.onAttachSession(event => {
const session = this.model.getSession(event.sessionId, true);
if (session) {
// EH was started in debug mode -> attach to it
session.configuration.request = 'attach';
session.configuration.port = event.port;
session.setSubId(event.subId);
this.launchOrAttachToSession(session).then(undefined, errors.onUnexpectedError);
}
}));
this.toDispose.push(this.extensionHostDebugService.onTerminateSession(event => {
const session = this.model.getSession(event.sessionId);
if (session && session.subId === event.subId) {
session.disconnect().then(undefined, errors.onUnexpectedError);
}
}));
this.toDispose.push(this.extensionHostDebugService.onLogToSession(event => {
const session = this.model.getSession(event.sessionId, true);
if (session) {
// extension logged output -> show it in REPL
const sev = event.log.severity === 'warn' ? severity.Warning : event.log.severity === 'error' ? severity.Error : severity.Info;
const { args, stack } = parse(event.log);
const frame = !!stack ? getFirstFrame(stack) : undefined;
session.logToRepl(sev, args, frame);
}
}));
this.toDispose.push(this.viewModel.onDidFocusStackFrame(() => {
this.onStateChange();
}));
this.toDispose.push(this.viewModel.onDidFocusSession(session => {
const id = session ? session.getId() : undefined;
this.model.setBreakpointsSessionId(id);
this.onStateChange();
}));
}
getModel(): IDebugModel {
return this.model;
}
getViewModel(): IViewModel {
return this.viewModel;
}
getConfigurationManager(): IConfigurationManager {
return this.configurationManager;
}
sourceIsNotAvailable(uri: uri): void {
this.model.sourceIsNotAvailable(uri);
}
dispose(): void {
this.toDispose = dispose(this.toDispose);
}
//---- state management
get state(): State {
const focusedSession = this.viewModel.focusedSession;
if (focusedSession) {
return focusedSession.state;
}
return this.initializing ? State.Initializing : State.Inactive;
}
private startInitializingState() {
if (!this.initializing) {
this.initializing = true;
this.onStateChange();
}
}
private endInitializingState() {
if (this.initCancellationToken) {
this.initCancellationToken.cancel();
this.initCancellationToken = undefined;
}
if (this.initializing) {
this.initializing = false;
this.onStateChange();
}
}
private onStateChange(): void {
const state = this.state;
if (this.previousState !== state) {
this.debugState.set(getStateLabel(state));
this.inDebugMode.set(state !== State.Inactive);
this.previousState = state;
this._onDidChangeState.fire(state);
}
}
get onDidChangeState(): Event<State> {
return this._onDidChangeState.event;
}
get onDidNewSession(): Event<IDebugSession> {
return this._onDidNewSession.event;
}
get onWillNewSession(): Event<IDebugSession> {
return this._onWillNewSession.event;
}
get onDidEndSession(): Event<IDebugSession> {
return this._onDidEndSession.event;
}
//---- life cycle management
/**
* main entry point
* properly manages compounds, checks for errors and handles the initializing state.
*/
startDebugging(launch: ILaunch | undefined, configOrName?: IConfig | string, noDebug = false, parentSession?: IDebugSession): Promise<boolean> {
this.startInitializingState();
// make sure to save all files and that the configuration is up to date
return this.extensionService.activateByEvent('onDebug').then(() => {
return this.textFileService.saveAll().then(() => this.configurationService.reloadConfiguration(launch ? launch.workspace : undefined).then(() => {
return this.extensionService.whenInstalledExtensionsRegistered().then(() => {
let config: IConfig | undefined;
let compound: ICompound | undefined;
if (!configOrName) {
configOrName = this.configurationManager.selectedConfiguration.name;
}
if (typeof configOrName === 'string' && launch) {
config = launch.getConfiguration(configOrName);
compound = launch.getCompound(configOrName);
const sessions = this.model.getSessions();
const alreadyRunningMessage = nls.localize('configurationAlreadyRunning', "There is already a debug configuration \"{0}\" running.", configOrName);
if (sessions.some(s => s.configuration.name === configOrName && (!launch || !launch.workspace || !s.root || s.root.uri.toString() === launch.workspace.uri.toString()))) {
return Promise.reject(new Error(alreadyRunningMessage));
}
if (compound && compound.configurations && sessions.some(p => compound!.configurations.indexOf(p.configuration.name) !== -1)) {
return Promise.reject(new Error(alreadyRunningMessage));
}
} else if (typeof configOrName !== 'string') {
config = configOrName;
}
if (compound) {
// we are starting a compound debug, first do some error checking and than start each configuration in the compound
if (!compound.configurations) {
return Promise.reject(new Error(nls.localize({ key: 'compoundMustHaveConfigurations', comment: ['compound indicates a "compounds" configuration item', '"configurations" is an attribute and should not be localized'] },
"Compound must have \"configurations\" attribute set in order to start multiple configurations.")));
}
return Promise.all(compound.configurations.map(configData => {
const name = typeof configData === 'string' ? configData : configData.name;
if (name === compound!.name) {
return Promise.resolve(false);
}
let launchForName: ILaunch | undefined;
if (typeof configData === 'string') {
const launchesContainingName = this.configurationManager.getLaunches().filter(l => !!l.getConfiguration(name));
if (launchesContainingName.length === 1) {
launchForName = launchesContainingName[0];
} else if (launch && launchesContainingName.length > 1 && launchesContainingName.indexOf(launch) >= 0) {
// If there are multiple launches containing the configuration give priority to the configuration in the current launch
launchForName = launch;
} else {
return Promise.reject(new Error(launchesContainingName.length === 0 ? nls.localize('noConfigurationNameInWorkspace', "Could not find launch configuration '{0}' in the workspace.", name)
: nls.localize('multipleConfigurationNamesInWorkspace', "There are multiple launch configurations '{0}' in the workspace. Use folder name to qualify the configuration.", name)));
}
} else if (configData.folder) {
const launchesMatchingConfigData = this.configurationManager.getLaunches().filter(l => l.workspace && l.workspace.name === configData.folder && !!l.getConfiguration(configData.name));
if (launchesMatchingConfigData.length === 1) {
launchForName = launchesMatchingConfigData[0];
} else {
return Promise.reject(new Error(nls.localize('noFolderWithName', "Can not find folder with name '{0}' for configuration '{1}' in compound '{2}'.", configData.folder, configData.name, compound!.name)));
}
}
return this.createSession(launchForName, launchForName!.getConfiguration(name), noDebug, parentSession);
})).then(values => values.every(success => !!success)); // Compound launch is a success only if each configuration launched successfully
}
if (configOrName && !config) {
const message = !!launch ? nls.localize('configMissing', "Configuration '{0}' is missing in 'launch.json'.", typeof configOrName === 'string' ? configOrName : JSON.stringify(configOrName)) :
nls.localize('launchJsonDoesNotExist', "'launch.json' does not exist.");
return Promise.reject(new Error(message));
}
return this.createSession(launch, config, noDebug, parentSession);
});
}));
}).then(success => {
// make sure to get out of initializing state, and propagate the result
this.endInitializingState();
return success;
}, err => {
this.endInitializingState();
return Promise.reject(err);
});
}
/**
* gets the debugger for the type, resolves configurations by providers, substitutes variables and runs prelaunch tasks
*/
private createSession(launch: ILaunch | undefined, config: IConfig | undefined, noDebug: boolean, parentSession?: IDebugSession): Promise<boolean> {
// We keep the debug type in a separate variable 'type' so that a no-folder config has no attributes.
// Storing the type in the config would break extensions that assume that the no-folder case is indicated by an empty config.
let type: string | undefined;
if (config) {
type = config.type;
} else {
// a no-folder workspace has no launch.config
config = Object.create(null);
}
const unresolvedConfig = deepClone(config);
if (noDebug) {
config!.noDebug = true;
}
const debuggerThenable: Promise<void> = type ? Promise.resolve() : this.configurationManager.guessDebugger().then(dbgr => { type = dbgr && dbgr.type; });
return debuggerThenable.then(() => {
this.initCancellationToken = new CancellationTokenSource();
return this.configurationManager.resolveConfigurationByProviders(launch && launch.workspace ? launch.workspace.uri : undefined, type, config!, this.initCancellationToken.token).then(config => {
// a falsy config indicates an aborted launch
if (config && config.type) {
return this.substituteVariables(launch, config).then(resolvedConfig => {
if (!resolvedConfig) {
// User canceled resolving of interactive variables, silently return
return false;
}
if (!this.configurationManager.getDebugger(resolvedConfig.type) || (config.request !== 'attach' && config.request !== 'launch')) {
let message: string;
if (config.request !== 'attach' && config.request !== 'launch') {
message = config.request ? nls.localize('debugRequestNotSupported', "Attribute '{0}' has an unsupported value '{1}' in the chosen debug configuration.", 'request', config.request)
: nls.localize('debugRequesMissing', "Attribute '{0}' is missing from the chosen debug configuration.", 'request');
} else {
message = resolvedConfig.type ? nls.localize('debugTypeNotSupported', "Configured debug type '{0}' is not supported.", resolvedConfig.type) :
nls.localize('debugTypeMissing', "Missing property 'type' for the chosen launch configuration.");
}
return this.showError(message).then(() => false);
}
const workspace = launch ? launch.workspace : undefined;
return this.runTaskAndCheckErrors(workspace, resolvedConfig.preLaunchTask).then(result => {
if (result === TaskRunResult.Success) {
return this.doCreateSession(workspace, { resolved: resolvedConfig, unresolved: unresolvedConfig }, parentSession);
}
return false;
});
}, err => {
if (err && err.message) {
return this.showError(err.message).then(() => false);
}
if (this.contextService.getWorkbenchState() === WorkbenchState.EMPTY) {
return this.showError(nls.localize('noFolderWorkspaceDebugError', "The active file can not be debugged. Make sure it is saved and that you have a debug extension installed for that file type."))
.then(() => false);
}
return !!launch && launch.openConfigFile(false, true, undefined, this.initCancellationToken ? this.initCancellationToken.token : undefined).then(() => false);
});
}
if (launch && type && config === null) { // show launch.json only for "config" being "null".
return launch.openConfigFile(false, true, type, this.initCancellationToken ? this.initCancellationToken.token : undefined).then(() => false);
}
return false;
});
});
}
/**
* instantiates the new session, initializes the session, registers session listeners and reports telemetry
*/
private doCreateSession(root: IWorkspaceFolder | undefined, configuration: { resolved: IConfig, unresolved: IConfig | undefined }, parentSession?: IDebugSession): Promise<boolean> {
const session = this.instantiationService.createInstance(DebugSession, configuration, root, this.model, parentSession);
this.model.addSession(session);
// register listeners as the very first thing!
this.registerSessionListeners(session);
// since the Session is now properly registered under its ID and hooked, we can announce it
// this event doesn't go to extensions
this._onWillNewSession.fire(session);
const openDebug = this.configurationService.getValue<IDebugConfiguration>('debug').openDebug;
// Open debug viewlet based on the visibility of the side bar and openDebug setting. Do not open for 'run without debug'
if (!configuration.resolved.noDebug && (openDebug === 'openOnSessionStart' || (openDebug === 'openOnFirstSessionStart' && this.viewModel.firstSessionStart))) {
this.viewletService.openViewlet(VIEWLET_ID).then(undefined, errors.onUnexpectedError);
}
return this.launchOrAttachToSession(session).then(() => {
const internalConsoleOptions = session.configuration.internalConsoleOptions || this.configurationService.getValue<IDebugConfiguration>('debug').internalConsoleOptions;
if (internalConsoleOptions === 'openOnSessionStart' || (this.viewModel.firstSessionStart && internalConsoleOptions === 'openOnFirstSessionStart')) {
this.panelService.openPanel(REPL_ID, false);
}
this.viewModel.firstSessionStart = false;
const showSubSessions = this.configurationService.getValue<IDebugConfiguration>('debug').showSubSessionsInToolBar;
const sessions = this.model.getSessions();
const shownSessions = showSubSessions ? sessions : sessions.filter(s => !s.parentSession);
if (shownSessions.length > 1) {
this.viewModel.setMultiSessionView(true);
}
// since the initialized response has arrived announce the new Session (including extensions)
this._onDidNewSession.fire(session);
return this.telemetryDebugSessionStart(root, session.configuration.type);
}).then(() => true, (error: Error | string) => {
if (errors.isPromiseCanceledError(error)) {
// don't show 'canceled' error messages to the user #7906
return Promise.resolve(false);
}
// Show the repl if some error got logged there #5870
if (session && session.getReplElements().length > 0) {
this.panelService.openPanel(REPL_ID, false);
}
if (session.configuration && session.configuration.request === 'attach' && session.configuration.__autoAttach) {
// ignore attach timeouts in auto attach mode
return Promise.resolve(false);
}
const errorMessage = error instanceof Error ? error.message : error;
this.telemetryDebugMisconfiguration(session.configuration ? session.configuration.type : undefined, errorMessage);
return this.showError(errorMessage, isErrorWithActions(error) ? error.actions : []).then(() => false);
});
}
private launchOrAttachToSession(session: IDebugSession, focus = true): Promise<void> {
const dbgr = this.configurationManager.getDebugger(session.configuration.type);
return session.initialize(dbgr!).then(() => {
return session.launchOrAttach(session.configuration).then(() => {
if (focus) {
this.focusStackFrame(undefined, undefined, session);
}
});
}).then(undefined, err => {
session.shutdown();
return Promise.reject(err);
});
}
private registerSessionListeners(session: IDebugSession): void {
const sessionRunningScheduler = new RunOnceScheduler(() => {
// Do not immediatly defocus the stack frame if the session is running
if (session.state === State.Running && this.viewModel.focusedSession === session) {
this.viewModel.setFocus(undefined, this.viewModel.focusedThread, session, false);
}
}, 200);
this.toDispose.push(session.onDidChangeState(() => {
if (session.state === State.Running && this.viewModel.focusedSession === session) {
sessionRunningScheduler.schedule();
}
if (session === this.viewModel.focusedSession) {
this.onStateChange();
}
}));
this.toDispose.push(session.onDidEndAdapter(adapterExitEvent => {
if (adapterExitEvent.error) {
this.notificationService.error(nls.localize('debugAdapterCrash', "Debug adapter process has terminated unexpectedly ({0})", adapterExitEvent.error.message || adapterExitEvent.error.toString()));
}
// 'Run without debugging' mode VSCode must terminate the extension host. More details: #3905
if (isExtensionHostDebugging(session.configuration) && session.state === State.Running && session.configuration.noDebug) {
this.extensionHostDebugService.close(session.getId());
}
this.telemetryDebugSessionStop(session, adapterExitEvent);
if (session.configuration.postDebugTask) {
this.runTask(session.root, session.configuration.postDebugTask).then(undefined, err =>
this.notificationService.error(err)
);
}
session.shutdown();
this.endInitializingState();
this._onDidEndSession.fire(session);
const focusedSession = this.viewModel.focusedSession;
if (focusedSession && focusedSession.getId() === session.getId()) {
this.focusStackFrame(undefined);
}
if (this.model.getSessions().length === 0) {
this.viewModel.setMultiSessionView(false);
if (this.layoutService.isVisible(Parts.SIDEBAR_PART) && this.configurationService.getValue<IDebugConfiguration>('debug').openExplorerOnEnd) {
this.viewletService.openViewlet(EXPLORER_VIEWLET_ID);
}
// Data breakpoints that can not be persisted should be cleared when a session ends
const dataBreakpoints = this.model.getDataBreakpoints().filter(dbp => !dbp.canPersist);
dataBreakpoints.forEach(dbp => this.model.removeDataBreakpoints(dbp.getId()));
}
}));
}
restartSession(session: IDebugSession, restartData?: any): Promise<any> {
return this.textFileService.saveAll().then(() => {
const isAutoRestart = !!restartData;
const runTasks: () => Promise<TaskRunResult> = () => {
if (isAutoRestart) {
// Do not run preLaunch and postDebug tasks for automatic restarts
return Promise.resolve(TaskRunResult.Success);
}
return this.runTask(session.root, session.configuration.postDebugTask)
.then(() => this.runTaskAndCheckErrors(session.root, session.configuration.preLaunchTask));
};
if (session.capabilities.supportsRestartRequest) {
return runTasks().then(taskResult => taskResult === TaskRunResult.Success ? session.restart() : undefined);
}
if (isExtensionHostDebugging(session.configuration)) {
return runTasks().then(taskResult => taskResult === TaskRunResult.Success ? this.extensionHostDebugService.reload(session.getId()) : undefined);
}
const shouldFocus = this.viewModel.focusedSession && session.getId() === this.viewModel.focusedSession.getId();
// If the restart is automatic -> disconnect, otherwise -> terminate #55064
return (isAutoRestart ? session.disconnect(true) : session.terminate(true)).then(() => {
return new Promise<void>((c, e) => {
setTimeout(() => {
runTasks().then(taskResult => {
if (taskResult !== TaskRunResult.Success) {
return;
}
// Read the configuration again if a launch.json has been changed, if not just use the inmemory configuration
let needsToSubstitute = false;
let unresolved: IConfig | undefined;
const launch = session.root ? this.configurationManager.getLaunch(session.root.uri) : undefined;
if (launch) {
unresolved = launch.getConfiguration(session.configuration.name);
if (unresolved && !equals(unresolved, session.unresolvedConfiguration)) {
// Take the type from the session since the debug extension might overwrite it #21316
unresolved.type = session.configuration.type;
unresolved.noDebug = session.configuration.noDebug;
needsToSubstitute = true;
}
}
let substitutionThenable: Promise<IConfig | null | undefined> = Promise.resolve(session.configuration);
if (launch && needsToSubstitute && unresolved) {
this.initCancellationToken = new CancellationTokenSource();
substitutionThenable = this.configurationManager.resolveConfigurationByProviders(launch.workspace ? launch.workspace.uri : undefined, unresolved.type, unresolved, this.initCancellationToken.token)
.then(resolved => {
if (resolved) {
// start debugging
return this.substituteVariables(launch, resolved);
} else if (resolved === null) {
// abort debugging silently and open launch.json
return Promise.resolve(null);
} else {
// abort debugging silently
return Promise.resolve(undefined);
}
});
}
substitutionThenable.then(resolved => {
if (!resolved) {
return c(undefined);
}
session.setConfiguration({ resolved, unresolved });
session.configuration.__restart = restartData;
this.launchOrAttachToSession(session, shouldFocus).then(() => {
this._onDidNewSession.fire(session);
c(undefined);
}, err => e(err));
});
});
}, 300);
});
});
});
}
stopSession(session: IDebugSession): Promise<any> {
if (session) {
return session.terminate();
}
const sessions = this.model.getSessions();
if (sessions.length === 0) {
this.endInitializingState();
}
return Promise.all(sessions.map(s => s.terminate()));
}
private substituteVariables(launch: ILaunch | undefined, config: IConfig): Promise<IConfig | undefined> {
const dbg = this.configurationManager.getDebugger(config.type);
if (dbg) {
let folder: IWorkspaceFolder | undefined = undefined;
if (launch && launch.workspace) {
folder = launch.workspace;
} else {
const folders = this.contextService.getWorkspace().folders;
if (folders.length === 1) {
folder = folders[0];
}
}
return dbg.substituteVariables(folder, config).then(config => {
return config;
}, (err: Error) => {
this.showError(err.message);
return undefined; // bail out
});
}
return Promise.resolve(config);
}
private showError(message: string, errorActions: ReadonlyArray<IAction> = []): Promise<void> {
const configureAction = this.instantiationService.createInstance(debugactions.ConfigureAction, debugactions.ConfigureAction.ID, debugactions.ConfigureAction.LABEL);
const actions = [...errorActions, configureAction];
return this.dialogService.show(severity.Error, message, actions.map(a => a.label).concat(nls.localize('cancel', "Cancel")), { cancelId: actions.length }).then(choice => {
if (choice < actions.length) {
return actions[choice].run();
}
return undefined;
});
}
//---- task management
private runTaskAndCheckErrors(root: IWorkspaceFolder | undefined, taskId: string | TaskIdentifier | undefined): Promise<TaskRunResult> {
const debugAnywayAction = new Action('debug.debugAnyway', nls.localize('debugAnyway', "Debug Anyway"), undefined, true, () => Promise.resolve(TaskRunResult.Success));
return this.runTask(root, taskId).then((taskSummary: ITaskSummary) => {
const errorCount = taskId ? this.markerService.getStatistics().errors : 0;
const successExitCode = taskSummary && taskSummary.exitCode === 0;
const failureExitCode = taskSummary && taskSummary.exitCode !== undefined && taskSummary.exitCode !== 0;
if (successExitCode || (errorCount === 0 && !failureExitCode)) {
return <any>TaskRunResult.Success;
}
const taskLabel = typeof taskId === 'string' ? taskId : taskId ? taskId.name : '';
const message = errorCount > 1
? nls.localize('preLaunchTaskErrors', "Errors exist after running preLaunchTask '{0}'.", taskLabel)
: errorCount === 1
? nls.localize('preLaunchTaskError', "Error exists after running preLaunchTask '{0}'.", taskLabel)
: nls.localize('preLaunchTaskExitCode', "The preLaunchTask '{0}' terminated with exit code {1}.", taskLabel, taskSummary.exitCode);
const showErrorsAction = new Action('debug.showErrors', nls.localize('showErrors', "Show Errors"), undefined, true, () => {
this.panelService.openPanel(Constants.MARKERS_PANEL_ID);
return Promise.resolve(TaskRunResult.Failure);
});
return this.showError(message, [debugAnywayAction, showErrorsAction]);
}, (err: TaskError) => {
return this.showError(err.message, [debugAnywayAction, this.taskService.configureAction()]);
});
}
private runTask(root: IWorkspaceFolder | undefined, taskId: string | TaskIdentifier | undefined): Promise<ITaskSummary | null> {
if (!taskId) {
return Promise.resolve(null);
}
if (!root) {
return Promise.reject(new Error(nls.localize('invalidTaskReference', "Task '{0}' can not be referenced from a launch configuration that is in a different workspace folder.", typeof taskId === 'string' ? taskId : taskId.type)));
}
// run a task before starting a debug session
return this.taskService.getTask(root, taskId).then(task => {
if (!task) {
const errorMessage = typeof taskId === 'string'
? nls.localize('DebugTaskNotFoundWithTaskId', "Could not find the task '{0}'.", taskId)
: nls.localize('DebugTaskNotFound', "Could not find the specified task.");
return Promise.reject(createErrorWithActions(errorMessage));
}
// If a task is missing the problem matcher the promise will never complete, so we need to have a workaround #35340
let taskStarted = false;
const promise: Promise<ITaskSummary | null> = this.taskService.getActiveTasks().then(tasks => {
if (tasks.filter(t => t._id === task._id).length) {
// task is already running - nothing to do.
return Promise.resolve(null);
}
once(e => ((e.kind === TaskEventKind.Active) || (e.kind === TaskEventKind.DependsOnStarted)) && e.taskId === task._id, this.taskService.onDidStateChange)(() => {
// Task is active, so everything seems to be fine, no need to prompt after 10 seconds
// Use case being a slow running task should not be prompted even though it takes more than 10 seconds
taskStarted = true;
});
const taskPromise = this.taskService.run(task);
if (task.configurationProperties.isBackground) {
return new Promise((c, e) => once(e => e.kind === TaskEventKind.Inactive && e.taskId === task._id, this.taskService.onDidStateChange)(() => {
taskStarted = true;
c(null);
}));
}
return taskPromise;
});
return new Promise((c, e) => {
promise.then(result => {
taskStarted = true;
c(result);
}, error => e(error));
setTimeout(() => {
if (!taskStarted) {
const errorMessage = typeof taskId === 'string'
? nls.localize('taskNotTrackedWithTaskId', "The specified task cannot be tracked.")
: nls.localize('taskNotTracked', "The task '{0}' cannot be tracked.", JSON.stringify(taskId));
e({ severity: severity.Error, message: errorMessage });
}
}, 10000);
});
});
}
//---- focus management
focusStackFrame(stackFrame: IStackFrame | undefined, thread?: IThread, session?: IDebugSession, explicit?: boolean): void {
if (!session) {
if (stackFrame || thread) {
session = stackFrame ? stackFrame.thread.session : thread!.session;
} else {
const sessions = this.model.getSessions();
const stoppedSession = sessions.filter(s => s.state === State.Stopped).shift();
session = stoppedSession || (sessions.length ? sessions[0] : undefined);
}
}
if (!thread) {
if (stackFrame) {
thread = stackFrame.thread;
} else {
const threads = session ? session.getAllThreads() : undefined;
const stoppedThread = threads && threads.filter(t => t.stopped).shift();
thread = stoppedThread || (threads && threads.length ? threads[0] : undefined);
}
}
if (!stackFrame) {
if (thread) {
const callStack = thread.getCallStack();
stackFrame = first(callStack, sf => !!(sf && sf.source && sf.source.available && sf.source.presentationHint !== 'deemphasize'), undefined);
}
}
if (stackFrame) {
stackFrame.openInEditor(this.editorService, true).then(editor => {
if (editor) {
const control = editor.getControl();
if (stackFrame && isCodeEditor(control) && control.hasModel()) {
const model = control.getModel();
if (stackFrame.range.startLineNumber <= model.getLineCount()) {
const lineContent = control.getModel().getLineContent(stackFrame.range.startLineNumber);
aria.alert(nls.localize('debuggingPaused', "Debugging paused {0}, {1} {2} {3}", thread && thread.stoppedDetails ? `, reason ${thread.stoppedDetails.reason}` : '', stackFrame.source ? stackFrame.source.name : '', stackFrame.range.startLineNumber, lineContent));
}
}
}
});
}
if (session) {
this.debugType.set(session.configuration.type);
} else {
this.debugType.reset();
}
this.viewModel.setFocus(stackFrame, thread, session, !!explicit);
}
//---- watches
addWatchExpression(name: string): void {
const we = this.model.addWatchExpression(name);
this.viewModel.setSelectedExpression(we);
this.storeWatchExpressions();
}
renameWatchExpression(id: string, newName: string): void {
this.model.renameWatchExpression(id, newName);
this.storeWatchExpressions();
}
moveWatchExpression(id: string, position: number): void {
this.model.moveWatchExpression(id, position);
this.storeWatchExpressions();
}
removeWatchExpressions(id?: string): void {
this.model.removeWatchExpressions(id);
this.storeWatchExpressions();
}
//---- breakpoints
async enableOrDisableBreakpoints(enable: boolean, breakpoint?: IEnablement): Promise<void> {
if (breakpoint) {
this.model.setEnablement(breakpoint, enable);
if (breakpoint instanceof Breakpoint) {
await this.sendBreakpoints(breakpoint.uri);
} else if (breakpoint instanceof FunctionBreakpoint) {
await this.sendFunctionBreakpoints();
} else if (breakpoint instanceof DataBreakpoint) {
await this.sendDataBreakpoints();
} else {
await this.sendExceptionBreakpoints();
}
} else {
this.model.enableOrDisableAllBreakpoints(enable);
await this.sendAllBreakpoints();
}
this.storeBreakpoints();
}
async addBreakpoints(uri: uri, rawBreakpoints: IBreakpointData[], context: string): Promise<IBreakpoint[]> {
const breakpoints = this.model.addBreakpoints(uri, rawBreakpoints);
breakpoints.forEach(bp => aria.status(nls.localize('breakpointAdded', "Added breakpoint, line {0}, file {1}", bp.lineNumber, uri.fsPath)));
breakpoints.forEach(bp => this.telemetryDebugAddBreakpoint(bp, context));
await this.sendBreakpoints(uri);
this.storeBreakpoints();
return breakpoints;
}
async updateBreakpoints(uri: uri, data: Map<string, DebugProtocol.Breakpoint>, sendOnResourceSaved: boolean): Promise<void> {
this.model.updateBreakpoints(data);
if (sendOnResourceSaved) {
this.breakpointsToSendOnResourceSaved.add(uri.toString());
} else {
await this.sendBreakpoints(uri);
}
this.storeBreakpoints();
}
async removeBreakpoints(id?: string): Promise<void> {
const toRemove = this.model.getBreakpoints().filter(bp => !id || bp.getId() === id);
toRemove.forEach(bp => aria.status(nls.localize('breakpointRemoved', "Removed breakpoint, line {0}, file {1}", bp.lineNumber, bp.uri.fsPath)));
const urisToClear = distinct(toRemove, bp => bp.uri.toString()).map(bp => bp.uri);
this.model.removeBreakpoints(toRemove);
await Promise.all(urisToClear.map(uri => this.sendBreakpoints(uri)));
this.storeBreakpoints();
}
setBreakpointsActivated(activated: boolean): Promise<void> {
this.model.setBreakpointsActivated(activated);
if (activated) {
this.storageService.store(DEBUG_BREAKPOINTS_ACTIVATED_KEY, 'false', StorageScope.WORKSPACE);
} else {
this.storageService.remove(DEBUG_BREAKPOINTS_ACTIVATED_KEY, StorageScope.WORKSPACE);
}
return this.sendAllBreakpoints();
}
addFunctionBreakpoint(name?: string, id?: string): void {
const newFunctionBreakpoint = this.model.addFunctionBreakpoint(name || '', id);
this.viewModel.setSelectedFunctionBreakpoint(newFunctionBreakpoint);
}
async renameFunctionBreakpoint(id: string, newFunctionName: string): Promise<void> {
this.model.renameFunctionBreakpoint(id, newFunctionName);
await this.sendFunctionBreakpoints();
this.storeBreakpoints();
}
async removeFunctionBreakpoints(id?: string): Promise<void> {
this.model.removeFunctionBreakpoints(id);
await this.sendFunctionBreakpoints();
this.storeBreakpoints();
}
async addDataBreakpoint(label: string, dataId: string, canPersist: boolean): Promise<void> {
this.model.addDataBreakpoint(label, dataId, canPersist);
await this.sendDataBreakpoints();
this.storeBreakpoints();
}
async removeDataBreakpoints(id?: string): Promise<void> {
this.model.removeDataBreakpoints(id);
await this.sendDataBreakpoints();
this.storeBreakpoints();
}
sendAllBreakpoints(session?: IDebugSession): Promise<any> {
return Promise.all(distinct(this.model.getBreakpoints(), bp => bp.uri.toString()).map(bp => this.sendBreakpoints(bp.uri, false, session)))
.then(() => this.sendFunctionBreakpoints(session))
// send exception breakpoints at the end since some debug adapters rely on the order
.then(() => this.sendExceptionBreakpoints(session));
}
private sendBreakpoints(modelUri: uri, sourceModified = false, session?: IDebugSession): Promise<void> {
const breakpointsToSend = this.model.getBreakpoints({ uri: modelUri, enabledOnly: true });
return this.sendToOneOrAllSessions(session, s =>
s.sendBreakpoints(modelUri, breakpointsToSend, sourceModified)
);
}
private sendFunctionBreakpoints(session?: IDebugSession): Promise<void> {
const breakpointsToSend = this.model.getFunctionBreakpoints().filter(fbp => fbp.enabled && this.model.areBreakpointsActivated());
return this.sendToOneOrAllSessions(session, s => {
return s.capabilities.supportsFunctionBreakpoints ? s.sendFunctionBreakpoints(breakpointsToSend) : Promise.resolve(undefined);
});
}
private sendDataBreakpoints(session?: IDebugSession): Promise<void> {
const breakpointsToSend = this.model.getDataBreakpoints().filter(fbp => fbp.enabled && this.model.areBreakpointsActivated());
return this.sendToOneOrAllSessions(session, s => {
return s.capabilities.supportsDataBreakpoints ? s.sendDataBreakpoints(breakpointsToSend) : Promise.resolve(undefined);
});
}
private sendExceptionBreakpoints(session?: IDebugSession): Promise<void> {
const enabledExceptionBps = this.model.getExceptionBreakpoints().filter(exb => exb.enabled);
return this.sendToOneOrAllSessions(session, s => {
return s.sendExceptionBreakpoints(enabledExceptionBps);
});
}
private sendToOneOrAllSessions(session: IDebugSession | undefined, send: (session: IDebugSession) => Promise<void>): Promise<void> {
if (session) {
return send(session);
}
return Promise.all(this.model.getSessions().map(s => send(s))).then(() => undefined);
}
private onFileChanges(fileChangesEvent: FileChangesEvent): void {
const toRemove = this.model.getBreakpoints().filter(bp =>
fileChangesEvent.contains(bp.uri, FileChangeType.DELETED));
if (toRemove.length) {
this.model.removeBreakpoints(toRemove);
}
fileChangesEvent.getUpdated().forEach(event => {
if (this.breakpointsToSendOnResourceSaved.delete(event.resource.toString())) {
this.sendBreakpoints(event.resource, true);
}
});
}
private loadBreakpoints(): Breakpoint[] {
let result: Breakpoint[] | undefined;
try {
result = JSON.parse(this.storageService.get(DEBUG_BREAKPOINTS_KEY, StorageScope.WORKSPACE, '[]')).map((breakpoint: any) => {
return new Breakpoint(uri.parse(breakpoint.uri.external || breakpoint.source.uri.external), breakpoint.lineNumber, breakpoint.column, breakpoint.enabled, breakpoint.condition, breakpoint.hitCondition, breakpoint.logMessage, breakpoint.adapterData, this.textFileService);
});
} catch (e) { }
return result || [];
}
private loadFunctionBreakpoints(): FunctionBreakpoint[] {
let result: FunctionBreakpoint[] | undefined;
try {
result = JSON.parse(this.storageService.get(DEBUG_FUNCTION_BREAKPOINTS_KEY, StorageScope.WORKSPACE, '[]')).map((fb: any) => {
return new FunctionBreakpoint(fb.name, fb.enabled, fb.hitCondition, fb.condition, fb.logMessage);
});
} catch (e) { }
return result || [];
}
private loadExceptionBreakpoints(): ExceptionBreakpoint[] {
let result: ExceptionBreakpoint[] | undefined;
try {
result = JSON.parse(this.storageService.get(DEBUG_EXCEPTION_BREAKPOINTS_KEY, StorageScope.WORKSPACE, '[]')).map((exBreakpoint: any) => {
return new ExceptionBreakpoint(exBreakpoint.filter, exBreakpoint.label, exBreakpoint.enabled);
});
} catch (e) { }
return result || [];
}
private loadDataBreakpoints(): DataBreakpoint[] {
let result: DataBreakpoint[] | undefined;
try {
result = JSON.parse(this.storageService.get(DEBUG_DATA_BREAKPOINTS_KEY, StorageScope.WORKSPACE, '[]')).map((dbp: any) => {
return new DataBreakpoint(dbp.label, dbp.dataId, true, dbp.enabled, dbp.hitCondition, dbp.condition, dbp.logMessage);
});
} catch (e) { }
return result || [];
}
private loadWatchExpressions(): Expression[] {
let result: Expression[] | undefined;
try {
result = JSON.parse(this.storageService.get(DEBUG_WATCH_EXPRESSIONS_KEY, StorageScope.WORKSPACE, '[]')).map((watchStoredData: { name: string, id: string }) => {
return new Expression(watchStoredData.name, watchStoredData.id);
});
} catch (e) { }
return result || [];
}
private storeWatchExpressions(): void {
const watchExpressions = this.model.getWatchExpressions();
if (watchExpressions.length) {
this.storageService.store(DEBUG_WATCH_EXPRESSIONS_KEY, JSON.stringify(watchExpressions.map(we => ({ name: we.name, id: we.getId() }))), StorageScope.WORKSPACE);
} else {
this.storageService.remove(DEBUG_WATCH_EXPRESSIONS_KEY, StorageScope.WORKSPACE);
}
}
private storeBreakpoints(): void {
const breakpoints = this.model.getBreakpoints();
if (breakpoints.length) {
this.storageService.store(DEBUG_BREAKPOINTS_KEY, JSON.stringify(breakpoints), StorageScope.WORKSPACE);
} else {
this.storageService.remove(DEBUG_BREAKPOINTS_KEY, StorageScope.WORKSPACE);
}
const functionBreakpoints = this.model.getFunctionBreakpoints();
if (functionBreakpoints.length) {
this.storageService.store(DEBUG_FUNCTION_BREAKPOINTS_KEY, JSON.stringify(functionBreakpoints), StorageScope.WORKSPACE);
} else {
this.storageService.remove(DEBUG_FUNCTION_BREAKPOINTS_KEY, StorageScope.WORKSPACE);
}
const dataBreakpoints = this.model.getDataBreakpoints().filter(dbp => dbp.canPersist);
if (dataBreakpoints.length) {
this.storageService.store(DEBUG_DATA_BREAKPOINTS_KEY, JSON.stringify(dataBreakpoints), StorageScope.WORKSPACE);
} else {
this.storageService.remove(DEBUG_DATA_BREAKPOINTS_KEY, StorageScope.WORKSPACE);
}
const exceptionBreakpoints = this.model.getExceptionBreakpoints();
if (exceptionBreakpoints.length) {
this.storageService.store(DEBUG_EXCEPTION_BREAKPOINTS_KEY, JSON.stringify(exceptionBreakpoints), StorageScope.WORKSPACE);
} else {
this.storageService.remove(DEBUG_EXCEPTION_BREAKPOINTS_KEY, StorageScope.WORKSPACE);
}
}
//---- telemetry
private telemetryDebugSessionStart(root: IWorkspaceFolder | undefined, type: string): Promise<void> {
const dbgr = this.configurationManager.getDebugger(type);
if (!dbgr) {
return Promise.resolve();
}
const extension = dbgr.getMainExtensionDescriptor();
/* __GDPR__
"debugSessionStart" : {
"type": { "classification": "SystemMetaData", "purpose": "FeatureInsight" },
"breakpointCount": { "classification": "SystemMetaData", "purpose": "FeatureInsight", "isMeasurement": true },
"exceptionBreakpoints": { "classification": "SystemMetaData", "purpose": "FeatureInsight" },
"watchExpressionsCount": { "classification": "SystemMetaData", "purpose": "FeatureInsight", "isMeasurement": true },
"extensionName": { "classification": "PublicNonPersonalData", "purpose": "FeatureInsight" },
"isBuiltin": { "classification": "SystemMetaData", "purpose": "FeatureInsight", "isMeasurement": true},
"launchJsonExists": { "classification": "SystemMetaData", "purpose": "FeatureInsight", "isMeasurement": true }
}
*/
return this.telemetryService.publicLog('debugSessionStart', {
type: type,
breakpointCount: this.model.getBreakpoints().length,
exceptionBreakpoints: this.model.getExceptionBreakpoints(),
watchExpressionsCount: this.model.getWatchExpressions().length,
extensionName: extension.identifier.value,
isBuiltin: extension.isBuiltin,
launchJsonExists: root && !!this.configurationService.getValue<IGlobalConfig>('launch', { resource: root.uri })
});
}
private telemetryDebugSessionStop(session: IDebugSession, adapterExitEvent: AdapterEndEvent): Promise<any> {
const breakpoints = this.model.getBreakpoints();
/* __GDPR__
"debugSessionStop" : {
"type" : { "classification": "SystemMetaData", "purpose": "FeatureInsight" },
"success": { "classification": "SystemMetaData", "purpose": "FeatureInsight", "isMeasurement": true },
"sessionLengthInSeconds": { "classification": "SystemMetaData", "purpose": "FeatureInsight", "isMeasurement": true },
"breakpointCount": { "classification": "SystemMetaData", "purpose": "FeatureInsight", "isMeasurement": true },
"watchExpressionsCount": { "classification": "SystemMetaData", "purpose": "FeatureInsight", "isMeasurement": true }
}
*/
return this.telemetryService.publicLog('debugSessionStop', {
type: session && session.configuration.type,
success: adapterExitEvent.emittedStopped || breakpoints.length === 0,
sessionLengthInSeconds: adapterExitEvent.sessionLengthInSeconds,
breakpointCount: breakpoints.length,
watchExpressionsCount: this.model.getWatchExpressions().length
});
}
private telemetryDebugMisconfiguration(debugType: string | undefined, message: string): Promise<any> {
/* __GDPR__
"debugMisconfiguration" : {
"type" : { "classification": "SystemMetaData", "purpose": "FeatureInsight" },
"error": { "classification": "CallstackOrException", "purpose": "FeatureInsight" }
}
*/
return this.telemetryService.publicLog('debugMisconfiguration', {
type: debugType,
error: message
});
}
private telemetryDebugAddBreakpoint(breakpoint: IBreakpoint, context: string): Promise<any> {
/* __GDPR__
"debugAddBreakpoint" : {
"context": { "classification": "SystemMetaData", "purpose": "FeatureInsight" },
"hasCondition": { "classification": "SystemMetaData", "purpose": "FeatureInsight", "isMeasurement": true },
"hasHitCondition": { "classification": "SystemMetaData", "purpose": "FeatureInsight", "isMeasurement": true },
"hasLogMessage": { "classification": "SystemMetaData", "purpose": "FeatureInsight", "isMeasurement": true }
}
*/
return this.telemetryService.publicLog('debugAddBreakpoint', {
context: context,
hasCondition: !!breakpoint.condition,
hasHitCondition: !!breakpoint.hitCondition,
hasLogMessage: !!breakpoint.logMessage
});
}
}
| src/vs/workbench/contrib/debug/browser/debugService.ts | 1 | https://github.com/microsoft/vscode/commit/38aa4766107555dce5e16e15c94135a3c681e497 | [
0.012568723410367966,
0.00043711528996936977,
0.00016194030467886478,
0.00017005421977955848,
0.0012714378535747528
] |
{
"id": 3,
"code_window": [
"\t}\n",
"\n",
"\tprivate registerListeners(): void {\n",
"\t\tthis._register(this.debugService.onDidChangeState(() => this.updateScheduler.schedule()));\n",
"\t\tthis._register(this.debugService.getViewModel().onDidFocusSession(() => this.updateScheduler.schedule()));\n",
"\t\tthis._register(this.configurationService.onDidChangeConfiguration(e => this.onDidConfigurationChange(e)));\n",
"\t\tthis._register(this.actionBar.actionRunner.onDidRun((e: IRunEvent) => {\n",
"\t\t\t// check for error\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\tthis._register(this.debugService.onDidNewSession(() => this.updateScheduler.schedule()));\n"
],
"file_path": "src/vs/workbench/contrib/debug/browser/debugToolBar.ts",
"type": "add",
"edit_start_line_idx": 133
} | // sub | src/vs/workbench/services/search/test/node/fixtures/examples/subfolder/subfile.txt | 0 | https://github.com/microsoft/vscode/commit/38aa4766107555dce5e16e15c94135a3c681e497 | [
0.00017129968910012394,
0.00017129968910012394,
0.00017129968910012394,
0.00017129968910012394,
0
] |
{
"id": 3,
"code_window": [
"\t}\n",
"\n",
"\tprivate registerListeners(): void {\n",
"\t\tthis._register(this.debugService.onDidChangeState(() => this.updateScheduler.schedule()));\n",
"\t\tthis._register(this.debugService.getViewModel().onDidFocusSession(() => this.updateScheduler.schedule()));\n",
"\t\tthis._register(this.configurationService.onDidChangeConfiguration(e => this.onDidConfigurationChange(e)));\n",
"\t\tthis._register(this.actionBar.actionRunner.onDidRun((e: IRunEvent) => {\n",
"\t\t\t// check for error\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\tthis._register(this.debugService.onDidNewSession(() => this.updateScheduler.schedule()));\n"
],
"file_path": "src/vs/workbench/contrib/debug/browser/debugToolBar.ts",
"type": "add",
"edit_start_line_idx": 133
} | <svg width="16" height="16" viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg">
<path d="M9 9H4V10H9V9Z" fill="#C5C5C5"/>
<path fill-rule="evenodd" clip-rule="evenodd" d="M5 3L6 2H13L14 3V10L13 11H11V13L10 14H3L2 13V6L3 5H5V3ZM6 5H10L11 6V10H13V3H6V5ZM10 6H3V13H10V6Z" fill="#C5C5C5"/>
</svg>
| src/vs/workbench/contrib/files/browser/media/collapse-all-dark.svg | 0 | https://github.com/microsoft/vscode/commit/38aa4766107555dce5e16e15c94135a3c681e497 | [
0.0001727424532873556,
0.0001727424532873556,
0.0001727424532873556,
0.0001727424532873556,
0
] |
{
"id": 3,
"code_window": [
"\t}\n",
"\n",
"\tprivate registerListeners(): void {\n",
"\t\tthis._register(this.debugService.onDidChangeState(() => this.updateScheduler.schedule()));\n",
"\t\tthis._register(this.debugService.getViewModel().onDidFocusSession(() => this.updateScheduler.schedule()));\n",
"\t\tthis._register(this.configurationService.onDidChangeConfiguration(e => this.onDidConfigurationChange(e)));\n",
"\t\tthis._register(this.actionBar.actionRunner.onDidRun((e: IRunEvent) => {\n",
"\t\t\t// check for error\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\tthis._register(this.debugService.onDidNewSession(() => this.updateScheduler.schedule()));\n"
],
"file_path": "src/vs/workbench/contrib/debug/browser/debugToolBar.ts",
"type": "add",
"edit_start_line_idx": 133
} | {
"Region Start": {
"prefix": "#region",
"body": [
"#pragma region $0"
],
"description": "Folding Region Start"
},
"Region End": {
"prefix": "#endregion",
"body": [
"#pragma endregion"
],
"description": "Folding Region End"
}
}
| extensions/cpp/snippets/cpp.json | 0 | https://github.com/microsoft/vscode/commit/38aa4766107555dce5e16e15c94135a3c681e497 | [
0.00017320325423497707,
0.00017271446995437145,
0.00017222570022568107,
0.00017271446995437145,
4.88777004648e-7
] |
{
"id": 0,
"code_window": [
"### Features\n",
"\n",
"* **compiler-core:** support parsing `const` modifier in type parameters ([#7912](https://github.com/vuejs/core/issues/7912)) ([b7bd50f](https://github.com/vuejs/core/commit/b7bd50f5059e8755c0204f01a8c55b1724688e7e))\n",
"* **compiler-sfc:** add defineOptions macro ([#5738](https://github.com/vuejs/core/issues/5738)) ([bcf5841](https://github.com/vuejs/core/commit/bcf5841ddecc64d0bdbd56ce1463eb8ebf01bb9d))\n",
"* **compiler-sfc:** enable reactive props destructure by default and deprecate withDefaults() ([#7986](https://github.com/vuejs/core/issues/7986)) ([ba9c2ae](https://github.com/vuejs/core/commit/ba9c2ae247fcc3960b238a04cb635158daa82004))\n",
"* **compiler-sfc:** improve runtime props inference for enum ([eded947](https://github.com/vuejs/core/commit/eded94712e37856f258dc8c85f98a26fa41ae05f))\n",
"* **compiler-sfc:** support generating variable instead of default export in compileScript ([71635be](https://github.com/vuejs/core/commit/71635be68d25887f91d624bb7f78281a851bc0cb))\n",
"* **compiler-sfc:** support module string names syntax ([#7428](https://github.com/vuejs/core/issues/7428)) ([0002567](https://github.com/vuejs/core/commit/000256772816d54976e462330a7be342c49c7304))\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
"* **compiler-sfc:** enable reactive props destructure by default ([#7986](https://github.com/vuejs/core/issues/7986)) ([ba9c2ae](https://github.com/vuejs/core/commit/ba9c2ae247fcc3960b238a04cb635158daa82004))\n"
],
"file_path": "CHANGELOG.md",
"type": "replace",
"edit_start_line_idx": 36
} | import {
isArray,
isPromise,
isFunction,
Prettify,
UnionToIntersection
} from '@vue/shared'
import {
getCurrentInstance,
setCurrentInstance,
SetupContext,
createSetupContext,
unsetCurrentInstance
} from './component'
import { EmitFn, EmitsOptions } from './componentEmits'
import {
ComponentOptionsMixin,
ComponentOptionsWithoutProps,
ComputedOptions,
MethodOptions
} from './componentOptions'
import {
ComponentPropsOptions,
ComponentObjectPropsOptions,
ExtractPropTypes
} from './componentProps'
import { warn } from './warning'
// dev only
const warnRuntimeUsage = (method: string) =>
warn(
`${method}() is a compiler-hint helper that is only usable inside ` +
`<script setup> of a single file component. Its arguments should be ` +
`compiled away and passing it at runtime has no effect.`
)
/**
* Vue `<script setup>` compiler macro for declaring component props. The
* expected argument is the same as the component `props` option.
*
* Example runtime declaration:
* ```js
* // using Array syntax
* const props = defineProps(['foo', 'bar'])
* // using Object syntax
* const props = defineProps({
* foo: String,
* bar: {
* type: Number,
* required: true
* }
* })
* ```
*
* Equivalent type-based declaration:
* ```ts
* // will be compiled into equivalent runtime declarations
* const props = defineProps<{
* foo?: string
* bar: number
* }>()
* ```
*
* This is only usable inside `<script setup>`, is compiled away in the
* output and should **not** be actually called at runtime.
*/
// overload 1: runtime props w/ array
export function defineProps<PropNames extends string = string>(
props: PropNames[]
): Prettify<Readonly<{ [key in PropNames]?: any }>>
// overload 2: runtime props w/ object
export function defineProps<
PP extends ComponentObjectPropsOptions = ComponentObjectPropsOptions
>(props: PP): Prettify<Readonly<ExtractPropTypes<PP>>>
// overload 3: typed-based declaration
export function defineProps<TypeProps>(): ResolveProps<TypeProps>
// implementation
export function defineProps() {
if (__DEV__) {
warnRuntimeUsage(`defineProps`)
}
return null as any
}
type ResolveProps<T, BooleanKeys extends keyof T = BooleanKey<T>> = Prettify<
Readonly<
T & {
[K in BooleanKeys]-?: boolean
}
>
>
type BooleanKey<T, K extends keyof T = keyof T> = K extends any
? [T[K]] extends [boolean | undefined]
? K
: never
: never
/**
* Vue `<script setup>` compiler macro for declaring a component's emitted
* events. The expected argument is the same as the component `emits` option.
*
* Example runtime declaration:
* ```js
* const emit = defineEmits(['change', 'update'])
* ```
*
* Example type-based declaration:
* ```ts
* const emit = defineEmits<{
* (event: 'change'): void
* (event: 'update', id: number): void
* }>()
*
* emit('change')
* emit('update', 1)
* ```
*
* This is only usable inside `<script setup>`, is compiled away in the
* output and should **not** be actually called at runtime.
*/
// overload 1: runtime emits w/ array
export function defineEmits<EE extends string = string>(
emitOptions: EE[]
): EmitFn<EE[]>
export function defineEmits<E extends EmitsOptions = EmitsOptions>(
emitOptions: E
): EmitFn<E>
export function defineEmits<
T extends ((...args: any[]) => any) | Record<string, any[]>
>(): T extends (...args: any[]) => any ? T : ShortEmits<T>
// implementation
export function defineEmits() {
if (__DEV__) {
warnRuntimeUsage(`defineEmits`)
}
return null as any
}
type RecordToUnion<T extends Record<string, any>> = T[keyof T]
type ShortEmits<T extends Record<string, any>> = UnionToIntersection<
RecordToUnion<{
[K in keyof T]: (evt: K, ...args: T[K]) => void
}>
>
/**
* Vue `<script setup>` compiler macro for declaring a component's exposed
* instance properties when it is accessed by a parent component via template
* refs.
*
* `<script setup>` components are closed by default - i.e. variables inside
* the `<script setup>` scope is not exposed to parent unless explicitly exposed
* via `defineExpose`.
*
* This is only usable inside `<script setup>`, is compiled away in the
* output and should **not** be actually called at runtime.
*/
export function defineExpose<
Exposed extends Record<string, any> = Record<string, any>
>(exposed?: Exposed) {
if (__DEV__) {
warnRuntimeUsage(`defineExpose`)
}
}
export function defineOptions<
RawBindings = {},
D = {},
C extends ComputedOptions = {},
M extends MethodOptions = {},
Mixin extends ComponentOptionsMixin = ComponentOptionsMixin,
Extends extends ComponentOptionsMixin = ComponentOptionsMixin,
E extends EmitsOptions = EmitsOptions,
EE extends string = string
>(
options?: ComponentOptionsWithoutProps<
{},
RawBindings,
D,
C,
M,
Mixin,
Extends,
E,
EE
> & { emits?: undefined; expose?: undefined }
): void {
if (__DEV__) {
warnRuntimeUsage(`defineOptions`)
}
}
type NotUndefined<T> = T extends undefined ? never : T
type InferDefaults<T> = {
[K in keyof T]?: InferDefault<T, NotUndefined<T[K]>>
}
type InferDefault<P, T> = T extends
| null
| number
| string
| boolean
| symbol
| Function
? T | ((props: P) => T)
: (props: P) => T
type PropsWithDefaults<Base, Defaults> = Base & {
[K in keyof Defaults]: K extends keyof Base
? Defaults[K] extends undefined
? Base[K]
: NotUndefined<Base[K]>
: never
}
/**
* Vue `<script setup>` compiler macro for providing props default values when
* using type-based `defineProps` declaration.
*
* Example usage:
* ```ts
* withDefaults(defineProps<{
* size?: number
* labels?: string[]
* }>(), {
* size: 3,
* labels: () => ['default label']
* })
* ```
*
* This is only usable inside `<script setup>`, is compiled away in the output
* and should **not** be actually called at runtime.
*
* @deprecated use reactive props destructure instead.
*/
export function withDefaults<Props, Defaults extends InferDefaults<Props>>(
props: Props,
defaults: Defaults
): PropsWithDefaults<Props, Defaults> {
if (__DEV__) {
warnRuntimeUsage(`withDefaults`)
}
return null as any
}
export function useSlots(): SetupContext['slots'] {
return getContext().slots
}
export function useAttrs(): SetupContext['attrs'] {
return getContext().attrs
}
function getContext(): SetupContext {
const i = getCurrentInstance()!
if (__DEV__ && !i) {
warn(`useContext() called without active instance.`)
}
return i.setupContext || (i.setupContext = createSetupContext(i))
}
/**
* Runtime helper for merging default declarations. Imported by compiled code
* only.
* @internal
*/
export function mergeDefaults(
raw: ComponentPropsOptions,
defaults: Record<string, any>
): ComponentObjectPropsOptions {
const props = isArray(raw)
? raw.reduce(
(normalized, p) => ((normalized[p] = {}), normalized),
{} as ComponentObjectPropsOptions
)
: raw
for (const key in defaults) {
if (key.startsWith('__skip')) continue
let opt = props[key]
if (opt) {
if (isArray(opt) || isFunction(opt)) {
opt = props[key] = { type: opt, default: defaults[key] }
} else {
opt.default = defaults[key]
}
} else if (opt === null) {
opt = props[key] = { default: defaults[key] }
} else if (__DEV__) {
warn(`props default key "${key}" has no corresponding declaration.`)
}
if (opt && defaults[`__skip_${key}`]) {
opt.skipFactory = true
}
}
return props
}
/**
* Used to create a proxy for the rest element when destructuring props with
* defineProps().
* @internal
*/
export function createPropsRestProxy(
props: any,
excludedKeys: string[]
): Record<string, any> {
const ret: Record<string, any> = {}
for (const key in props) {
if (!excludedKeys.includes(key)) {
Object.defineProperty(ret, key, {
enumerable: true,
get: () => props[key]
})
}
}
return ret
}
/**
* `<script setup>` helper for persisting the current instance context over
* async/await flows.
*
* `@vue/compiler-sfc` converts the following:
*
* ```ts
* const x = await foo()
* ```
*
* into:
*
* ```ts
* let __temp, __restore
* const x = (([__temp, __restore] = withAsyncContext(() => foo())),__temp=await __temp,__restore(),__temp)
* ```
* @internal
*/
export function withAsyncContext(getAwaitable: () => any) {
const ctx = getCurrentInstance()!
if (__DEV__ && !ctx) {
warn(
`withAsyncContext called without active current instance. ` +
`This is likely a bug.`
)
}
let awaitable = getAwaitable()
unsetCurrentInstance()
if (isPromise(awaitable)) {
awaitable = awaitable.catch(e => {
setCurrentInstance(ctx)
throw e
})
}
return [awaitable, () => setCurrentInstance(ctx)]
}
| packages/runtime-core/src/apiSetupHelpers.ts | 1 | https://github.com/vuejs/core/commit/4af5d1b0754035058436f9e4e5c12aedef199177 | [
0.012117143720388412,
0.0016642106929793954,
0.0001713849778752774,
0.0006305029382929206,
0.0024284864775836468
] |
{
"id": 0,
"code_window": [
"### Features\n",
"\n",
"* **compiler-core:** support parsing `const` modifier in type parameters ([#7912](https://github.com/vuejs/core/issues/7912)) ([b7bd50f](https://github.com/vuejs/core/commit/b7bd50f5059e8755c0204f01a8c55b1724688e7e))\n",
"* **compiler-sfc:** add defineOptions macro ([#5738](https://github.com/vuejs/core/issues/5738)) ([bcf5841](https://github.com/vuejs/core/commit/bcf5841ddecc64d0bdbd56ce1463eb8ebf01bb9d))\n",
"* **compiler-sfc:** enable reactive props destructure by default and deprecate withDefaults() ([#7986](https://github.com/vuejs/core/issues/7986)) ([ba9c2ae](https://github.com/vuejs/core/commit/ba9c2ae247fcc3960b238a04cb635158daa82004))\n",
"* **compiler-sfc:** improve runtime props inference for enum ([eded947](https://github.com/vuejs/core/commit/eded94712e37856f258dc8c85f98a26fa41ae05f))\n",
"* **compiler-sfc:** support generating variable instead of default export in compileScript ([71635be](https://github.com/vuejs/core/commit/71635be68d25887f91d624bb7f78281a851bc0cb))\n",
"* **compiler-sfc:** support module string names syntax ([#7428](https://github.com/vuejs/core/issues/7428)) ([0002567](https://github.com/vuejs/core/commit/000256772816d54976e462330a7be342c49c7304))\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
"* **compiler-sfc:** enable reactive props destructure by default ([#7986](https://github.com/vuejs/core/issues/7986)) ([ba9c2ae](https://github.com/vuejs/core/commit/ba9c2ae247fcc3960b238a04cb635158daa82004))\n"
],
"file_path": "CHANGELOG.md",
"type": "replace",
"edit_start_line_idx": 36
} | import {
getCurrentInstance,
warn,
VNode,
Fragment,
Static,
watchPostEffect,
onMounted,
onUnmounted
} from '@vue/runtime-core'
import { ShapeFlags } from '@vue/shared'
/**
* Runtime helper for SFC's CSS variable injection feature.
* @private
*/
export function useCssVars(getter: (ctx: any) => Record<string, string>) {
if (!__BROWSER__ && !__TEST__) return
const instance = getCurrentInstance()
/* istanbul ignore next */
if (!instance) {
__DEV__ &&
warn(`useCssVars is called without current active component instance.`)
return
}
const updateTeleports = (instance.ut = (vars = getter(instance.proxy)) => {
Array.from(
document.querySelectorAll(`[data-v-owner="${instance.uid}"]`)
).forEach(node => setVarsOnNode(node, vars))
})
const setVars = () => {
const vars = getter(instance.proxy)
setVarsOnVNode(instance.subTree, vars)
updateTeleports(vars)
}
watchPostEffect(setVars)
onMounted(() => {
const ob = new MutationObserver(setVars)
ob.observe(instance.subTree.el!.parentNode, { childList: true })
onUnmounted(() => ob.disconnect())
})
}
function setVarsOnVNode(vnode: VNode, vars: Record<string, string>) {
if (__FEATURE_SUSPENSE__ && vnode.shapeFlag & ShapeFlags.SUSPENSE) {
const suspense = vnode.suspense!
vnode = suspense.activeBranch!
if (suspense.pendingBranch && !suspense.isHydrating) {
suspense.effects.push(() => {
setVarsOnVNode(suspense.activeBranch!, vars)
})
}
}
// drill down HOCs until it's a non-component vnode
while (vnode.component) {
vnode = vnode.component.subTree
}
if (vnode.shapeFlag & ShapeFlags.ELEMENT && vnode.el) {
setVarsOnNode(vnode.el as Node, vars)
} else if (vnode.type === Fragment) {
;(vnode.children as VNode[]).forEach(c => setVarsOnVNode(c, vars))
} else if (vnode.type === Static) {
let { el, anchor } = vnode
while (el) {
setVarsOnNode(el as Node, vars)
if (el === anchor) break
el = el.nextSibling
}
}
}
function setVarsOnNode(el: Node, vars: Record<string, string>) {
if (el.nodeType === 1) {
const style = (el as HTMLElement).style
for (const key in vars) {
style.setProperty(`--${key}`, vars[key])
}
}
}
| packages/runtime-dom/src/helpers/useCssVars.ts | 0 | https://github.com/vuejs/core/commit/4af5d1b0754035058436f9e4e5c12aedef199177 | [
0.0005756283062510192,
0.0003146238159388304,
0.0001627408928470686,
0.0003007267077919096,
0.00015224327216856182
] |
{
"id": 0,
"code_window": [
"### Features\n",
"\n",
"* **compiler-core:** support parsing `const` modifier in type parameters ([#7912](https://github.com/vuejs/core/issues/7912)) ([b7bd50f](https://github.com/vuejs/core/commit/b7bd50f5059e8755c0204f01a8c55b1724688e7e))\n",
"* **compiler-sfc:** add defineOptions macro ([#5738](https://github.com/vuejs/core/issues/5738)) ([bcf5841](https://github.com/vuejs/core/commit/bcf5841ddecc64d0bdbd56ce1463eb8ebf01bb9d))\n",
"* **compiler-sfc:** enable reactive props destructure by default and deprecate withDefaults() ([#7986](https://github.com/vuejs/core/issues/7986)) ([ba9c2ae](https://github.com/vuejs/core/commit/ba9c2ae247fcc3960b238a04cb635158daa82004))\n",
"* **compiler-sfc:** improve runtime props inference for enum ([eded947](https://github.com/vuejs/core/commit/eded94712e37856f258dc8c85f98a26fa41ae05f))\n",
"* **compiler-sfc:** support generating variable instead of default export in compileScript ([71635be](https://github.com/vuejs/core/commit/71635be68d25887f91d624bb7f78281a851bc0cb))\n",
"* **compiler-sfc:** support module string names syntax ([#7428](https://github.com/vuejs/core/issues/7428)) ([0002567](https://github.com/vuejs/core/commit/000256772816d54976e462330a7be342c49c7304))\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
"* **compiler-sfc:** enable reactive props destructure by default ([#7986](https://github.com/vuejs/core/issues/7986)) ([ba9c2ae](https://github.com/vuejs/core/commit/ba9c2ae247fcc3960b238a04cb635158daa82004))\n"
],
"file_path": "CHANGELOG.md",
"type": "replace",
"edit_start_line_idx": 36
} | import {
h,
render,
nodeOps,
serializeInner,
renderSlot,
withScopeId,
pushScopeId,
popScopeId
} from '@vue/runtime-test'
import { withCtx } from '../src/componentRenderContext'
describe('scopeId runtime support', () => {
test('should attach scopeId', () => {
const App = {
__scopeId: 'parent',
render: () => h('div', [h('div')])
}
const root = nodeOps.createElement('div')
render(h(App), root)
expect(serializeInner(root)).toBe(`<div parent><div parent></div></div>`)
})
test('should attach scopeId to components in parent component', () => {
const Child = {
__scopeId: 'child',
render: () => h('div')
}
const App = {
__scopeId: 'parent',
render: () => h('div', [h(Child)])
}
const root = nodeOps.createElement('div')
render(h(App), root)
expect(serializeInner(root)).toBe(
`<div parent><div child parent></div></div>`
)
})
// :slotted basic
test('should work on slots', () => {
const Child = {
__scopeId: 'child',
render(this: any) {
return h('div', renderSlot(this.$slots, 'default'))
}
}
const Child2 = {
__scopeId: 'child2',
render: () => h('span')
}
const App = {
__scopeId: 'parent',
render: () => {
return h(
Child,
withCtx(() => {
return [h('div'), h(Child2)]
})
)
}
}
const root = nodeOps.createElement('div')
render(h(App), root)
// slot content should have:
// - scopeId from parent
// - slotted scopeId (with `-s` postfix) from child (the tree owner)
expect(serializeInner(root)).toBe(
`<div child parent>` +
`<div parent child-s></div>` +
// component inside slot should have:
// - scopeId from template context
// - slotted scopeId from slot owner
// - its own scopeId
`<span child2 parent child-s></span>` +
`</div>`
)
})
// #2892
test(':slotted on forwarded slots', async () => {
const Wrapper = {
__scopeId: 'wrapper',
render(this: any) {
// <div class="wrapper"><slot/></div>
return h('div', { class: 'wrapper' }, [
renderSlot(
this.$slots,
'default',
{},
undefined,
true /* noSlotted */
)
])
}
}
const Slotted = {
__scopeId: 'slotted',
render(this: any) {
// <Wrapper><slot/></Wrapper>
return h(Wrapper, null, {
default: withCtx(() => [renderSlot(this.$slots, 'default')])
})
}
}
// simulate hoisted node
pushScopeId('root')
const hoisted = h('div', 'hoisted')
popScopeId()
const Root = {
__scopeId: 'root',
render(this: any) {
// <Slotted><div>hoisted</div><div>{{ dynamic }}</div></Slotted>
return h(Slotted, null, {
default: withCtx(() => {
return [hoisted, h('div', 'dynamic')]
})
})
}
}
const root = nodeOps.createElement('div')
render(h(Root), root)
expect(serializeInner(root)).toBe(
`<div wrapper slotted root class="wrapper">` +
`<div root slotted-s>hoisted</div>` +
`<div root slotted-s>dynamic</div>` +
`</div>`
)
const Root2 = {
__scopeId: 'root',
render(this: any) {
// <Slotted>
// <Wrapper>
// <div>hoisted</div><div>{{ dynamic }}</div>
// </Wrapper>
// </Slotted>
return h(Slotted, null, {
default: withCtx(() => [
h(Wrapper, null, {
default: withCtx(() => [hoisted, h('div', 'dynamic')])
})
])
})
}
}
const root2 = nodeOps.createElement('div')
render(h(Root2), root2)
expect(serializeInner(root2)).toBe(
`<div wrapper slotted root class="wrapper">` +
`<div wrapper root slotted-s class="wrapper">` +
`<div root>hoisted</div>` +
`<div root>dynamic</div>` +
`</div>` +
`</div>`
)
})
// #1988
test('should inherit scopeId through nested HOCs with inheritAttrs: false', () => {
const App = {
__scopeId: 'parent',
render: () => {
return h(Child)
}
}
function Child() {
return h(Child2, { class: 'foo' })
}
function Child2() {
return h('div')
}
Child2.inheritAttrs = false
const root = nodeOps.createElement('div')
render(h(App), root)
expect(serializeInner(root)).toBe(`<div parent></div>`)
})
})
describe('backwards compat with <=3.0.7', () => {
const withParentId = withScopeId('parent')
const withChildId = withScopeId('child')
test('should attach scopeId', () => {
const App = {
__scopeId: 'parent',
render: withParentId(() => {
return h('div', [h('div')])
})
}
const root = nodeOps.createElement('div')
render(h(App), root)
expect(serializeInner(root)).toBe(`<div parent><div parent></div></div>`)
})
test('should attach scopeId to components in parent component', () => {
const Child = {
__scopeId: 'child',
render: withChildId(() => {
return h('div')
})
}
const App = {
__scopeId: 'parent',
render: withParentId(() => {
return h('div', [h(Child)])
})
}
const root = nodeOps.createElement('div')
render(h(App), root)
expect(serializeInner(root)).toBe(
`<div parent><div child parent></div></div>`
)
})
test('should work on slots', () => {
const Child = {
__scopeId: 'child',
render: withChildId(function (this: any) {
return h('div', renderSlot(this.$slots, 'default'))
})
}
const withChild2Id = withScopeId('child2')
const Child2 = {
__scopeId: 'child2',
render: withChild2Id(() => h('span'))
}
const App = {
__scopeId: 'parent',
render: withParentId(() => {
return h(
Child,
withParentId(() => {
return [h('div'), h(Child2)]
})
)
})
}
const root = nodeOps.createElement('div')
render(h(App), root)
// slot content should have:
// - scopeId from parent
// - slotted scopeId (with `-s` postfix) from child (the tree owner)
expect(serializeInner(root)).toBe(
`<div child parent>` +
`<div parent child-s></div>` +
// component inside slot should have:
// - scopeId from template context
// - slotted scopeId from slot owner
// - its own scopeId
`<span child2 parent child-s></span>` +
`</div>`
)
})
// #1988
test('should inherit scopeId through nested HOCs with inheritAttrs: false', () => {
const withParentId = withScopeId('parent')
const App = {
__scopeId: 'parent',
render: withParentId(() => {
return h(Child)
})
}
function Child() {
return h(Child2, { class: 'foo' })
}
function Child2() {
return h('div')
}
Child2.inheritAttrs = false
const root = nodeOps.createElement('div')
render(h(App), root)
expect(serializeInner(root)).toBe(`<div parent></div>`)
})
test('hoisted nodes', async () => {
pushScopeId('foobar')
const hoisted = h('div', 'hello')
popScopeId()
const App = {
__scopeId: 'foobar',
render: () => h('div', [hoisted])
}
const root = nodeOps.createElement('div')
render(h(App), root)
expect(serializeInner(root)).toBe(
`<div foobar><div foobar>hello</div></div>`
)
})
})
| packages/runtime-core/__tests__/scopeId.spec.ts | 0 | https://github.com/vuejs/core/commit/4af5d1b0754035058436f9e4e5c12aedef199177 | [
0.004285610746592283,
0.0003781636478379369,
0.00016290329222101718,
0.0001997588260564953,
0.0007224567816592753
] |
{
"id": 0,
"code_window": [
"### Features\n",
"\n",
"* **compiler-core:** support parsing `const` modifier in type parameters ([#7912](https://github.com/vuejs/core/issues/7912)) ([b7bd50f](https://github.com/vuejs/core/commit/b7bd50f5059e8755c0204f01a8c55b1724688e7e))\n",
"* **compiler-sfc:** add defineOptions macro ([#5738](https://github.com/vuejs/core/issues/5738)) ([bcf5841](https://github.com/vuejs/core/commit/bcf5841ddecc64d0bdbd56ce1463eb8ebf01bb9d))\n",
"* **compiler-sfc:** enable reactive props destructure by default and deprecate withDefaults() ([#7986](https://github.com/vuejs/core/issues/7986)) ([ba9c2ae](https://github.com/vuejs/core/commit/ba9c2ae247fcc3960b238a04cb635158daa82004))\n",
"* **compiler-sfc:** improve runtime props inference for enum ([eded947](https://github.com/vuejs/core/commit/eded94712e37856f258dc8c85f98a26fa41ae05f))\n",
"* **compiler-sfc:** support generating variable instead of default export in compileScript ([71635be](https://github.com/vuejs/core/commit/71635be68d25887f91d624bb7f78281a851bc0cb))\n",
"* **compiler-sfc:** support module string names syntax ([#7428](https://github.com/vuejs/core/issues/7428)) ([0002567](https://github.com/vuejs/core/commit/000256772816d54976e462330a7be342c49c7304))\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
"* **compiler-sfc:** enable reactive props destructure by default ([#7986](https://github.com/vuejs/core/issues/7986)) ([ba9c2ae](https://github.com/vuejs/core/commit/ba9c2ae247fcc3960b238a04cb635158daa82004))\n"
],
"file_path": "CHANGELOG.md",
"type": "replace",
"edit_start_line_idx": 36
} | // global JSX namespace registration
// somehow we have to copy=pase the jsx-runtime types here to make TypeScript happy
import type {
VNode,
IntrinsicElementAttributes,
ReservedProps,
NativeElements
} from '@vue/runtime-dom'
declare global {
namespace JSX {
export interface Element extends VNode {}
export interface ElementClass {
$props: {}
}
export interface ElementAttributesProperty {
$props: {}
}
export interface IntrinsicElements extends NativeElements {
// allow arbitrary elements
// @ts-ignore suppress ts:2374 = Duplicate string index signature.
[name: string]: any
}
export interface IntrinsicAttributes extends ReservedProps {}
}
}
| packages/vue/jsx.d.ts | 0 | https://github.com/vuejs/core/commit/4af5d1b0754035058436f9e4e5c12aedef199177 | [
0.003691320074722171,
0.0015765015268698335,
0.00022873729176353663,
0.0008094473741948605,
0.0015140781179070473
] |
{
"id": 0,
"code_window": [
"defineType(\"RegExpLiteral\", {\n",
" builder: [\"pattern\", \"flags\"],\n",
" deprecatedAlias: \"RegexLiteral\",\n",
" aliases: [\"Expression\", \"Literal\"],\n",
" fields: {\n",
" pattern: {\n",
" validate: assertValueType(\"string\"),\n",
" },\n",
" flags: {\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" aliases: [\"Expression\", \"Pureish\", \"Literal\"],\n"
],
"file_path": "packages/babel-types/src/definitions/core.js",
"type": "replace",
"edit_start_line_idx": 570
} | // @flow
import esutils from "esutils";
import is from "../validators/is";
import {
BINARY_OPERATORS,
LOGICAL_OPERATORS,
ASSIGNMENT_OPERATORS,
UNARY_OPERATORS,
UPDATE_OPERATORS,
} from "../constants";
import defineType, {
assertValueType,
assertNodeType,
assertNodeOrValueType,
assertEach,
chain,
assertOneOf,
} from "./utils";
defineType("ArrayExpression", {
fields: {
elements: {
validate: chain(
assertValueType("array"),
assertEach(
assertNodeOrValueType("null", "Expression", "SpreadElement"),
),
),
default: !process.env.BABEL_TYPES_8_BREAKING ? [] : undefined,
},
},
visitor: ["elements"],
aliases: ["Expression"],
});
defineType("AssignmentExpression", {
fields: {
operator: {
validate: (function() {
if (!process.env.BABEL_TYPES_8_BREAKING) {
return assertValueType("string");
}
const identifier = assertOneOf(...ASSIGNMENT_OPERATORS);
const pattern = assertOneOf("=");
return function(node, key, val) {
const validator = is("Pattern", node.left) ? pattern : identifier;
validator(node, key, val);
};
})(),
},
left: {
validate: !process.env.BABEL_TYPES_8_BREAKING
? assertNodeType("LVal")
: assertNodeType(
"Identifier",
"MemberExpression",
"ArrayPattern",
"ObjectPattern",
),
},
right: {
validate: assertNodeType("Expression"),
},
},
builder: ["operator", "left", "right"],
visitor: ["left", "right"],
aliases: ["Expression"],
});
defineType("BinaryExpression", {
builder: ["operator", "left", "right"],
fields: {
operator: {
validate: assertOneOf(...BINARY_OPERATORS),
},
left: {
validate: assertNodeType("Expression"),
},
right: {
validate: assertNodeType("Expression"),
},
},
visitor: ["left", "right"],
aliases: ["Binary", "Expression"],
});
defineType("InterpreterDirective", {
builder: ["value"],
fields: {
value: {
validate: assertValueType("string"),
},
},
});
defineType("Directive", {
visitor: ["value"],
fields: {
value: {
validate: assertNodeType("DirectiveLiteral"),
},
},
});
defineType("DirectiveLiteral", {
builder: ["value"],
fields: {
value: {
validate: assertValueType("string"),
},
},
});
defineType("BlockStatement", {
builder: ["body", "directives"],
visitor: ["directives", "body"],
fields: {
directives: {
validate: chain(
assertValueType("array"),
assertEach(assertNodeType("Directive")),
),
default: [],
},
body: {
validate: chain(
assertValueType("array"),
assertEach(assertNodeType("Statement")),
),
},
},
aliases: ["Scopable", "BlockParent", "Block", "Statement"],
});
defineType("BreakStatement", {
visitor: ["label"],
fields: {
label: {
validate: assertNodeType("Identifier"),
optional: true,
},
},
aliases: ["Statement", "Terminatorless", "CompletionStatement"],
});
defineType("CallExpression", {
visitor: ["callee", "arguments", "typeParameters", "typeArguments"],
builder: ["callee", "arguments"],
aliases: ["Expression"],
fields: {
callee: {
validate: assertNodeType("Expression", "V8IntrinsicIdentifier"),
},
arguments: {
validate: chain(
assertValueType("array"),
assertEach(
assertNodeType(
"Expression",
"SpreadElement",
"JSXNamespacedName",
"ArgumentPlaceholder",
),
),
),
},
...(!process.env.BABEL_TYPES_8_BREAKING
? {
optional: {
validate: assertOneOf(true, false),
optional: true,
},
}
: {}),
typeArguments: {
validate: assertNodeType("TypeParameterInstantiation"),
optional: true,
},
typeParameters: {
validate: assertNodeType("TSTypeParameterInstantiation"),
optional: true,
},
},
});
defineType("CatchClause", {
visitor: ["param", "body"],
fields: {
param: {
validate: assertNodeType("Identifier", "ArrayPattern", "ObjectPattern"),
optional: true,
},
body: {
validate: assertNodeType("BlockStatement"),
},
},
aliases: ["Scopable", "BlockParent"],
});
defineType("ConditionalExpression", {
visitor: ["test", "consequent", "alternate"],
fields: {
test: {
validate: assertNodeType("Expression"),
},
consequent: {
validate: assertNodeType("Expression"),
},
alternate: {
validate: assertNodeType("Expression"),
},
},
aliases: ["Expression", "Conditional"],
});
defineType("ContinueStatement", {
visitor: ["label"],
fields: {
label: {
validate: assertNodeType("Identifier"),
optional: true,
},
},
aliases: ["Statement", "Terminatorless", "CompletionStatement"],
});
defineType("DebuggerStatement", {
aliases: ["Statement"],
});
defineType("DoWhileStatement", {
visitor: ["test", "body"],
fields: {
test: {
validate: assertNodeType("Expression"),
},
body: {
validate: assertNodeType("Statement"),
},
},
aliases: ["Statement", "BlockParent", "Loop", "While", "Scopable"],
});
defineType("EmptyStatement", {
aliases: ["Statement"],
});
defineType("ExpressionStatement", {
visitor: ["expression"],
fields: {
expression: {
validate: assertNodeType("Expression"),
},
},
aliases: ["Statement", "ExpressionWrapper"],
});
defineType("File", {
builder: ["program", "comments", "tokens"],
visitor: ["program"],
fields: {
program: {
validate: assertNodeType("Program"),
},
},
});
defineType("ForInStatement", {
visitor: ["left", "right", "body"],
aliases: [
"Scopable",
"Statement",
"For",
"BlockParent",
"Loop",
"ForXStatement",
],
fields: {
left: {
validate: !process.env.BABEL_TYPES_8_BREAKING
? assertNodeType("VariableDeclaration", "LVal")
: assertNodeType(
"VariableDeclaration",
"Identifier",
"MemberExpression",
"ArrayPattern",
"ObjectPattern",
),
},
right: {
validate: assertNodeType("Expression"),
},
body: {
validate: assertNodeType("Statement"),
},
},
});
defineType("ForStatement", {
visitor: ["init", "test", "update", "body"],
aliases: ["Scopable", "Statement", "For", "BlockParent", "Loop"],
fields: {
init: {
validate: assertNodeType("VariableDeclaration", "Expression"),
optional: true,
},
test: {
validate: assertNodeType("Expression"),
optional: true,
},
update: {
validate: assertNodeType("Expression"),
optional: true,
},
body: {
validate: assertNodeType("Statement"),
},
},
});
export const functionCommon = {
params: {
validate: chain(
assertValueType("array"),
assertEach(
assertNodeType(
"Identifier",
"Pattern",
"RestElement",
"TSParameterProperty",
),
),
),
},
generator: {
default: false,
},
async: {
default: false,
},
};
export const functionTypeAnnotationCommon = {
returnType: {
validate: assertNodeType("TypeAnnotation", "TSTypeAnnotation", "Noop"),
optional: true,
},
typeParameters: {
validate: assertNodeType(
"TypeParameterDeclaration",
"TSTypeParameterDeclaration",
"Noop",
),
optional: true,
},
};
export const functionDeclarationCommon = {
...functionCommon,
declare: {
validate: assertValueType("boolean"),
optional: true,
},
id: {
validate: assertNodeType("Identifier"),
optional: true, // May be null for `export default function`
},
};
defineType("FunctionDeclaration", {
builder: ["id", "params", "body", "generator", "async"],
visitor: ["id", "params", "body", "returnType", "typeParameters"],
fields: {
...functionDeclarationCommon,
...functionTypeAnnotationCommon,
body: {
validate: assertNodeType("BlockStatement"),
},
},
aliases: [
"Scopable",
"Function",
"BlockParent",
"FunctionParent",
"Statement",
"Pureish",
"Declaration",
],
validate: (function() {
if (!process.env.BABEL_TYPES_8_BREAKING) return () => {};
const identifier = assertNodeType("Identifier");
return function(parent, key, node) {
if (!is("ExportDefaultDeclaration", parent)) {
identifier(node, "id", node.id);
}
};
})(),
});
defineType("FunctionExpression", {
inherits: "FunctionDeclaration",
aliases: [
"Scopable",
"Function",
"BlockParent",
"FunctionParent",
"Expression",
"Pureish",
],
fields: {
...functionCommon,
...functionTypeAnnotationCommon,
id: {
validate: assertNodeType("Identifier"),
optional: true,
},
body: {
validate: assertNodeType("BlockStatement"),
},
},
});
export const patternLikeCommon = {
typeAnnotation: {
// TODO: @babel/plugin-transform-flow-comments puts a Noop here, is there a better way?
validate: assertNodeType("TypeAnnotation", "TSTypeAnnotation", "Noop"),
optional: true,
},
decorators: {
validate: chain(
assertValueType("array"),
assertEach(assertNodeType("Decorator")),
),
},
};
defineType("Identifier", {
builder: ["name"],
visitor: ["typeAnnotation", "decorators" /* for legacy param decorators */],
aliases: ["Expression", "PatternLike", "LVal", "TSEntityName"],
fields: {
...patternLikeCommon,
name: {
validate: chain(assertValueType("string"), function(node, key, val) {
if (!process.env.BABEL_TYPES_8_BREAKING) return;
if (!esutils.keyword.isIdentifierNameES6(val)) {
throw new TypeError(`"${val}" is not a valid identifier name`);
}
}),
},
optional: {
validate: assertValueType("boolean"),
optional: true,
},
},
validate(parent, key, node) {
if (!process.env.BABEL_TYPES_8_BREAKING) return;
const match = /\.(\w+)$/.exec(key);
if (!match) return;
const [, parentKey] = match;
const nonComp = { computed: false };
// We can't check if `parent.property === node`, because nodes are validated
// before replacing them in the AST.
if (parentKey === "property") {
if (is("MemberExpression", parent, nonComp)) return;
if (is("OptionalMemberExpression", parent, nonComp)) return;
} else if (parentKey === "key") {
if (is("Property", parent, nonComp)) return;
if (is("Method", parent, nonComp)) return;
} else if (parentKey === "exported") {
if (is("ExportSpecifier", parent)) return;
} else if (parentKey === "imported") {
if (is("ImportSpecifier", parent, { imported: node })) return;
} else if (parentKey === "meta") {
if (is("MetaProperty", parent, { meta: node })) return;
}
if (
// Ideally this should be strict if this node is a descendant of a block
// in strict mode. Also, we should disallow "await" in modules.
esutils.keyword.isReservedWordES6(node.name, /* strict */ false) &&
// Even if "this" is a keyword, we are using the Identifier
// node to represent it.
node.name !== "this"
) {
throw new TypeError(`"${node.name}" is not a valid identifer`);
}
},
});
defineType("IfStatement", {
visitor: ["test", "consequent", "alternate"],
aliases: ["Statement", "Conditional"],
fields: {
test: {
validate: assertNodeType("Expression"),
},
consequent: {
validate: assertNodeType("Statement"),
},
alternate: {
optional: true,
validate: assertNodeType("Statement"),
},
},
});
defineType("LabeledStatement", {
visitor: ["label", "body"],
aliases: ["Statement"],
fields: {
label: {
validate: assertNodeType("Identifier"),
},
body: {
validate: assertNodeType("Statement"),
},
},
});
defineType("StringLiteral", {
builder: ["value"],
fields: {
value: {
validate: assertValueType("string"),
},
},
aliases: ["Expression", "Pureish", "Literal", "Immutable"],
});
defineType("NumericLiteral", {
builder: ["value"],
deprecatedAlias: "NumberLiteral",
fields: {
value: {
validate: assertValueType("number"),
},
},
aliases: ["Expression", "Pureish", "Literal", "Immutable"],
});
defineType("NullLiteral", {
aliases: ["Expression", "Pureish", "Literal", "Immutable"],
});
defineType("BooleanLiteral", {
builder: ["value"],
fields: {
value: {
validate: assertValueType("boolean"),
},
},
aliases: ["Expression", "Pureish", "Literal", "Immutable"],
});
defineType("RegExpLiteral", {
builder: ["pattern", "flags"],
deprecatedAlias: "RegexLiteral",
aliases: ["Expression", "Literal"],
fields: {
pattern: {
validate: assertValueType("string"),
},
flags: {
validate: chain(assertValueType("string"), function(node, key, val) {
if (!process.env.BABEL_TYPES_8_BREAKING) return;
const invalid = /[^gimsuy]/.exec(val);
if (invalid) {
throw new TypeError(`"${invalid[0]}" is not a valid RegExp flag`);
}
}),
default: "",
},
},
});
defineType("LogicalExpression", {
builder: ["operator", "left", "right"],
visitor: ["left", "right"],
aliases: ["Binary", "Expression"],
fields: {
operator: {
validate: assertOneOf(...LOGICAL_OPERATORS),
},
left: {
validate: assertNodeType("Expression"),
},
right: {
validate: assertNodeType("Expression"),
},
},
});
defineType("MemberExpression", {
builder: ["object", "property", "computed", "optional"],
visitor: ["object", "property"],
aliases: ["Expression", "LVal"],
fields: {
object: {
validate: assertNodeType("Expression"),
},
property: {
validate: (function() {
const normal = assertNodeType("Identifier", "PrivateName");
const computed = assertNodeType("Expression");
return function(node, key, val) {
const validator = node.computed ? computed : normal;
validator(node, key, val);
};
})(),
},
computed: {
default: false,
},
...(!process.env.BABEL_TYPES_8_BREAKING
? {
optional: {
validate: assertOneOf(true, false),
optional: true,
},
}
: {}),
},
});
defineType("NewExpression", { inherits: "CallExpression" });
defineType("Program", {
// Note: We explicitly leave 'interpreter' out here because it is
// conceptually comment-like, and Babel does not traverse comments either.
visitor: ["directives", "body"],
builder: ["body", "directives", "sourceType", "interpreter"],
fields: {
sourceFile: {
validate: assertValueType("string"),
},
sourceType: {
validate: assertOneOf("script", "module"),
default: "script",
},
interpreter: {
validate: assertNodeType("InterpreterDirective"),
default: null,
optional: true,
},
directives: {
validate: chain(
assertValueType("array"),
assertEach(assertNodeType("Directive")),
),
default: [],
},
body: {
validate: chain(
assertValueType("array"),
assertEach(assertNodeType("Statement")),
),
},
},
aliases: ["Scopable", "BlockParent", "Block"],
});
defineType("ObjectExpression", {
visitor: ["properties"],
aliases: ["Expression"],
fields: {
properties: {
validate: chain(
assertValueType("array"),
assertEach(
assertNodeType("ObjectMethod", "ObjectProperty", "SpreadElement"),
),
),
},
},
});
defineType("ObjectMethod", {
builder: ["kind", "key", "params", "body", "computed", "generator", "async"],
fields: {
...functionCommon,
...functionTypeAnnotationCommon,
kind: {
validate: assertOneOf("method", "get", "set"),
...(!process.env.BABEL_TYPES_8_BREAKING ? { default: "method" } : {}),
},
computed: {
default: false,
},
key: {
validate: (function() {
const normal = assertNodeType(
"Identifier",
"StringLiteral",
"NumericLiteral",
);
const computed = assertNodeType("Expression");
return function(node, key, val) {
const validator = node.computed ? computed : normal;
validator(node, key, val);
};
})(),
},
decorators: {
validate: chain(
assertValueType("array"),
assertEach(assertNodeType("Decorator")),
),
optional: true,
},
body: {
validate: assertNodeType("BlockStatement"),
},
},
visitor: [
"key",
"params",
"body",
"decorators",
"returnType",
"typeParameters",
],
aliases: [
"UserWhitespacable",
"Function",
"Scopable",
"BlockParent",
"FunctionParent",
"Method",
"ObjectMember",
],
});
defineType("ObjectProperty", {
builder: [
"key",
"value",
"computed",
"shorthand",
...(!process.env.BABEL_TYPES_8_BREAKING ? ["decorators"] : []),
],
fields: {
computed: {
default: false,
},
key: {
validate: (function() {
const normal = assertNodeType(
"Identifier",
"StringLiteral",
"NumericLiteral",
);
const computed = assertNodeType("Expression");
return function(node, key, val) {
const validator = node.computed ? computed : normal;
validator(node, key, val);
};
})(),
},
value: {
// Value may be PatternLike if this is an AssignmentProperty
// https://github.com/babel/babylon/issues/434
validate: assertNodeType("Expression", "PatternLike"),
},
shorthand: {
validate: chain(
assertValueType("boolean"),
function(node, key, val) {
if (!process.env.BABEL_TYPES_8_BREAKING) return;
if (val && node.computed) {
throw new TypeError(
"Property shorthand of ObjectProperty cannot be true if computed is true",
);
}
},
function(node, key, val) {
if (!process.env.BABEL_TYPES_8_BREAKING) return;
if (val && !is("Identifier", node.key)) {
throw new TypeError(
"Property shorthand of ObjectProperty cannot be true if key is not an Identifier",
);
}
},
),
default: false,
},
decorators: {
validate: chain(
assertValueType("array"),
assertEach(assertNodeType("Decorator")),
),
optional: true,
},
},
visitor: ["key", "value", "decorators"],
aliases: ["UserWhitespacable", "Property", "ObjectMember"],
validate: (function() {
const pattern = assertNodeType("Identifier", "Pattern");
const expression = assertNodeType("Expression");
return function(parent, key, node) {
if (!process.env.BABEL_TYPES_8_BREAKING) return;
const validator = is("ObjectPattern", parent) ? pattern : expression;
validator(node, "value", node.value);
};
})(),
});
defineType("RestElement", {
visitor: ["argument", "typeAnnotation"],
builder: ["argument"],
aliases: ["LVal", "PatternLike"],
deprecatedAlias: "RestProperty",
fields: {
...patternLikeCommon,
argument: {
validate: !process.env.BABEL_TYPES_8_BREAKING
? assertNodeType("LVal")
: assertNodeType("Identifier", "Pattern", "MemberExpression"),
},
},
validate(parent, key) {
if (!process.env.BABEL_TYPES_8_BREAKING) return;
const match = /(\w+)\[(\d+)\]/.exec(key);
if (!match) throw new Error("Internal Babel error: malformed key.");
const [, listKey, index] = match;
if (parent[listKey].length > index + 1) {
throw new TypeError(`RestElement must be last element of ${listKey}`);
}
},
});
defineType("ReturnStatement", {
visitor: ["argument"],
aliases: ["Statement", "Terminatorless", "CompletionStatement"],
fields: {
argument: {
validate: assertNodeType("Expression"),
optional: true,
},
},
});
defineType("SequenceExpression", {
visitor: ["expressions"],
fields: {
expressions: {
validate: chain(
assertValueType("array"),
assertEach(assertNodeType("Expression")),
),
},
},
aliases: ["Expression"],
});
defineType("ParenthesizedExpression", {
visitor: ["expression"],
aliases: ["Expression", "ExpressionWrapper"],
fields: {
expression: {
validate: assertNodeType("Expression"),
},
},
});
defineType("SwitchCase", {
visitor: ["test", "consequent"],
fields: {
test: {
validate: assertNodeType("Expression"),
optional: true,
},
consequent: {
validate: chain(
assertValueType("array"),
assertEach(assertNodeType("Statement")),
),
},
},
});
defineType("SwitchStatement", {
visitor: ["discriminant", "cases"],
aliases: ["Statement", "BlockParent", "Scopable"],
fields: {
discriminant: {
validate: assertNodeType("Expression"),
},
cases: {
validate: chain(
assertValueType("array"),
assertEach(assertNodeType("SwitchCase")),
),
},
},
});
defineType("ThisExpression", {
aliases: ["Expression"],
});
defineType("ThrowStatement", {
visitor: ["argument"],
aliases: ["Statement", "Terminatorless", "CompletionStatement"],
fields: {
argument: {
validate: assertNodeType("Expression"),
},
},
});
defineType("TryStatement", {
visitor: ["block", "handler", "finalizer"],
aliases: ["Statement"],
fields: {
block: {
validate: chain(assertNodeType("BlockStatement"), function(node) {
if (!process.env.BABEL_TYPES_8_BREAKING) return;
// This validator isn't put at the top level because we can run it
// even if this node doesn't have a parent.
if (!node.handler && !node.finalizer) {
throw new TypeError(
"TryStatement expects either a handler or finalizer, or both",
);
}
}),
},
handler: {
optional: true,
validate: assertNodeType("CatchClause"),
},
finalizer: {
optional: true,
validate: assertNodeType("BlockStatement"),
},
},
});
defineType("UnaryExpression", {
builder: ["operator", "argument", "prefix"],
fields: {
prefix: {
default: true,
},
argument: {
validate: assertNodeType("Expression"),
},
operator: {
validate: assertOneOf(...UNARY_OPERATORS),
},
},
visitor: ["argument"],
aliases: ["UnaryLike", "Expression"],
});
defineType("UpdateExpression", {
builder: ["operator", "argument", "prefix"],
fields: {
prefix: {
default: false,
},
argument: {
validate: !process.env.BABEL_TYPES_8_BREAKING
? assertNodeType("Expression")
: assertNodeType("Identifier", "MemberExpression"),
},
operator: {
validate: assertOneOf(...UPDATE_OPERATORS),
},
},
visitor: ["argument"],
aliases: ["Expression"],
});
defineType("VariableDeclaration", {
builder: ["kind", "declarations"],
visitor: ["declarations"],
aliases: ["Statement", "Declaration"],
fields: {
declare: {
validate: assertValueType("boolean"),
optional: true,
},
kind: {
validate: assertOneOf("var", "let", "const"),
},
declarations: {
validate: chain(
assertValueType("array"),
assertEach(assertNodeType("VariableDeclarator")),
),
},
},
validate(parent, key, node) {
if (!process.env.BABEL_TYPES_8_BREAKING) return;
if (!is("ForXStatement", parent, { left: node })) return;
if (node.declarations.length !== 1) {
throw new TypeError(
`Exactly one VariableDeclarator is required in the VariableDeclaration of a ${parent.type}`,
);
}
},
});
defineType("VariableDeclarator", {
visitor: ["id", "init"],
fields: {
id: {
validate: (function() {
if (!process.env.BABEL_TYPES_8_BREAKING) {
return assertNodeType("LVal");
}
const normal = assertNodeType(
"Identifier",
"ArrayPattern",
"ObjectPattern",
);
const without = assertNodeType("Identifier");
return function(node, key, val) {
const validator = node.init ? normal : without;
validator(node, key, val);
};
})(),
},
definite: {
optional: true,
validate: assertValueType("boolean"),
},
init: {
optional: true,
validate: assertNodeType("Expression"),
},
},
});
defineType("WhileStatement", {
visitor: ["test", "body"],
aliases: ["Statement", "BlockParent", "Loop", "While", "Scopable"],
fields: {
test: {
validate: assertNodeType("Expression"),
},
body: {
validate: assertNodeType("Statement"),
},
},
});
defineType("WithStatement", {
visitor: ["object", "body"],
aliases: ["Statement"],
fields: {
object: {
validate: assertNodeType("Expression"),
},
body: {
validate: assertNodeType("Statement"),
},
},
});
| packages/babel-types/src/definitions/core.js | 1 | https://github.com/babel/babel/commit/10058901d0703a9f2a4882c4d16c77d10d2145eb | [
0.2726881802082062,
0.0031117338221520185,
0.00016490939015056938,
0.0001729532377794385,
0.026048054918646812
] |
{
"id": 0,
"code_window": [
"defineType(\"RegExpLiteral\", {\n",
" builder: [\"pattern\", \"flags\"],\n",
" deprecatedAlias: \"RegexLiteral\",\n",
" aliases: [\"Expression\", \"Literal\"],\n",
" fields: {\n",
" pattern: {\n",
" validate: assertValueType(\"string\"),\n",
" },\n",
" flags: {\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" aliases: [\"Expression\", \"Pureish\", \"Literal\"],\n"
],
"file_path": "packages/babel-types/src/definitions/core.js",
"type": "replace",
"edit_start_line_idx": 570
} | async <T>(a: T): T => a; | packages/babel-generator/test/fixtures/typescript/arrow-function-async-generic/output.js | 0 | https://github.com/babel/babel/commit/10058901d0703a9f2a4882c4d16c77d10d2145eb | [
0.00016695560771040618,
0.00016695560771040618,
0.00016695560771040618,
0.00016695560771040618,
0
] |
{
"id": 0,
"code_window": [
"defineType(\"RegExpLiteral\", {\n",
" builder: [\"pattern\", \"flags\"],\n",
" deprecatedAlias: \"RegexLiteral\",\n",
" aliases: [\"Expression\", \"Literal\"],\n",
" fields: {\n",
" pattern: {\n",
" validate: assertValueType(\"string\"),\n",
" },\n",
" flags: {\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" aliases: [\"Expression\", \"Pureish\", \"Literal\"],\n"
],
"file_path": "packages/babel-types/src/definitions/core.js",
"type": "replace",
"edit_start_line_idx": 570
} | {
"sourceType": "module"
}
| packages/babel-parser/test/fixtures/es2015/uncategorised/78/options.json | 0 | https://github.com/babel/babel/commit/10058901d0703a9f2a4882c4d16c77d10d2145eb | [
0.00017425282567273825,
0.00017425282567273825,
0.00017425282567273825,
0.00017425282567273825,
0
] |
{
"id": 0,
"code_window": [
"defineType(\"RegExpLiteral\", {\n",
" builder: [\"pattern\", \"flags\"],\n",
" deprecatedAlias: \"RegexLiteral\",\n",
" aliases: [\"Expression\", \"Literal\"],\n",
" fields: {\n",
" pattern: {\n",
" validate: assertValueType(\"string\"),\n",
" },\n",
" flags: {\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" aliases: [\"Expression\", \"Pureish\", \"Literal\"],\n"
],
"file_path": "packages/babel-types/src/definitions/core.js",
"type": "replace",
"edit_start_line_idx": 570
} | export const unreleasedLabels = {
safari: "tp",
};
export const browserNameMap = {
and_chr: "chrome",
and_ff: "firefox",
android: "android",
chrome: "chrome",
edge: "edge",
firefox: "firefox",
ie: "ie",
ie_mob: "ie",
ios_saf: "ios",
node: "node",
op_mob: "opera",
opera: "opera",
safari: "safari",
samsung: "samsung",
};
| packages/babel-helper-compilation-targets/src/targets.js | 0 | https://github.com/babel/babel/commit/10058901d0703a9f2a4882c4d16c77d10d2145eb | [
0.00017659553850535303,
0.00017260412278119475,
0.00016953550220932811,
0.00017168134218081832,
0.0000029551849820563802
] |
{
"id": 2,
"code_window": [
"\n",
"defineType(\"ClassDeclaration\", {\n",
" inherits: \"ClassExpression\",\n",
" aliases: [\"Scopable\", \"Class\", \"Statement\", \"Declaration\", \"Pureish\"],\n",
" fields: {\n",
" declare: {\n",
" validate: assertValueType(\"boolean\"),\n",
" optional: true,\n",
" },\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" aliases: [\"Scopable\", \"Class\", \"Statement\", \"Declaration\"],\n"
],
"file_path": "packages/babel-types/src/definitions/es2015.js",
"type": "replace",
"edit_start_line_idx": 177
} | // @flow
import defineType, {
assertShape,
assertNodeType,
assertValueType,
assertNodeOrValueType,
chain,
assertEach,
assertOneOf,
validateOptional,
} from "./utils";
import {
functionCommon,
functionTypeAnnotationCommon,
patternLikeCommon,
} from "./core";
import is from "../validators/is";
defineType("AssignmentPattern", {
visitor: ["left", "right", "decorators" /* for legacy param decorators */],
builder: ["left", "right"],
aliases: ["Pattern", "PatternLike", "LVal"],
fields: {
...patternLikeCommon,
left: {
validate: assertNodeType(
"Identifier",
"ObjectPattern",
"ArrayPattern",
"MemberExpression",
),
},
right: {
validate: assertNodeType("Expression"),
},
// For TypeScript
decorators: {
validate: chain(
assertValueType("array"),
assertEach(assertNodeType("Decorator")),
),
optional: true,
},
},
});
defineType("ArrayPattern", {
visitor: ["elements", "typeAnnotation"],
builder: ["elements"],
aliases: ["Pattern", "PatternLike", "LVal"],
fields: {
...patternLikeCommon,
elements: {
validate: chain(
assertValueType("array"),
assertEach(assertNodeOrValueType("null", "PatternLike")),
),
},
// For TypeScript
decorators: {
validate: chain(
assertValueType("array"),
assertEach(assertNodeType("Decorator")),
),
optional: true,
},
},
});
defineType("ArrowFunctionExpression", {
builder: ["params", "body", "async"],
visitor: ["params", "body", "returnType", "typeParameters"],
aliases: [
"Scopable",
"Function",
"BlockParent",
"FunctionParent",
"Expression",
"Pureish",
],
fields: {
...functionCommon,
...functionTypeAnnotationCommon,
expression: {
// https://github.com/babel/babylon/issues/505
validate: assertValueType("boolean"),
},
body: {
validate: assertNodeType("BlockStatement", "Expression"),
},
},
});
defineType("ClassBody", {
visitor: ["body"],
fields: {
body: {
validate: chain(
assertValueType("array"),
assertEach(
assertNodeType(
"ClassMethod",
"ClassPrivateMethod",
"ClassProperty",
"ClassPrivateProperty",
"TSDeclareMethod",
"TSIndexSignature",
),
),
),
},
},
});
defineType("ClassExpression", {
builder: ["id", "superClass", "body", "decorators"],
visitor: [
"id",
"body",
"superClass",
"mixins",
"typeParameters",
"superTypeParameters",
"implements",
"decorators",
],
aliases: ["Scopable", "Class", "Expression", "Pureish"],
fields: {
id: {
validate: assertNodeType("Identifier"),
// In declarations, this is missing if this is the
// child of an ExportDefaultDeclaration.
optional: true,
},
typeParameters: {
validate: assertNodeType(
"TypeParameterDeclaration",
"TSTypeParameterDeclaration",
"Noop",
),
optional: true,
},
body: {
validate: assertNodeType("ClassBody"),
},
superClass: {
optional: true,
validate: assertNodeType("Expression"),
},
superTypeParameters: {
validate: assertNodeType(
"TypeParameterInstantiation",
"TSTypeParameterInstantiation",
),
optional: true,
},
implements: {
validate: chain(
assertValueType("array"),
assertEach(
assertNodeType("TSExpressionWithTypeArguments", "ClassImplements"),
),
),
optional: true,
},
decorators: {
validate: chain(
assertValueType("array"),
assertEach(assertNodeType("Decorator")),
),
optional: true,
},
},
});
defineType("ClassDeclaration", {
inherits: "ClassExpression",
aliases: ["Scopable", "Class", "Statement", "Declaration", "Pureish"],
fields: {
declare: {
validate: assertValueType("boolean"),
optional: true,
},
abstract: {
validate: assertValueType("boolean"),
optional: true,
},
},
validate: (function() {
const identifier = assertNodeType("Identifier");
return function(parent, key, node) {
if (!process.env.BABEL_TYPES_8_BREAKING) return;
if (!is("ExportDefaultDeclaration", parent)) {
identifier(node, "id", node.id);
}
};
})(),
});
defineType("ExportAllDeclaration", {
visitor: ["source"],
aliases: [
"Statement",
"Declaration",
"ModuleDeclaration",
"ExportDeclaration",
],
fields: {
source: {
validate: assertNodeType("StringLiteral"),
},
},
});
defineType("ExportDefaultDeclaration", {
visitor: ["declaration"],
aliases: [
"Statement",
"Declaration",
"ModuleDeclaration",
"ExportDeclaration",
],
fields: {
declaration: {
validate: assertNodeType(
"FunctionDeclaration",
"TSDeclareFunction",
"ClassDeclaration",
"Expression",
),
},
},
});
defineType("ExportNamedDeclaration", {
visitor: ["declaration", "specifiers", "source"],
aliases: [
"Statement",
"Declaration",
"ModuleDeclaration",
"ExportDeclaration",
],
fields: {
declaration: {
optional: true,
validate: chain(
assertNodeType("Declaration"),
function(node, key, val) {
if (!process.env.BABEL_TYPES_8_BREAKING) return;
// This validator isn't put at the top level because we can run it
// even if this node doesn't have a parent.
if (val && node.specifiers.length) {
throw new TypeError(
"Only declaration or specifiers is allowed on ExportNamedDeclaration",
);
}
},
function(node, key, val) {
if (!process.env.BABEL_TYPES_8_BREAKING) return;
// This validator isn't put at the top level because we can run it
// even if this node doesn't have a parent.
if (val && node.source) {
throw new TypeError("Cannot export a declaration from a source");
}
},
),
},
specifiers: {
default: [],
validate: chain(
assertValueType("array"),
assertEach(
(function() {
const sourced = assertNodeType(
"ExportSpecifier",
"ExportDefaultSpecifier",
"ExportNamespaceSpecifier",
);
const sourceless = assertNodeType("ExportSpecifier");
if (!process.env.BABEL_TYPES_8_BREAKING) return sourced;
return function(node, key, val) {
const validator = node.source ? sourced : sourceless;
validator(node, key, val);
};
})(),
),
),
},
source: {
validate: assertNodeType("StringLiteral"),
optional: true,
},
exportKind: validateOptional(assertOneOf("type", "value")),
},
});
defineType("ExportSpecifier", {
visitor: ["local", "exported"],
aliases: ["ModuleSpecifier"],
fields: {
local: {
validate: assertNodeType("Identifier"),
},
exported: {
validate: assertNodeType("Identifier"),
},
},
});
defineType("ForOfStatement", {
visitor: ["left", "right", "body"],
builder: ["left", "right", "body", "await"],
aliases: [
"Scopable",
"Statement",
"For",
"BlockParent",
"Loop",
"ForXStatement",
],
fields: {
left: {
validate: (function() {
if (!process.env.BABEL_TYPES_8_BREAKING) {
return assertNodeType("VariableDeclaration", "LVal");
}
const declaration = assertNodeType("VariableDeclaration");
const lval = assertNodeType(
"Identifier",
"MemberExpression",
"ArrayPattern",
"ObjectPattern",
);
return function(node, key, val) {
if (is("VariableDeclaration", val)) {
declaration(node, key, val);
} else {
lval(node, key, val);
}
};
})(),
},
right: {
validate: assertNodeType("Expression"),
},
body: {
validate: assertNodeType("Statement"),
},
await: {
default: false,
},
},
});
defineType("ImportDeclaration", {
visitor: ["specifiers", "source"],
aliases: ["Statement", "Declaration", "ModuleDeclaration"],
fields: {
specifiers: {
validate: chain(
assertValueType("array"),
assertEach(
assertNodeType(
"ImportSpecifier",
"ImportDefaultSpecifier",
"ImportNamespaceSpecifier",
),
),
),
},
source: {
validate: assertNodeType("StringLiteral"),
},
importKind: {
// Handle Flowtype's extension "import {typeof foo} from"
validate: assertOneOf("type", "typeof", "value"),
optional: true,
},
},
});
defineType("ImportDefaultSpecifier", {
visitor: ["local"],
aliases: ["ModuleSpecifier"],
fields: {
local: {
validate: assertNodeType("Identifier"),
},
},
});
defineType("ImportNamespaceSpecifier", {
visitor: ["local"],
aliases: ["ModuleSpecifier"],
fields: {
local: {
validate: assertNodeType("Identifier"),
},
},
});
defineType("ImportSpecifier", {
visitor: ["local", "imported"],
aliases: ["ModuleSpecifier"],
fields: {
local: {
validate: assertNodeType("Identifier"),
},
imported: {
validate: assertNodeType("Identifier"),
},
importKind: {
// Handle Flowtype's extension "import {typeof foo} from"
validate: assertOneOf("type", "typeof"),
optional: true,
},
},
});
defineType("MetaProperty", {
visitor: ["meta", "property"],
aliases: ["Expression"],
fields: {
meta: {
validate: chain(assertNodeType("Identifier"), function(node, key, val) {
if (!process.env.BABEL_TYPES_8_BREAKING) return;
let property;
switch (val.name) {
case "function":
property = "sent";
break;
case "new":
property = "target";
break;
case "import":
property = "meta";
break;
}
if (!is("Identifier", node.property, { name: property })) {
throw new TypeError("Unrecognised MetaProperty");
}
}),
},
property: {
validate: assertNodeType("Identifier"),
},
},
});
export const classMethodOrPropertyCommon = {
abstract: {
validate: assertValueType("boolean"),
optional: true,
},
accessibility: {
validate: assertOneOf("public", "private", "protected"),
optional: true,
},
static: {
default: false,
},
computed: {
default: false,
},
optional: {
validate: assertValueType("boolean"),
optional: true,
},
key: {
validate: chain(
(function() {
const normal = assertNodeType(
"Identifier",
"StringLiteral",
"NumericLiteral",
);
const computed = assertNodeType("Expression");
return function(node: Object, key: string, val: any) {
const validator = node.computed ? computed : normal;
validator(node, key, val);
};
})(),
assertNodeType(
"Identifier",
"StringLiteral",
"NumericLiteral",
"Expression",
),
),
},
};
export const classMethodOrDeclareMethodCommon = {
...functionCommon,
...classMethodOrPropertyCommon,
kind: {
validate: assertOneOf("get", "set", "method", "constructor"),
default: "method",
},
access: {
validate: chain(
assertValueType("string"),
assertOneOf("public", "private", "protected"),
),
optional: true,
},
decorators: {
validate: chain(
assertValueType("array"),
assertEach(assertNodeType("Decorator")),
),
optional: true,
},
};
defineType("ClassMethod", {
aliases: ["Function", "Scopable", "BlockParent", "FunctionParent", "Method"],
builder: [
"kind",
"key",
"params",
"body",
"computed",
"static",
"generator",
"async",
],
visitor: [
"key",
"params",
"body",
"decorators",
"returnType",
"typeParameters",
],
fields: {
...classMethodOrDeclareMethodCommon,
...functionTypeAnnotationCommon,
body: {
validate: assertNodeType("BlockStatement"),
},
},
});
defineType("ObjectPattern", {
visitor: [
"properties",
"typeAnnotation",
"decorators" /* for legacy param decorators */,
],
builder: ["properties"],
aliases: ["Pattern", "PatternLike", "LVal"],
fields: {
...patternLikeCommon,
properties: {
validate: chain(
assertValueType("array"),
assertEach(assertNodeType("RestElement", "ObjectProperty")),
),
},
},
});
defineType("SpreadElement", {
visitor: ["argument"],
aliases: ["UnaryLike"],
deprecatedAlias: "SpreadProperty",
fields: {
argument: {
validate: assertNodeType("Expression"),
},
},
});
defineType("Super", {
aliases: ["Expression"],
});
defineType("TaggedTemplateExpression", {
visitor: ["tag", "quasi"],
aliases: ["Expression"],
fields: {
tag: {
validate: assertNodeType("Expression"),
},
quasi: {
validate: assertNodeType("TemplateLiteral"),
},
typeParameters: {
validate: assertNodeType(
"TypeParameterInstantiation",
"TSTypeParameterInstantiation",
),
optional: true,
},
},
});
defineType("TemplateElement", {
builder: ["value", "tail"],
fields: {
value: {
validate: assertShape({
raw: {
validate: assertValueType("string"),
},
cooked: {
validate: assertValueType("string"),
optional: true,
},
}),
},
tail: {
default: false,
},
},
});
defineType("TemplateLiteral", {
visitor: ["quasis", "expressions"],
aliases: ["Expression", "Literal"],
fields: {
quasis: {
validate: chain(
assertValueType("array"),
assertEach(assertNodeType("TemplateElement")),
),
},
expressions: {
validate: chain(
assertValueType("array"),
assertEach(assertNodeType("Expression")),
function(node, key, val) {
if (node.quasis.length !== val.length + 1) {
throw new TypeError(
`Number of ${
node.type
} quasis should be exactly one more than the number of expressions.\nExpected ${val.length +
1} quasis but got ${node.quasis.length}`,
);
}
},
),
},
},
});
defineType("YieldExpression", {
builder: ["argument", "delegate"],
visitor: ["argument"],
aliases: ["Expression", "Terminatorless"],
fields: {
delegate: {
validate: chain(assertValueType("boolean"), function(node, key, val) {
if (!process.env.BABEL_TYPES_8_BREAKING) return;
if (val && !node.argument) {
throw new TypeError(
"Property delegate of YieldExpression cannot be true if there is no argument",
);
}
}),
default: false,
},
argument: {
optional: true,
validate: assertNodeType("Expression"),
},
},
});
| packages/babel-types/src/definitions/es2015.js | 1 | https://github.com/babel/babel/commit/10058901d0703a9f2a4882c4d16c77d10d2145eb | [
0.007340744137763977,
0.0003990980621892959,
0.000165180055773817,
0.0001929153222590685,
0.0008897505467757583
] |
{
"id": 2,
"code_window": [
"\n",
"defineType(\"ClassDeclaration\", {\n",
" inherits: \"ClassExpression\",\n",
" aliases: [\"Scopable\", \"Class\", \"Statement\", \"Declaration\", \"Pureish\"],\n",
" fields: {\n",
" declare: {\n",
" validate: assertValueType(\"boolean\"),\n",
" optional: true,\n",
" },\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" aliases: [\"Scopable\", \"Class\", \"Statement\", \"Declaration\"],\n"
],
"file_path": "packages/babel-types/src/definitions/es2015.js",
"type": "replace",
"edit_start_line_idx": 177
} | {
"type": "File",
"start": 0,
"end": 34,
"loc": {
"start": {
"line": 1,
"column": 0
},
"end": {
"line": 4,
"column": 1
}
},
"errors": [
"SyntaxError: Explicit inexact syntax cannot appear in class or interface definitions (3:2)"
],
"program": {
"type": "Program",
"start": 0,
"end": 34,
"loc": {
"start": {
"line": 1,
"column": 0
},
"end": {
"line": 4,
"column": 1
}
},
"sourceType": "module",
"interpreter": null,
"body": [
{
"type": "DeclareClass",
"start": 8,
"end": 34,
"loc": {
"start": {
"line": 2,
"column": 0
},
"end": {
"line": 4,
"column": 1
}
},
"id": {
"type": "Identifier",
"start": 22,
"end": 23,
"loc": {
"start": {
"line": 2,
"column": 14
},
"end": {
"line": 2,
"column": 15
},
"identifierName": "A"
},
"name": "A"
},
"typeParameters": null,
"extends": [],
"implements": [],
"mixins": [],
"body": {
"type": "ObjectTypeAnnotation",
"start": 24,
"end": 34,
"loc": {
"start": {
"line": 2,
"column": 16
},
"end": {
"line": 4,
"column": 1
}
},
"callProperties": [],
"properties": [],
"indexers": [],
"internalSlots": [],
"exact": false
},
"leadingComments": [
{
"type": "CommentLine",
"value": "@flow",
"start": 0,
"end": 7,
"loc": {
"start": {
"line": 1,
"column": 0
},
"end": {
"line": 1,
"column": 7
}
}
}
]
}
],
"directives": []
},
"comments": [
{
"type": "CommentLine",
"value": "@flow",
"start": 0,
"end": 7,
"loc": {
"start": {
"line": 1,
"column": 0
},
"end": {
"line": 1,
"column": 7
}
}
}
]
} | packages/babel-parser/test/fixtures/flow/explicit-inexact-object/explicit_inexact_disallowed_in_non_objects1/output.json | 0 | https://github.com/babel/babel/commit/10058901d0703a9f2a4882c4d16c77d10d2145eb | [
0.00017657331773079932,
0.00017195206601172686,
0.00016644696006551385,
0.0001714997342787683,
0.0000022924255063117016
] |
{
"id": 2,
"code_window": [
"\n",
"defineType(\"ClassDeclaration\", {\n",
" inherits: \"ClassExpression\",\n",
" aliases: [\"Scopable\", \"Class\", \"Statement\", \"Declaration\", \"Pureish\"],\n",
" fields: {\n",
" declare: {\n",
" validate: assertValueType(\"boolean\"),\n",
" optional: true,\n",
" },\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" aliases: [\"Scopable\", \"Class\", \"Statement\", \"Declaration\"],\n"
],
"file_path": "packages/babel-types/src/definitions/es2015.js",
"type": "replace",
"edit_start_line_idx": 177
} | let let
| packages/babel-parser/test/fixtures/es2015/let/let-at-binding-list-fail-5/input.js | 0 | https://github.com/babel/babel/commit/10058901d0703a9f2a4882c4d16c77d10d2145eb | [
0.0001745095505611971,
0.0001745095505611971,
0.0001745095505611971,
0.0001745095505611971,
0
] |
{
"id": 2,
"code_window": [
"\n",
"defineType(\"ClassDeclaration\", {\n",
" inherits: \"ClassExpression\",\n",
" aliases: [\"Scopable\", \"Class\", \"Statement\", \"Declaration\", \"Pureish\"],\n",
" fields: {\n",
" declare: {\n",
" validate: assertValueType(\"boolean\"),\n",
" optional: true,\n",
" },\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" aliases: [\"Scopable\", \"Class\", \"Statement\", \"Declaration\"],\n"
],
"file_path": "packages/babel-types/src/definitions/es2015.js",
"type": "replace",
"edit_start_line_idx": 177
} | "use strict";
function _possibleConstructorReturn(self, call) { if (call && (typeof call === "object" || typeof call === "function")) { return call; } return _assertThisInitialized(self); }
function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; }
function set(target, property, value, receiver) { if (typeof Reflect !== "undefined" && Reflect.set) { set = Reflect.set; } else { set = function set(target, property, value, receiver) { var base = _superPropBase(target, property); var desc; if (base) { desc = Object.getOwnPropertyDescriptor(base, property); if (desc.set) { desc.set.call(receiver, value); return true; } else if (!desc.writable) { return false; } } desc = Object.getOwnPropertyDescriptor(receiver, property); if (desc) { if (!desc.writable) { return false; } desc.value = value; Object.defineProperty(receiver, property, desc); } else { _defineProperty(receiver, property, value); } return true; }; } return set(target, property, value, receiver); }
function _set(target, property, value, receiver, isStrict) { var s = set(target, property, value, receiver || target); if (!s && isStrict) { throw new Error('failed to set property'); } return value; }
function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
function _superPropBase(object, property) { while (!Object.prototype.hasOwnProperty.call(object, property)) { object = _getPrototypeOf(object); if (object === null) break; } return object; }
function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) _setPrototypeOf(subClass, superClass); }
function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }
function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }
let value = 1;
let Base = /*#__PURE__*/function () {
function Base() {
_classCallCheck(this, Base);
}
_createClass(Base, [{
key: "test",
set: function (v) {
value = v;
}
}]);
return Base;
}();
let Obj = /*#__PURE__*/function (_Base) {
_inherits(Obj, _Base);
function Obj() {
_classCallCheck(this, Obj);
return _possibleConstructorReturn(this, _getPrototypeOf(Obj).apply(this, arguments));
}
_createClass(Obj, [{
key: "set",
value: function set() {
return _set(_getPrototypeOf(Obj.prototype), "test", 3, this, true);
}
}]);
return Obj;
}(Base);
Object.defineProperty(Obj.prototype, 'test', {
value: 2,
writable: true,
configurable: true
});
const obj = new Obj();
expect(obj.set()).toBe(3);
expect(value).toBe(3);
expect(Base.prototype.test).toBeUndefined();
expect(Obj.prototype.test).toBe(2);
expect(obj.test).toBe(2);
| packages/babel-plugin-transform-classes/test/fixtures/get-set/set-semantics-setter-defined-on-parent/output.js | 0 | https://github.com/babel/babel/commit/10058901d0703a9f2a4882c4d16c77d10d2145eb | [
0.0004984033294022083,
0.0002358763595111668,
0.00016822248289827257,
0.00017302815103903413,
0.00011614924733294174
] |
{
"id": 4,
"code_window": [
" \"ArrowFunctionExpression\" === nodeType ||\n",
" \"ClassExpression\" === nodeType ||\n",
" \"ClassDeclaration\" === nodeType ||\n",
" \"BigIntLiteral\" === nodeType ||\n",
" (nodeType === \"Placeholder\" && \"StringLiteral\" === node.expectedNode)\n",
" ) {\n",
" if (typeof opts === \"undefined\") {\n",
" return true;\n"
],
"labels": [
"keep",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [],
"file_path": "packages/babel-types/src/validators/generated/index.js",
"type": "replace",
"edit_start_line_idx": 1001
} | // @flow
import esutils from "esutils";
import is from "../validators/is";
import {
BINARY_OPERATORS,
LOGICAL_OPERATORS,
ASSIGNMENT_OPERATORS,
UNARY_OPERATORS,
UPDATE_OPERATORS,
} from "../constants";
import defineType, {
assertValueType,
assertNodeType,
assertNodeOrValueType,
assertEach,
chain,
assertOneOf,
} from "./utils";
defineType("ArrayExpression", {
fields: {
elements: {
validate: chain(
assertValueType("array"),
assertEach(
assertNodeOrValueType("null", "Expression", "SpreadElement"),
),
),
default: !process.env.BABEL_TYPES_8_BREAKING ? [] : undefined,
},
},
visitor: ["elements"],
aliases: ["Expression"],
});
defineType("AssignmentExpression", {
fields: {
operator: {
validate: (function() {
if (!process.env.BABEL_TYPES_8_BREAKING) {
return assertValueType("string");
}
const identifier = assertOneOf(...ASSIGNMENT_OPERATORS);
const pattern = assertOneOf("=");
return function(node, key, val) {
const validator = is("Pattern", node.left) ? pattern : identifier;
validator(node, key, val);
};
})(),
},
left: {
validate: !process.env.BABEL_TYPES_8_BREAKING
? assertNodeType("LVal")
: assertNodeType(
"Identifier",
"MemberExpression",
"ArrayPattern",
"ObjectPattern",
),
},
right: {
validate: assertNodeType("Expression"),
},
},
builder: ["operator", "left", "right"],
visitor: ["left", "right"],
aliases: ["Expression"],
});
defineType("BinaryExpression", {
builder: ["operator", "left", "right"],
fields: {
operator: {
validate: assertOneOf(...BINARY_OPERATORS),
},
left: {
validate: assertNodeType("Expression"),
},
right: {
validate: assertNodeType("Expression"),
},
},
visitor: ["left", "right"],
aliases: ["Binary", "Expression"],
});
defineType("InterpreterDirective", {
builder: ["value"],
fields: {
value: {
validate: assertValueType("string"),
},
},
});
defineType("Directive", {
visitor: ["value"],
fields: {
value: {
validate: assertNodeType("DirectiveLiteral"),
},
},
});
defineType("DirectiveLiteral", {
builder: ["value"],
fields: {
value: {
validate: assertValueType("string"),
},
},
});
defineType("BlockStatement", {
builder: ["body", "directives"],
visitor: ["directives", "body"],
fields: {
directives: {
validate: chain(
assertValueType("array"),
assertEach(assertNodeType("Directive")),
),
default: [],
},
body: {
validate: chain(
assertValueType("array"),
assertEach(assertNodeType("Statement")),
),
},
},
aliases: ["Scopable", "BlockParent", "Block", "Statement"],
});
defineType("BreakStatement", {
visitor: ["label"],
fields: {
label: {
validate: assertNodeType("Identifier"),
optional: true,
},
},
aliases: ["Statement", "Terminatorless", "CompletionStatement"],
});
defineType("CallExpression", {
visitor: ["callee", "arguments", "typeParameters", "typeArguments"],
builder: ["callee", "arguments"],
aliases: ["Expression"],
fields: {
callee: {
validate: assertNodeType("Expression", "V8IntrinsicIdentifier"),
},
arguments: {
validate: chain(
assertValueType("array"),
assertEach(
assertNodeType(
"Expression",
"SpreadElement",
"JSXNamespacedName",
"ArgumentPlaceholder",
),
),
),
},
...(!process.env.BABEL_TYPES_8_BREAKING
? {
optional: {
validate: assertOneOf(true, false),
optional: true,
},
}
: {}),
typeArguments: {
validate: assertNodeType("TypeParameterInstantiation"),
optional: true,
},
typeParameters: {
validate: assertNodeType("TSTypeParameterInstantiation"),
optional: true,
},
},
});
defineType("CatchClause", {
visitor: ["param", "body"],
fields: {
param: {
validate: assertNodeType("Identifier", "ArrayPattern", "ObjectPattern"),
optional: true,
},
body: {
validate: assertNodeType("BlockStatement"),
},
},
aliases: ["Scopable", "BlockParent"],
});
defineType("ConditionalExpression", {
visitor: ["test", "consequent", "alternate"],
fields: {
test: {
validate: assertNodeType("Expression"),
},
consequent: {
validate: assertNodeType("Expression"),
},
alternate: {
validate: assertNodeType("Expression"),
},
},
aliases: ["Expression", "Conditional"],
});
defineType("ContinueStatement", {
visitor: ["label"],
fields: {
label: {
validate: assertNodeType("Identifier"),
optional: true,
},
},
aliases: ["Statement", "Terminatorless", "CompletionStatement"],
});
defineType("DebuggerStatement", {
aliases: ["Statement"],
});
defineType("DoWhileStatement", {
visitor: ["test", "body"],
fields: {
test: {
validate: assertNodeType("Expression"),
},
body: {
validate: assertNodeType("Statement"),
},
},
aliases: ["Statement", "BlockParent", "Loop", "While", "Scopable"],
});
defineType("EmptyStatement", {
aliases: ["Statement"],
});
defineType("ExpressionStatement", {
visitor: ["expression"],
fields: {
expression: {
validate: assertNodeType("Expression"),
},
},
aliases: ["Statement", "ExpressionWrapper"],
});
defineType("File", {
builder: ["program", "comments", "tokens"],
visitor: ["program"],
fields: {
program: {
validate: assertNodeType("Program"),
},
},
});
defineType("ForInStatement", {
visitor: ["left", "right", "body"],
aliases: [
"Scopable",
"Statement",
"For",
"BlockParent",
"Loop",
"ForXStatement",
],
fields: {
left: {
validate: !process.env.BABEL_TYPES_8_BREAKING
? assertNodeType("VariableDeclaration", "LVal")
: assertNodeType(
"VariableDeclaration",
"Identifier",
"MemberExpression",
"ArrayPattern",
"ObjectPattern",
),
},
right: {
validate: assertNodeType("Expression"),
},
body: {
validate: assertNodeType("Statement"),
},
},
});
defineType("ForStatement", {
visitor: ["init", "test", "update", "body"],
aliases: ["Scopable", "Statement", "For", "BlockParent", "Loop"],
fields: {
init: {
validate: assertNodeType("VariableDeclaration", "Expression"),
optional: true,
},
test: {
validate: assertNodeType("Expression"),
optional: true,
},
update: {
validate: assertNodeType("Expression"),
optional: true,
},
body: {
validate: assertNodeType("Statement"),
},
},
});
export const functionCommon = {
params: {
validate: chain(
assertValueType("array"),
assertEach(
assertNodeType(
"Identifier",
"Pattern",
"RestElement",
"TSParameterProperty",
),
),
),
},
generator: {
default: false,
},
async: {
default: false,
},
};
export const functionTypeAnnotationCommon = {
returnType: {
validate: assertNodeType("TypeAnnotation", "TSTypeAnnotation", "Noop"),
optional: true,
},
typeParameters: {
validate: assertNodeType(
"TypeParameterDeclaration",
"TSTypeParameterDeclaration",
"Noop",
),
optional: true,
},
};
export const functionDeclarationCommon = {
...functionCommon,
declare: {
validate: assertValueType("boolean"),
optional: true,
},
id: {
validate: assertNodeType("Identifier"),
optional: true, // May be null for `export default function`
},
};
defineType("FunctionDeclaration", {
builder: ["id", "params", "body", "generator", "async"],
visitor: ["id", "params", "body", "returnType", "typeParameters"],
fields: {
...functionDeclarationCommon,
...functionTypeAnnotationCommon,
body: {
validate: assertNodeType("BlockStatement"),
},
},
aliases: [
"Scopable",
"Function",
"BlockParent",
"FunctionParent",
"Statement",
"Pureish",
"Declaration",
],
validate: (function() {
if (!process.env.BABEL_TYPES_8_BREAKING) return () => {};
const identifier = assertNodeType("Identifier");
return function(parent, key, node) {
if (!is("ExportDefaultDeclaration", parent)) {
identifier(node, "id", node.id);
}
};
})(),
});
defineType("FunctionExpression", {
inherits: "FunctionDeclaration",
aliases: [
"Scopable",
"Function",
"BlockParent",
"FunctionParent",
"Expression",
"Pureish",
],
fields: {
...functionCommon,
...functionTypeAnnotationCommon,
id: {
validate: assertNodeType("Identifier"),
optional: true,
},
body: {
validate: assertNodeType("BlockStatement"),
},
},
});
export const patternLikeCommon = {
typeAnnotation: {
// TODO: @babel/plugin-transform-flow-comments puts a Noop here, is there a better way?
validate: assertNodeType("TypeAnnotation", "TSTypeAnnotation", "Noop"),
optional: true,
},
decorators: {
validate: chain(
assertValueType("array"),
assertEach(assertNodeType("Decorator")),
),
},
};
defineType("Identifier", {
builder: ["name"],
visitor: ["typeAnnotation", "decorators" /* for legacy param decorators */],
aliases: ["Expression", "PatternLike", "LVal", "TSEntityName"],
fields: {
...patternLikeCommon,
name: {
validate: chain(assertValueType("string"), function(node, key, val) {
if (!process.env.BABEL_TYPES_8_BREAKING) return;
if (!esutils.keyword.isIdentifierNameES6(val)) {
throw new TypeError(`"${val}" is not a valid identifier name`);
}
}),
},
optional: {
validate: assertValueType("boolean"),
optional: true,
},
},
validate(parent, key, node) {
if (!process.env.BABEL_TYPES_8_BREAKING) return;
const match = /\.(\w+)$/.exec(key);
if (!match) return;
const [, parentKey] = match;
const nonComp = { computed: false };
// We can't check if `parent.property === node`, because nodes are validated
// before replacing them in the AST.
if (parentKey === "property") {
if (is("MemberExpression", parent, nonComp)) return;
if (is("OptionalMemberExpression", parent, nonComp)) return;
} else if (parentKey === "key") {
if (is("Property", parent, nonComp)) return;
if (is("Method", parent, nonComp)) return;
} else if (parentKey === "exported") {
if (is("ExportSpecifier", parent)) return;
} else if (parentKey === "imported") {
if (is("ImportSpecifier", parent, { imported: node })) return;
} else if (parentKey === "meta") {
if (is("MetaProperty", parent, { meta: node })) return;
}
if (
// Ideally this should be strict if this node is a descendant of a block
// in strict mode. Also, we should disallow "await" in modules.
esutils.keyword.isReservedWordES6(node.name, /* strict */ false) &&
// Even if "this" is a keyword, we are using the Identifier
// node to represent it.
node.name !== "this"
) {
throw new TypeError(`"${node.name}" is not a valid identifer`);
}
},
});
defineType("IfStatement", {
visitor: ["test", "consequent", "alternate"],
aliases: ["Statement", "Conditional"],
fields: {
test: {
validate: assertNodeType("Expression"),
},
consequent: {
validate: assertNodeType("Statement"),
},
alternate: {
optional: true,
validate: assertNodeType("Statement"),
},
},
});
defineType("LabeledStatement", {
visitor: ["label", "body"],
aliases: ["Statement"],
fields: {
label: {
validate: assertNodeType("Identifier"),
},
body: {
validate: assertNodeType("Statement"),
},
},
});
defineType("StringLiteral", {
builder: ["value"],
fields: {
value: {
validate: assertValueType("string"),
},
},
aliases: ["Expression", "Pureish", "Literal", "Immutable"],
});
defineType("NumericLiteral", {
builder: ["value"],
deprecatedAlias: "NumberLiteral",
fields: {
value: {
validate: assertValueType("number"),
},
},
aliases: ["Expression", "Pureish", "Literal", "Immutable"],
});
defineType("NullLiteral", {
aliases: ["Expression", "Pureish", "Literal", "Immutable"],
});
defineType("BooleanLiteral", {
builder: ["value"],
fields: {
value: {
validate: assertValueType("boolean"),
},
},
aliases: ["Expression", "Pureish", "Literal", "Immutable"],
});
defineType("RegExpLiteral", {
builder: ["pattern", "flags"],
deprecatedAlias: "RegexLiteral",
aliases: ["Expression", "Literal"],
fields: {
pattern: {
validate: assertValueType("string"),
},
flags: {
validate: chain(assertValueType("string"), function(node, key, val) {
if (!process.env.BABEL_TYPES_8_BREAKING) return;
const invalid = /[^gimsuy]/.exec(val);
if (invalid) {
throw new TypeError(`"${invalid[0]}" is not a valid RegExp flag`);
}
}),
default: "",
},
},
});
defineType("LogicalExpression", {
builder: ["operator", "left", "right"],
visitor: ["left", "right"],
aliases: ["Binary", "Expression"],
fields: {
operator: {
validate: assertOneOf(...LOGICAL_OPERATORS),
},
left: {
validate: assertNodeType("Expression"),
},
right: {
validate: assertNodeType("Expression"),
},
},
});
defineType("MemberExpression", {
builder: ["object", "property", "computed", "optional"],
visitor: ["object", "property"],
aliases: ["Expression", "LVal"],
fields: {
object: {
validate: assertNodeType("Expression"),
},
property: {
validate: (function() {
const normal = assertNodeType("Identifier", "PrivateName");
const computed = assertNodeType("Expression");
return function(node, key, val) {
const validator = node.computed ? computed : normal;
validator(node, key, val);
};
})(),
},
computed: {
default: false,
},
...(!process.env.BABEL_TYPES_8_BREAKING
? {
optional: {
validate: assertOneOf(true, false),
optional: true,
},
}
: {}),
},
});
defineType("NewExpression", { inherits: "CallExpression" });
defineType("Program", {
// Note: We explicitly leave 'interpreter' out here because it is
// conceptually comment-like, and Babel does not traverse comments either.
visitor: ["directives", "body"],
builder: ["body", "directives", "sourceType", "interpreter"],
fields: {
sourceFile: {
validate: assertValueType("string"),
},
sourceType: {
validate: assertOneOf("script", "module"),
default: "script",
},
interpreter: {
validate: assertNodeType("InterpreterDirective"),
default: null,
optional: true,
},
directives: {
validate: chain(
assertValueType("array"),
assertEach(assertNodeType("Directive")),
),
default: [],
},
body: {
validate: chain(
assertValueType("array"),
assertEach(assertNodeType("Statement")),
),
},
},
aliases: ["Scopable", "BlockParent", "Block"],
});
defineType("ObjectExpression", {
visitor: ["properties"],
aliases: ["Expression"],
fields: {
properties: {
validate: chain(
assertValueType("array"),
assertEach(
assertNodeType("ObjectMethod", "ObjectProperty", "SpreadElement"),
),
),
},
},
});
defineType("ObjectMethod", {
builder: ["kind", "key", "params", "body", "computed", "generator", "async"],
fields: {
...functionCommon,
...functionTypeAnnotationCommon,
kind: {
validate: assertOneOf("method", "get", "set"),
...(!process.env.BABEL_TYPES_8_BREAKING ? { default: "method" } : {}),
},
computed: {
default: false,
},
key: {
validate: (function() {
const normal = assertNodeType(
"Identifier",
"StringLiteral",
"NumericLiteral",
);
const computed = assertNodeType("Expression");
return function(node, key, val) {
const validator = node.computed ? computed : normal;
validator(node, key, val);
};
})(),
},
decorators: {
validate: chain(
assertValueType("array"),
assertEach(assertNodeType("Decorator")),
),
optional: true,
},
body: {
validate: assertNodeType("BlockStatement"),
},
},
visitor: [
"key",
"params",
"body",
"decorators",
"returnType",
"typeParameters",
],
aliases: [
"UserWhitespacable",
"Function",
"Scopable",
"BlockParent",
"FunctionParent",
"Method",
"ObjectMember",
],
});
defineType("ObjectProperty", {
builder: [
"key",
"value",
"computed",
"shorthand",
...(!process.env.BABEL_TYPES_8_BREAKING ? ["decorators"] : []),
],
fields: {
computed: {
default: false,
},
key: {
validate: (function() {
const normal = assertNodeType(
"Identifier",
"StringLiteral",
"NumericLiteral",
);
const computed = assertNodeType("Expression");
return function(node, key, val) {
const validator = node.computed ? computed : normal;
validator(node, key, val);
};
})(),
},
value: {
// Value may be PatternLike if this is an AssignmentProperty
// https://github.com/babel/babylon/issues/434
validate: assertNodeType("Expression", "PatternLike"),
},
shorthand: {
validate: chain(
assertValueType("boolean"),
function(node, key, val) {
if (!process.env.BABEL_TYPES_8_BREAKING) return;
if (val && node.computed) {
throw new TypeError(
"Property shorthand of ObjectProperty cannot be true if computed is true",
);
}
},
function(node, key, val) {
if (!process.env.BABEL_TYPES_8_BREAKING) return;
if (val && !is("Identifier", node.key)) {
throw new TypeError(
"Property shorthand of ObjectProperty cannot be true if key is not an Identifier",
);
}
},
),
default: false,
},
decorators: {
validate: chain(
assertValueType("array"),
assertEach(assertNodeType("Decorator")),
),
optional: true,
},
},
visitor: ["key", "value", "decorators"],
aliases: ["UserWhitespacable", "Property", "ObjectMember"],
validate: (function() {
const pattern = assertNodeType("Identifier", "Pattern");
const expression = assertNodeType("Expression");
return function(parent, key, node) {
if (!process.env.BABEL_TYPES_8_BREAKING) return;
const validator = is("ObjectPattern", parent) ? pattern : expression;
validator(node, "value", node.value);
};
})(),
});
defineType("RestElement", {
visitor: ["argument", "typeAnnotation"],
builder: ["argument"],
aliases: ["LVal", "PatternLike"],
deprecatedAlias: "RestProperty",
fields: {
...patternLikeCommon,
argument: {
validate: !process.env.BABEL_TYPES_8_BREAKING
? assertNodeType("LVal")
: assertNodeType("Identifier", "Pattern", "MemberExpression"),
},
},
validate(parent, key) {
if (!process.env.BABEL_TYPES_8_BREAKING) return;
const match = /(\w+)\[(\d+)\]/.exec(key);
if (!match) throw new Error("Internal Babel error: malformed key.");
const [, listKey, index] = match;
if (parent[listKey].length > index + 1) {
throw new TypeError(`RestElement must be last element of ${listKey}`);
}
},
});
defineType("ReturnStatement", {
visitor: ["argument"],
aliases: ["Statement", "Terminatorless", "CompletionStatement"],
fields: {
argument: {
validate: assertNodeType("Expression"),
optional: true,
},
},
});
defineType("SequenceExpression", {
visitor: ["expressions"],
fields: {
expressions: {
validate: chain(
assertValueType("array"),
assertEach(assertNodeType("Expression")),
),
},
},
aliases: ["Expression"],
});
defineType("ParenthesizedExpression", {
visitor: ["expression"],
aliases: ["Expression", "ExpressionWrapper"],
fields: {
expression: {
validate: assertNodeType("Expression"),
},
},
});
defineType("SwitchCase", {
visitor: ["test", "consequent"],
fields: {
test: {
validate: assertNodeType("Expression"),
optional: true,
},
consequent: {
validate: chain(
assertValueType("array"),
assertEach(assertNodeType("Statement")),
),
},
},
});
defineType("SwitchStatement", {
visitor: ["discriminant", "cases"],
aliases: ["Statement", "BlockParent", "Scopable"],
fields: {
discriminant: {
validate: assertNodeType("Expression"),
},
cases: {
validate: chain(
assertValueType("array"),
assertEach(assertNodeType("SwitchCase")),
),
},
},
});
defineType("ThisExpression", {
aliases: ["Expression"],
});
defineType("ThrowStatement", {
visitor: ["argument"],
aliases: ["Statement", "Terminatorless", "CompletionStatement"],
fields: {
argument: {
validate: assertNodeType("Expression"),
},
},
});
defineType("TryStatement", {
visitor: ["block", "handler", "finalizer"],
aliases: ["Statement"],
fields: {
block: {
validate: chain(assertNodeType("BlockStatement"), function(node) {
if (!process.env.BABEL_TYPES_8_BREAKING) return;
// This validator isn't put at the top level because we can run it
// even if this node doesn't have a parent.
if (!node.handler && !node.finalizer) {
throw new TypeError(
"TryStatement expects either a handler or finalizer, or both",
);
}
}),
},
handler: {
optional: true,
validate: assertNodeType("CatchClause"),
},
finalizer: {
optional: true,
validate: assertNodeType("BlockStatement"),
},
},
});
defineType("UnaryExpression", {
builder: ["operator", "argument", "prefix"],
fields: {
prefix: {
default: true,
},
argument: {
validate: assertNodeType("Expression"),
},
operator: {
validate: assertOneOf(...UNARY_OPERATORS),
},
},
visitor: ["argument"],
aliases: ["UnaryLike", "Expression"],
});
defineType("UpdateExpression", {
builder: ["operator", "argument", "prefix"],
fields: {
prefix: {
default: false,
},
argument: {
validate: !process.env.BABEL_TYPES_8_BREAKING
? assertNodeType("Expression")
: assertNodeType("Identifier", "MemberExpression"),
},
operator: {
validate: assertOneOf(...UPDATE_OPERATORS),
},
},
visitor: ["argument"],
aliases: ["Expression"],
});
defineType("VariableDeclaration", {
builder: ["kind", "declarations"],
visitor: ["declarations"],
aliases: ["Statement", "Declaration"],
fields: {
declare: {
validate: assertValueType("boolean"),
optional: true,
},
kind: {
validate: assertOneOf("var", "let", "const"),
},
declarations: {
validate: chain(
assertValueType("array"),
assertEach(assertNodeType("VariableDeclarator")),
),
},
},
validate(parent, key, node) {
if (!process.env.BABEL_TYPES_8_BREAKING) return;
if (!is("ForXStatement", parent, { left: node })) return;
if (node.declarations.length !== 1) {
throw new TypeError(
`Exactly one VariableDeclarator is required in the VariableDeclaration of a ${parent.type}`,
);
}
},
});
defineType("VariableDeclarator", {
visitor: ["id", "init"],
fields: {
id: {
validate: (function() {
if (!process.env.BABEL_TYPES_8_BREAKING) {
return assertNodeType("LVal");
}
const normal = assertNodeType(
"Identifier",
"ArrayPattern",
"ObjectPattern",
);
const without = assertNodeType("Identifier");
return function(node, key, val) {
const validator = node.init ? normal : without;
validator(node, key, val);
};
})(),
},
definite: {
optional: true,
validate: assertValueType("boolean"),
},
init: {
optional: true,
validate: assertNodeType("Expression"),
},
},
});
defineType("WhileStatement", {
visitor: ["test", "body"],
aliases: ["Statement", "BlockParent", "Loop", "While", "Scopable"],
fields: {
test: {
validate: assertNodeType("Expression"),
},
body: {
validate: assertNodeType("Statement"),
},
},
});
defineType("WithStatement", {
visitor: ["object", "body"],
aliases: ["Statement"],
fields: {
object: {
validate: assertNodeType("Expression"),
},
body: {
validate: assertNodeType("Statement"),
},
},
});
| packages/babel-types/src/definitions/core.js | 1 | https://github.com/babel/babel/commit/10058901d0703a9f2a4882c4d16c77d10d2145eb | [
0.0009077061549760401,
0.0001951243611983955,
0.00016337214037775993,
0.00017305965593550354,
0.00009501455497229472
] |
{
"id": 4,
"code_window": [
" \"ArrowFunctionExpression\" === nodeType ||\n",
" \"ClassExpression\" === nodeType ||\n",
" \"ClassDeclaration\" === nodeType ||\n",
" \"BigIntLiteral\" === nodeType ||\n",
" (nodeType === \"Placeholder\" && \"StringLiteral\" === node.expectedNode)\n",
" ) {\n",
" if (typeof opts === \"undefined\") {\n",
" return true;\n"
],
"labels": [
"keep",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [],
"file_path": "packages/babel-types/src/validators/generated/index.js",
"type": "replace",
"edit_start_line_idx": 1001
} | Array.from; // static method
Map; // built-in
new Promise(); // new builtin
Symbol.match; // as member expression
_arr[Symbol.iterator](); // Symbol.iterator
// no import
Array.asdf;
Array2.from;
Map2;
new Promise2();
Symbol.asdf;
Symbol2.match;
_arr9[Symbol2.iterator]();
_arr9[Symbol.iterator2]();
G.assign; // static method
function H(WeakMap) { var blah = new WeakMap(); } // shadowed
const foo = new Promise((resolve) => {
resolve(new Map());
});
queueMicrotask(() => globalThis);
Observable.from(10);
| packages/babel-preset-env/test/fixtures/corejs3/usage-shippedProposals/input.mjs | 0 | https://github.com/babel/babel/commit/10058901d0703a9f2a4882c4d16c77d10d2145eb | [
0.00017890901654027402,
0.0001757186691975221,
0.00017371763533446938,
0.00017452937026973814,
0.00000228012322622817
] |
{
"id": 4,
"code_window": [
" \"ArrowFunctionExpression\" === nodeType ||\n",
" \"ClassExpression\" === nodeType ||\n",
" \"ClassDeclaration\" === nodeType ||\n",
" \"BigIntLiteral\" === nodeType ||\n",
" (nodeType === \"Placeholder\" && \"StringLiteral\" === node.expectedNode)\n",
" ) {\n",
" if (typeof opts === \"undefined\") {\n",
" return true;\n"
],
"labels": [
"keep",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [],
"file_path": "packages/babel-types/src/validators/generated/index.js",
"type": "replace",
"edit_start_line_idx": 1001
} | "use strict";
var foo = babelHelpers.interopRequireWildcard(require("foo"));
| packages/babel-plugin-transform-modules-commonjs/test/fixtures/interop/imports-glob/output.js | 0 | https://github.com/babel/babel/commit/10058901d0703a9f2a4882c4d16c77d10d2145eb | [
0.0001701711880741641,
0.0001701711880741641,
0.0001701711880741641,
0.0001701711880741641,
0
] |
{
"id": 4,
"code_window": [
" \"ArrowFunctionExpression\" === nodeType ||\n",
" \"ClassExpression\" === nodeType ||\n",
" \"ClassDeclaration\" === nodeType ||\n",
" \"BigIntLiteral\" === nodeType ||\n",
" (nodeType === \"Placeholder\" && \"StringLiteral\" === node.expectedNode)\n",
" ) {\n",
" if (typeof opts === \"undefined\") {\n",
" return true;\n"
],
"labels": [
"keep",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [],
"file_path": "packages/babel-types/src/validators/generated/index.js",
"type": "replace",
"edit_start_line_idx": 1001
} | (function () {
'use strict';
var _functionReturn;
var result = (_functionReturn = '(function() { return this; })()', (0, eval)(_functionReturn));
expect(result).not.toBeUndefined();
})();
| packages/babel-plugin-proposal-pipeline-operator/test/fixtures/smart/indirect-eval/output.js | 0 | https://github.com/babel/babel/commit/10058901d0703a9f2a4882c4d16c77d10d2145eb | [
0.00017545456648804247,
0.00017545456648804247,
0.00017545456648804247,
0.00017545456648804247,
0
] |
{
"id": 0,
"code_window": [
" expect(doubled).toBe(undefined)\n",
" })\n",
"\n",
" it('should fire onDispose hook', () => {\n",
" let dummy = 0\n",
"\n",
" const scope = new EffectScope()\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" it('should fire onScopeDispose hook', () => {\n"
],
"file_path": "packages/reactivity/__tests__/effectScope.spec.ts",
"type": "replace",
"edit_start_line_idx": 175
} | import { ReactiveEffect } from './effect'
import { warn } from './warning'
let activeEffectScope: EffectScope | undefined
const effectScopeStack: EffectScope[] = []
export class EffectScope {
active = true
effects: ReactiveEffect[] = []
cleanups: (() => void)[] = []
parent: EffectScope | undefined
scopes: EffectScope[] | undefined
/**
* track a child scope's index in its parent's scopes array for optimized
* removal
*/
private index: number | undefined
constructor(detached = false) {
if (!detached && activeEffectScope) {
this.parent = activeEffectScope
this.index =
(activeEffectScope.scopes || (activeEffectScope.scopes = [])).push(
this
) - 1
}
}
run<T>(fn: () => T): T | undefined {
if (this.active) {
try {
this.on()
return fn()
} finally {
this.off()
}
} else if (__DEV__) {
warn(`cannot run an inactive effect scope.`)
}
}
on() {
if (this.active) {
effectScopeStack.push(this)
activeEffectScope = this
}
}
off() {
if (this.active) {
effectScopeStack.pop()
activeEffectScope = effectScopeStack[effectScopeStack.length - 1]
}
}
stop(fromParent?: boolean) {
if (this.active) {
this.effects.forEach(e => e.stop())
this.cleanups.forEach(cleanup => cleanup())
if (this.scopes) {
this.scopes.forEach(e => e.stop(true))
}
// nested scope, dereference from parent to avoid memory leaks
if (this.parent && !fromParent) {
// optimized O(1) removal
const last = this.parent.scopes!.pop()
if (last && last !== this) {
this.parent.scopes![this.index!] = last
last.index = this.index!
}
}
this.active = false
}
}
}
export function effectScope(detached?: boolean) {
return new EffectScope(detached)
}
export function recordEffectScope(
effect: ReactiveEffect,
scope?: EffectScope | null
) {
scope = scope || activeEffectScope
if (scope && scope.active) {
scope.effects.push(effect)
}
}
export function getCurrentScope() {
return activeEffectScope
}
export function onScopeDispose(fn: () => void) {
if (activeEffectScope) {
activeEffectScope.cleanups.push(fn)
} else if (__DEV__) {
warn(
`onDispose() is called when there is no active effect scope` +
` to be associated with.`
)
}
}
| packages/reactivity/src/effectScope.ts | 1 | https://github.com/vuejs/core/commit/7c4e4514d166b2fcb055baa091a79d9244458ab5 | [
0.9957081079483032,
0.09236492961645126,
0.00020327186211943626,
0.0011360823409631848,
0.2856723666191101
] |
{
"id": 0,
"code_window": [
" expect(doubled).toBe(undefined)\n",
" })\n",
"\n",
" it('should fire onDispose hook', () => {\n",
" let dummy = 0\n",
"\n",
" const scope = new EffectScope()\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" it('should fire onScopeDispose hook', () => {\n"
],
"file_path": "packages/reactivity/__tests__/effectScope.spec.ts",
"type": "replace",
"edit_start_line_idx": 175
} | import { createApp } from 'vue'
import App from './App.vue'
createApp(App).mount('#app')
| packages/sfc-playground/src/main.ts | 0 | https://github.com/vuejs/core/commit/7c4e4514d166b2fcb055baa091a79d9244458ab5 | [
0.0001738064456731081,
0.0001738064456731081,
0.0001738064456731081,
0.0001738064456731081,
0
] |
{
"id": 0,
"code_window": [
" expect(doubled).toBe(undefined)\n",
" })\n",
"\n",
" it('should fire onDispose hook', () => {\n",
" let dummy = 0\n",
"\n",
" const scope = new EffectScope()\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" it('should fire onScopeDispose hook', () => {\n"
],
"file_path": "packages/reactivity/__tests__/effectScope.spec.ts",
"type": "replace",
"edit_start_line_idx": 175
} | import {
CompilerOptions,
baseParse as parse,
transform,
ElementNode,
NodeTypes,
ErrorCodes
} from '../../src'
import { transformElement } from '../../src/transforms/transformElement'
import { transformOn } from '../../src/transforms/vOn'
import { transformBind } from '../../src/transforms/vBind'
import { transformExpression } from '../../src/transforms/transformExpression'
import { RENDER_SLOT } from '../../src/runtimeHelpers'
import { transformSlotOutlet } from '../../src/transforms/transformSlotOutlet'
function parseWithSlots(template: string, options: CompilerOptions = {}) {
const ast = parse(template)
transform(ast, {
nodeTransforms: [
...(options.prefixIdentifiers ? [transformExpression] : []),
transformSlotOutlet,
transformElement
],
directiveTransforms: {
on: transformOn,
bind: transformBind
},
...options
})
return ast
}
describe('compiler: transform <slot> outlets', () => {
test('default slot outlet', () => {
const ast = parseWithSlots(`<slot/>`)
expect((ast.children[0] as ElementNode).codegenNode).toMatchObject({
type: NodeTypes.JS_CALL_EXPRESSION,
callee: RENDER_SLOT,
arguments: [`$slots`, `"default"`]
})
})
test('statically named slot outlet', () => {
const ast = parseWithSlots(`<slot name="foo" />`)
expect((ast.children[0] as ElementNode).codegenNode).toMatchObject({
type: NodeTypes.JS_CALL_EXPRESSION,
callee: RENDER_SLOT,
arguments: [`$slots`, `"foo"`]
})
})
test('dynamically named slot outlet', () => {
const ast = parseWithSlots(`<slot :name="foo" />`)
expect((ast.children[0] as ElementNode).codegenNode).toMatchObject({
type: NodeTypes.JS_CALL_EXPRESSION,
callee: RENDER_SLOT,
arguments: [
`$slots`,
{
type: NodeTypes.SIMPLE_EXPRESSION,
content: `foo`,
isStatic: false
}
]
})
})
test('dynamically named slot outlet w/ prefixIdentifiers: true', () => {
const ast = parseWithSlots(`<slot :name="foo + bar" />`, {
prefixIdentifiers: true
})
expect((ast.children[0] as ElementNode).codegenNode).toMatchObject({
type: NodeTypes.JS_CALL_EXPRESSION,
callee: RENDER_SLOT,
arguments: [
`_ctx.$slots`,
{
type: NodeTypes.COMPOUND_EXPRESSION,
children: [
{
type: NodeTypes.SIMPLE_EXPRESSION,
content: `_ctx.foo`,
isStatic: false
},
` + `,
{
type: NodeTypes.SIMPLE_EXPRESSION,
content: `_ctx.bar`,
isStatic: false
}
]
}
]
})
})
test('default slot outlet with props', () => {
const ast = parseWithSlots(
`<slot foo="bar" :baz="qux" :foo-bar="foo-bar" />`
)
expect((ast.children[0] as ElementNode).codegenNode).toMatchObject({
type: NodeTypes.JS_CALL_EXPRESSION,
callee: RENDER_SLOT,
arguments: [
`$slots`,
`"default"`,
{
type: NodeTypes.JS_OBJECT_EXPRESSION,
properties: [
{
key: {
content: `foo`,
isStatic: true
},
value: {
content: `bar`,
isStatic: true
}
},
{
key: {
content: `baz`,
isStatic: true
},
value: {
content: `qux`,
isStatic: false
}
},
{
key: {
content: `fooBar`,
isStatic: true
},
value: {
content: `foo-bar`,
isStatic: false
}
}
]
}
]
})
})
test('statically named slot outlet with props', () => {
const ast = parseWithSlots(`<slot name="foo" foo="bar" :baz="qux" />`)
expect((ast.children[0] as ElementNode).codegenNode).toMatchObject({
type: NodeTypes.JS_CALL_EXPRESSION,
callee: RENDER_SLOT,
arguments: [
`$slots`,
`"foo"`,
{
type: NodeTypes.JS_OBJECT_EXPRESSION,
// props should not include name
properties: [
{
key: {
content: `foo`,
isStatic: true
},
value: {
content: `bar`,
isStatic: true
}
},
{
key: {
content: `baz`,
isStatic: true
},
value: {
content: `qux`,
isStatic: false
}
}
]
}
]
})
})
test('dynamically named slot outlet with props', () => {
const ast = parseWithSlots(`<slot :name="foo" foo="bar" :baz="qux" />`)
expect((ast.children[0] as ElementNode).codegenNode).toMatchObject({
type: NodeTypes.JS_CALL_EXPRESSION,
callee: RENDER_SLOT,
arguments: [
`$slots`,
{ content: `foo`, isStatic: false },
{
type: NodeTypes.JS_OBJECT_EXPRESSION,
// props should not include name
properties: [
{
key: {
content: `foo`,
isStatic: true
},
value: {
content: `bar`,
isStatic: true
}
},
{
key: {
content: `baz`,
isStatic: true
},
value: {
content: `qux`,
isStatic: false
}
}
]
}
]
})
})
test('default slot outlet with fallback', () => {
const ast = parseWithSlots(`<slot><div/></slot>`)
expect((ast.children[0] as ElementNode).codegenNode).toMatchObject({
type: NodeTypes.JS_CALL_EXPRESSION,
callee: RENDER_SLOT,
arguments: [
`$slots`,
`"default"`,
`{}`,
{
type: NodeTypes.JS_FUNCTION_EXPRESSION,
params: [],
returns: [
{
type: NodeTypes.ELEMENT,
tag: `div`
}
]
}
]
})
})
test('named slot outlet with fallback', () => {
const ast = parseWithSlots(`<slot name="foo"><div/></slot>`)
expect((ast.children[0] as ElementNode).codegenNode).toMatchObject({
type: NodeTypes.JS_CALL_EXPRESSION,
callee: RENDER_SLOT,
arguments: [
`$slots`,
`"foo"`,
`{}`,
{
type: NodeTypes.JS_FUNCTION_EXPRESSION,
params: [],
returns: [
{
type: NodeTypes.ELEMENT,
tag: `div`
}
]
}
]
})
})
test('default slot outlet with props & fallback', () => {
const ast = parseWithSlots(`<slot :foo="bar"><div/></slot>`)
expect((ast.children[0] as ElementNode).codegenNode).toMatchObject({
type: NodeTypes.JS_CALL_EXPRESSION,
callee: RENDER_SLOT,
arguments: [
`$slots`,
`"default"`,
{
type: NodeTypes.JS_OBJECT_EXPRESSION,
properties: [
{
key: {
content: `foo`,
isStatic: true
},
value: {
content: `bar`,
isStatic: false
}
}
]
},
{
type: NodeTypes.JS_FUNCTION_EXPRESSION,
params: [],
returns: [
{
type: NodeTypes.ELEMENT,
tag: `div`
}
]
}
]
})
})
test('named slot outlet with props & fallback', () => {
const ast = parseWithSlots(`<slot name="foo" :foo="bar"><div/></slot>`)
expect((ast.children[0] as ElementNode).codegenNode).toMatchObject({
type: NodeTypes.JS_CALL_EXPRESSION,
callee: RENDER_SLOT,
arguments: [
`$slots`,
`"foo"`,
{
type: NodeTypes.JS_OBJECT_EXPRESSION,
properties: [
{
key: {
content: `foo`,
isStatic: true
},
value: {
content: `bar`,
isStatic: false
}
}
]
},
{
type: NodeTypes.JS_FUNCTION_EXPRESSION,
params: [],
returns: [
{
type: NodeTypes.ELEMENT,
tag: `div`
}
]
}
]
})
})
test('slot with slotted: false', async () => {
const ast = parseWithSlots(`<slot/>`, { slotted: false, scopeId: 'foo' })
expect((ast.children[0] as ElementNode).codegenNode).toMatchObject({
type: NodeTypes.JS_CALL_EXPRESSION,
callee: RENDER_SLOT,
arguments: [`$slots`, `"default"`, `{}`, `undefined`, `true`]
})
})
test(`error on unexpected custom directive on <slot>`, () => {
const onError = jest.fn()
const source = `<slot v-foo />`
parseWithSlots(source, { onError })
const index = source.indexOf('v-foo')
expect(onError.mock.calls[0][0]).toMatchObject({
code: ErrorCodes.X_V_SLOT_UNEXPECTED_DIRECTIVE_ON_SLOT_OUTLET,
loc: {
source: `v-foo`,
start: {
offset: index,
line: 1,
column: index + 1
},
end: {
offset: index + 5,
line: 1,
column: index + 6
}
}
})
})
})
| packages/compiler-core/__tests__/transforms/transformSlotOutlet.spec.ts | 0 | https://github.com/vuejs/core/commit/7c4e4514d166b2fcb055baa091a79d9244458ab5 | [
0.0001882122305687517,
0.00017011749150697142,
0.00016706198221072555,
0.00016921338101383299,
0.000003512231614877237
] |
{
"id": 0,
"code_window": [
" expect(doubled).toBe(undefined)\n",
" })\n",
"\n",
" it('should fire onDispose hook', () => {\n",
" let dummy = 0\n",
"\n",
" const scope = new EffectScope()\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" it('should fire onScopeDispose hook', () => {\n"
],
"file_path": "packages/reactivity/__tests__/effectScope.spec.ts",
"type": "replace",
"edit_start_line_idx": 175
} | import {
baseParse as parse,
NodeTypes,
ElementNode,
TextNode,
ErrorCodes,
ElementTypes,
InterpolationNode,
AttributeNode,
ConstantTypes
} from '@vue/compiler-core'
import { parserOptions, DOMNamespaces } from '../src/parserOptions'
describe('DOM parser', () => {
describe('Text', () => {
test('textarea handles comments/elements as just text', () => {
const ast = parse(
'<textarea>some<div>text</div>and<!--comment--></textarea>',
parserOptions
)
const element = ast.children[0] as ElementNode
const text = element.children[0] as TextNode
expect(text).toStrictEqual({
type: NodeTypes.TEXT,
content: 'some<div>text</div>and<!--comment-->',
loc: {
start: { offset: 10, line: 1, column: 11 },
end: { offset: 46, line: 1, column: 47 },
source: 'some<div>text</div>and<!--comment-->'
}
})
})
test('textarea handles character references', () => {
const ast = parse('<textarea>&</textarea>', parserOptions)
const element = ast.children[0] as ElementNode
const text = element.children[0] as TextNode
expect(text).toStrictEqual({
type: NodeTypes.TEXT,
content: '&',
loc: {
start: { offset: 10, line: 1, column: 11 },
end: { offset: 15, line: 1, column: 16 },
source: '&'
}
})
})
test('textarea support interpolation', () => {
const ast = parse('<textarea><div>{{ foo }}</textarea>', parserOptions)
const element = ast.children[0] as ElementNode
expect(element.children).toMatchObject([
{ type: NodeTypes.TEXT, content: `<div>` },
{
type: NodeTypes.INTERPOLATION,
content: {
type: NodeTypes.SIMPLE_EXPRESSION,
content: `foo`,
isStatic: false
}
}
])
})
test('style handles comments/elements as just a text', () => {
const ast = parse(
'<style>some<div>text</div>and<!--comment--></style>',
parserOptions
)
const element = ast.children[0] as ElementNode
const text = element.children[0] as TextNode
expect(text).toStrictEqual({
type: NodeTypes.TEXT,
content: 'some<div>text</div>and<!--comment-->',
loc: {
start: { offset: 7, line: 1, column: 8 },
end: { offset: 43, line: 1, column: 44 },
source: 'some<div>text</div>and<!--comment-->'
}
})
})
test("style doesn't handle character references", () => {
const ast = parse('<style>&</style>', parserOptions)
const element = ast.children[0] as ElementNode
const text = element.children[0] as TextNode
expect(text).toStrictEqual({
type: NodeTypes.TEXT,
content: '&',
loc: {
start: { offset: 7, line: 1, column: 8 },
end: { offset: 12, line: 1, column: 13 },
source: '&'
}
})
})
test('CDATA', () => {
const ast = parse('<svg><![CDATA[some text]]></svg>', parserOptions)
const text = (ast.children[0] as ElementNode).children![0] as TextNode
expect(text).toStrictEqual({
type: NodeTypes.TEXT,
content: 'some text',
loc: {
start: { offset: 14, line: 1, column: 15 },
end: { offset: 23, line: 1, column: 24 },
source: 'some text'
}
})
})
test('<pre> tag should preserve raw whitespace', () => {
const rawText = ` \na <div>foo \n bar</div> \n c`
const ast = parse(`<pre>${rawText}</pre>`, parserOptions)
expect((ast.children[0] as ElementNode).children).toMatchObject([
{
type: NodeTypes.TEXT,
content: ` \na `
},
{
type: NodeTypes.ELEMENT,
children: [
{
type: NodeTypes.TEXT,
content: `foo \n bar`
}
]
},
{
type: NodeTypes.TEXT,
content: ` \n c`
}
])
})
// #908
test('<pre> tag should remove leading newline', () => {
const rawText = `\nhello<div>\nbye</div>`
const ast = parse(`<pre>${rawText}</pre>`, parserOptions)
expect((ast.children[0] as ElementNode).children).toMatchObject([
{
type: NodeTypes.TEXT,
content: `hello`
},
{
type: NodeTypes.ELEMENT,
children: [
{
type: NodeTypes.TEXT,
// should not remove the leading newline for nested elements
content: `\nbye`
}
]
}
])
})
// #945
test(' should not be condensed', () => {
const nbsp = String.fromCharCode(160)
const ast = parse(`foo bar`, parserOptions)
expect(ast.children[0]).toMatchObject({
type: NodeTypes.TEXT,
content: `foo${nbsp}${nbsp}bar`
})
})
// https://html.spec.whatwg.org/multipage/parsing.html#named-character-reference-state
test('HTML entities compatibility in text', () => {
const ast = parse('&ersand;', parserOptions)
const text = ast.children[0] as TextNode
expect(text).toStrictEqual({
type: NodeTypes.TEXT,
content: '&ersand;',
loc: {
start: { offset: 0, line: 1, column: 1 },
end: { offset: 11, line: 1, column: 12 },
source: '&ersand;'
}
})
})
// https://html.spec.whatwg.org/multipage/parsing.html#named-character-reference-state
test('HTML entities compatibility in attribute', () => {
const ast = parse(
'<div a="&ersand;" b="&ersand;" c="&!"></div>',
parserOptions
)
const element = ast.children[0] as ElementNode
const text1 = (element.props[0] as AttributeNode).value
const text2 = (element.props[1] as AttributeNode).value
const text3 = (element.props[2] as AttributeNode).value
expect(text1).toStrictEqual({
type: NodeTypes.TEXT,
content: '&ersand;',
loc: {
start: { offset: 7, line: 1, column: 8 },
end: { offset: 20, line: 1, column: 21 },
source: '"&ersand;"'
}
})
expect(text2).toStrictEqual({
type: NodeTypes.TEXT,
content: '&ersand;',
loc: {
start: { offset: 23, line: 1, column: 24 },
end: { offset: 37, line: 1, column: 38 },
source: '"&ersand;"'
}
})
expect(text3).toStrictEqual({
type: NodeTypes.TEXT,
content: '&!',
loc: {
start: { offset: 40, line: 1, column: 41 },
end: { offset: 47, line: 1, column: 48 },
source: '"&!"'
}
})
})
test('Some control character reference should be replaced.', () => {
const ast = parse('†', parserOptions)
const text = ast.children[0] as TextNode
expect(text).toStrictEqual({
type: NodeTypes.TEXT,
content: '†',
loc: {
start: { offset: 0, line: 1, column: 1 },
end: { offset: 6, line: 1, column: 7 },
source: '†'
}
})
})
})
describe('Interpolation', () => {
test('HTML entities in interpolation should be translated for backward compatibility.', () => {
const ast = parse('<div>{{ a < b }}</div>', parserOptions)
const element = ast.children[0] as ElementNode
const interpolation = element.children[0] as InterpolationNode
expect(interpolation).toStrictEqual({
type: NodeTypes.INTERPOLATION,
content: {
type: NodeTypes.SIMPLE_EXPRESSION,
content: `a < b`,
isStatic: false,
constType: ConstantTypes.NOT_CONSTANT,
loc: {
start: { offset: 8, line: 1, column: 9 },
end: { offset: 16, line: 1, column: 17 },
source: 'a < b'
}
},
loc: {
start: { offset: 5, line: 1, column: 6 },
end: { offset: 19, line: 1, column: 20 },
source: '{{ a < b }}'
}
})
})
})
describe('Element', () => {
test('void element', () => {
const ast = parse('<img>after', parserOptions)
const element = ast.children[0] as ElementNode
expect(element).toStrictEqual({
type: NodeTypes.ELEMENT,
ns: DOMNamespaces.HTML,
tag: 'img',
tagType: ElementTypes.ELEMENT,
props: [],
isSelfClosing: false,
children: [],
loc: {
start: { offset: 0, line: 1, column: 1 },
end: { offset: 5, line: 1, column: 6 },
source: '<img>'
},
codegenNode: undefined
})
})
test('native element', () => {
const ast = parse('<div></div><comp></comp><Comp></Comp>', parserOptions)
expect(ast.children[0]).toMatchObject({
type: NodeTypes.ELEMENT,
tag: 'div',
tagType: ElementTypes.ELEMENT
})
expect(ast.children[1]).toMatchObject({
type: NodeTypes.ELEMENT,
tag: 'comp',
tagType: ElementTypes.COMPONENT
})
expect(ast.children[2]).toMatchObject({
type: NodeTypes.ELEMENT,
tag: 'Comp',
tagType: ElementTypes.COMPONENT
})
})
test('Strict end tag detection for textarea.', () => {
const ast = parse(
'<textarea>hello</textarea</textarea0></texTArea a="<>">',
{
...parserOptions,
onError: err => {
if (err.code !== ErrorCodes.END_TAG_WITH_ATTRIBUTES) {
throw err
}
}
}
)
const element = ast.children[0] as ElementNode
const text = element.children[0] as TextNode
expect(ast.children.length).toBe(1)
expect(text).toStrictEqual({
type: NodeTypes.TEXT,
content: 'hello</textarea</textarea0>',
loc: {
start: { offset: 10, line: 1, column: 11 },
end: { offset: 37, line: 1, column: 38 },
source: 'hello</textarea</textarea0>'
}
})
})
})
describe('Namespaces', () => {
test('HTML namespace', () => {
const ast = parse('<html>test</html>', parserOptions)
const element = ast.children[0] as ElementNode
expect(element.ns).toBe(DOMNamespaces.HTML)
})
test('SVG namespace', () => {
const ast = parse('<svg>test</svg>', parserOptions)
const element = ast.children[0] as ElementNode
expect(element.ns).toBe(DOMNamespaces.SVG)
})
test('MATH_ML namespace', () => {
const ast = parse('<math>test</math>', parserOptions)
const element = ast.children[0] as ElementNode
expect(element.ns).toBe(DOMNamespaces.MATH_ML)
})
test('SVG in MATH_ML namespace', () => {
const ast = parse(
'<math><annotation-xml><svg></svg></annotation-xml></math>',
parserOptions
)
const elementMath = ast.children[0] as ElementNode
const elementAnnotation = elementMath.children[0] as ElementNode
const elementSvg = elementAnnotation.children[0] as ElementNode
expect(elementMath.ns).toBe(DOMNamespaces.MATH_ML)
expect(elementSvg.ns).toBe(DOMNamespaces.SVG)
})
test('html text/html in MATH_ML namespace', () => {
const ast = parse(
'<math><annotation-xml encoding="text/html"><test/></annotation-xml></math>',
parserOptions
)
const elementMath = ast.children[0] as ElementNode
const elementAnnotation = elementMath.children[0] as ElementNode
const element = elementAnnotation.children[0] as ElementNode
expect(elementMath.ns).toBe(DOMNamespaces.MATH_ML)
expect(element.ns).toBe(DOMNamespaces.HTML)
})
test('html application/xhtml+xml in MATH_ML namespace', () => {
const ast = parse(
'<math><annotation-xml encoding="application/xhtml+xml"><test/></annotation-xml></math>',
parserOptions
)
const elementMath = ast.children[0] as ElementNode
const elementAnnotation = elementMath.children[0] as ElementNode
const element = elementAnnotation.children[0] as ElementNode
expect(elementMath.ns).toBe(DOMNamespaces.MATH_ML)
expect(element.ns).toBe(DOMNamespaces.HTML)
})
test('mtext malignmark in MATH_ML namespace', () => {
const ast = parse(
'<math><mtext><malignmark/></mtext></math>',
parserOptions
)
const elementMath = ast.children[0] as ElementNode
const elementText = elementMath.children[0] as ElementNode
const element = elementText.children[0] as ElementNode
expect(elementMath.ns).toBe(DOMNamespaces.MATH_ML)
expect(element.ns).toBe(DOMNamespaces.MATH_ML)
})
test('mtext and not malignmark tag in MATH_ML namespace', () => {
const ast = parse('<math><mtext><test/></mtext></math>', parserOptions)
const elementMath = ast.children[0] as ElementNode
const elementText = elementMath.children[0] as ElementNode
const element = elementText.children[0] as ElementNode
expect(elementMath.ns).toBe(DOMNamespaces.MATH_ML)
expect(element.ns).toBe(DOMNamespaces.HTML)
})
test('foreignObject tag in SVG namespace', () => {
const ast = parse(
'<svg><foreignObject><test/></foreignObject></svg>',
parserOptions
)
const elementSvg = ast.children[0] as ElementNode
const elementForeignObject = elementSvg.children[0] as ElementNode
const element = elementForeignObject.children[0] as ElementNode
expect(elementSvg.ns).toBe(DOMNamespaces.SVG)
expect(element.ns).toBe(DOMNamespaces.HTML)
})
test('desc tag in SVG namespace', () => {
const ast = parse('<svg><desc><test/></desc></svg>', parserOptions)
const elementSvg = ast.children[0] as ElementNode
const elementDesc = elementSvg.children[0] as ElementNode
const element = elementDesc.children[0] as ElementNode
expect(elementSvg.ns).toBe(DOMNamespaces.SVG)
expect(element.ns).toBe(DOMNamespaces.HTML)
})
test('title tag in SVG namespace', () => {
const ast = parse('<svg><title><test/></title></svg>', parserOptions)
const elementSvg = ast.children[0] as ElementNode
const elementTitle = elementSvg.children[0] as ElementNode
const element = elementTitle.children[0] as ElementNode
expect(elementSvg.ns).toBe(DOMNamespaces.SVG)
expect(element.ns).toBe(DOMNamespaces.HTML)
})
test('SVG in HTML namespace', () => {
const ast = parse('<html><svg></svg></html>', parserOptions)
const elementHtml = ast.children[0] as ElementNode
const element = elementHtml.children[0] as ElementNode
expect(elementHtml.ns).toBe(DOMNamespaces.HTML)
expect(element.ns).toBe(DOMNamespaces.SVG)
})
test('MATH in HTML namespace', () => {
const ast = parse('<html><math></math></html>', parserOptions)
const elementHtml = ast.children[0] as ElementNode
const element = elementHtml.children[0] as ElementNode
expect(elementHtml.ns).toBe(DOMNamespaces.HTML)
expect(element.ns).toBe(DOMNamespaces.MATH_ML)
})
})
})
| packages/compiler-dom/__tests__/parse.spec.ts | 0 | https://github.com/vuejs/core/commit/7c4e4514d166b2fcb055baa091a79d9244458ab5 | [
0.0001764652697602287,
0.0001717977283988148,
0.0001668609183980152,
0.0001717119594104588,
0.0000022503684249386424
] |
{
"id": 1,
"code_window": [
" expect(dummy).toBe(7)\n",
" })\n",
"\n",
" it('should warn onDispose() is called when there is no active effect scope', () => {\n",
" const spy = jest.fn()\n",
" const scope = new EffectScope()\n",
" scope.run(() => {\n",
" onScopeDispose(spy)\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" it('should warn onScopeDispose() is called when there is no active effect scope', () => {\n"
],
"file_path": "packages/reactivity/__tests__/effectScope.spec.ts",
"type": "replace",
"edit_start_line_idx": 194
} | import { nextTick, watch, watchEffect } from '@vue/runtime-core'
import {
reactive,
effect,
EffectScope,
onScopeDispose,
computed,
ref,
ComputedRef
} from '../src'
describe('reactivity/effect/scope', () => {
it('should run', () => {
const fnSpy = jest.fn(() => {})
new EffectScope().run(fnSpy)
expect(fnSpy).toHaveBeenCalledTimes(1)
})
it('should accept zero argument', () => {
const scope = new EffectScope()
expect(scope.effects.length).toBe(0)
})
it('should return run value', () => {
expect(new EffectScope().run(() => 1)).toBe(1)
})
it('should collect the effects', () => {
const scope = new EffectScope()
scope.run(() => {
let dummy
const counter = reactive({ num: 0 })
effect(() => (dummy = counter.num))
expect(dummy).toBe(0)
counter.num = 7
expect(dummy).toBe(7)
})
expect(scope.effects.length).toBe(1)
})
it('stop', () => {
let dummy, doubled
const counter = reactive({ num: 0 })
const scope = new EffectScope()
scope.run(() => {
effect(() => (dummy = counter.num))
effect(() => (doubled = counter.num * 2))
})
expect(scope.effects.length).toBe(2)
expect(dummy).toBe(0)
counter.num = 7
expect(dummy).toBe(7)
expect(doubled).toBe(14)
scope.stop()
counter.num = 6
expect(dummy).toBe(7)
expect(doubled).toBe(14)
})
it('should collect nested scope', () => {
let dummy, doubled
const counter = reactive({ num: 0 })
const scope = new EffectScope()
scope.run(() => {
effect(() => (dummy = counter.num))
// nested scope
new EffectScope().run(() => {
effect(() => (doubled = counter.num * 2))
})
})
expect(scope.effects.length).toBe(1)
expect(scope.scopes!.length).toBe(1)
expect(scope.scopes![0]).toBeInstanceOf(EffectScope)
expect(dummy).toBe(0)
counter.num = 7
expect(dummy).toBe(7)
expect(doubled).toBe(14)
// stop the nested scope as well
scope.stop()
counter.num = 6
expect(dummy).toBe(7)
expect(doubled).toBe(14)
})
it('nested scope can be escaped', () => {
let dummy, doubled
const counter = reactive({ num: 0 })
const scope = new EffectScope()
scope.run(() => {
effect(() => (dummy = counter.num))
// nested scope
new EffectScope(true).run(() => {
effect(() => (doubled = counter.num * 2))
})
})
expect(scope.effects.length).toBe(1)
expect(dummy).toBe(0)
counter.num = 7
expect(dummy).toBe(7)
expect(doubled).toBe(14)
scope.stop()
counter.num = 6
expect(dummy).toBe(7)
// nested scope should not be stoped
expect(doubled).toBe(12)
})
it('able to run the scope', () => {
let dummy, doubled
const counter = reactive({ num: 0 })
const scope = new EffectScope()
scope.run(() => {
effect(() => (dummy = counter.num))
})
expect(scope.effects.length).toBe(1)
scope.run(() => {
effect(() => (doubled = counter.num * 2))
})
expect(scope.effects.length).toBe(2)
counter.num = 7
expect(dummy).toBe(7)
expect(doubled).toBe(14)
scope.stop()
})
it('can not run an inactive scope', () => {
let dummy, doubled
const counter = reactive({ num: 0 })
const scope = new EffectScope()
scope.run(() => {
effect(() => (dummy = counter.num))
})
expect(scope.effects.length).toBe(1)
scope.stop()
scope.run(() => {
effect(() => (doubled = counter.num * 2))
})
expect('[Vue warn] cannot run an inactive effect scope.').toHaveBeenWarned()
expect(scope.effects.length).toBe(1)
counter.num = 7
expect(dummy).toBe(0)
expect(doubled).toBe(undefined)
})
it('should fire onDispose hook', () => {
let dummy = 0
const scope = new EffectScope()
scope.run(() => {
onScopeDispose(() => (dummy += 1))
onScopeDispose(() => (dummy += 2))
})
scope.run(() => {
onScopeDispose(() => (dummy += 4))
})
expect(dummy).toBe(0)
scope.stop()
expect(dummy).toBe(7)
})
it('should warn onDispose() is called when there is no active effect scope', () => {
const spy = jest.fn()
const scope = new EffectScope()
scope.run(() => {
onScopeDispose(spy)
})
expect(spy).toHaveBeenCalledTimes(0)
onScopeDispose(spy)
expect(
'[Vue warn] onDispose() is called when there is no active effect scope to be associated with.'
).toHaveBeenWarned()
scope.stop()
expect(spy).toHaveBeenCalledTimes(1)
})
it('should derefence child scope from parent scope after stopping child scope (no memleaks)', async () => {
const parent = new EffectScope()
const child = parent.run(() => new EffectScope())!
expect(parent.scopes!.includes(child)).toBe(true)
child.stop()
expect(parent.scopes!.includes(child)).toBe(false)
})
it('test with higher level APIs', async () => {
const r = ref(1)
const computedSpy = jest.fn()
const watchSpy = jest.fn()
const watchEffectSpy = jest.fn()
let c: ComputedRef
const scope = new EffectScope()
scope.run(() => {
c = computed(() => {
computedSpy()
return r.value + 1
})
watch(r, watchSpy)
watchEffect(() => {
watchEffectSpy()
r.value
})
})
c!.value // computed is lazy so trigger collection
expect(computedSpy).toHaveBeenCalledTimes(1)
expect(watchSpy).toHaveBeenCalledTimes(0)
expect(watchEffectSpy).toHaveBeenCalledTimes(1)
r.value++
c!.value
await nextTick()
expect(computedSpy).toHaveBeenCalledTimes(2)
expect(watchSpy).toHaveBeenCalledTimes(1)
expect(watchEffectSpy).toHaveBeenCalledTimes(2)
scope.stop()
r.value++
c!.value
await nextTick()
// should not trigger anymore
expect(computedSpy).toHaveBeenCalledTimes(2)
expect(watchSpy).toHaveBeenCalledTimes(1)
expect(watchEffectSpy).toHaveBeenCalledTimes(2)
})
})
| packages/reactivity/__tests__/effectScope.spec.ts | 1 | https://github.com/vuejs/core/commit/7c4e4514d166b2fcb055baa091a79d9244458ab5 | [
0.9989392161369324,
0.5698105692863464,
0.00016734912060201168,
0.9616726636886597,
0.47079360485076904
] |
{
"id": 1,
"code_window": [
" expect(dummy).toBe(7)\n",
" })\n",
"\n",
" it('should warn onDispose() is called when there is no active effect scope', () => {\n",
" const spy = jest.fn()\n",
" const scope = new EffectScope()\n",
" scope.run(() => {\n",
" onScopeDispose(spy)\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" it('should warn onScopeDispose() is called when there is no active effect scope', () => {\n"
],
"file_path": "packages/reactivity/__tests__/effectScope.spec.ts",
"type": "replace",
"edit_start_line_idx": 194
} | const fs = require('fs')
const chalk = require('chalk')
const targets = (exports.targets = fs.readdirSync('packages').filter(f => {
if (!fs.statSync(`packages/${f}`).isDirectory()) {
return false
}
const pkg = require(`../packages/${f}/package.json`)
if (pkg.private && !pkg.buildOptions) {
return false
}
return true
}))
exports.fuzzyMatchTarget = (partialTargets, includeAllMatching) => {
const matched = []
partialTargets.forEach(partialTarget => {
for (const target of targets) {
if (target.match(partialTarget)) {
matched.push(target)
if (!includeAllMatching) {
break
}
}
}
})
if (matched.length) {
return matched
} else {
console.log()
console.error(
` ${chalk.bgRed.white(' ERROR ')} ${chalk.red(
`Target ${chalk.underline(partialTargets)} not found!`
)}`
)
console.log()
process.exit(1)
}
}
| scripts/utils.js | 0 | https://github.com/vuejs/core/commit/7c4e4514d166b2fcb055baa091a79d9244458ab5 | [
0.00017788162222132087,
0.00017577208927832544,
0.0001733248500386253,
0.00017559214029461145,
0.00000180360916601785
] |
{
"id": 1,
"code_window": [
" expect(dummy).toBe(7)\n",
" })\n",
"\n",
" it('should warn onDispose() is called when there is no active effect scope', () => {\n",
" const spy = jest.fn()\n",
" const scope = new EffectScope()\n",
" scope.run(() => {\n",
" onScopeDispose(spy)\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" it('should warn onScopeDispose() is called when there is no active effect scope', () => {\n"
],
"file_path": "packages/reactivity/__tests__/effectScope.spec.ts",
"type": "replace",
"edit_start_line_idx": 194
} | import {
includeBooleanAttr,
isSpecialBooleanAttr,
makeMap,
NOOP
} from '@vue/shared'
import {
compatUtils,
ComponentInternalInstance,
DeprecationTypes
} from '@vue/runtime-core'
export const xlinkNS = 'http://www.w3.org/1999/xlink'
export function patchAttr(
el: Element,
key: string,
value: any,
isSVG: boolean,
instance?: ComponentInternalInstance | null
) {
if (isSVG && key.startsWith('xlink:')) {
if (value == null) {
el.removeAttributeNS(xlinkNS, key.slice(6, key.length))
} else {
el.setAttributeNS(xlinkNS, key, value)
}
} else {
if (__COMPAT__ && compatCoerceAttr(el, key, value, instance)) {
return
}
// note we are only checking boolean attributes that don't have a
// corresponding dom prop of the same name here.
const isBoolean = isSpecialBooleanAttr(key)
if (value == null || (isBoolean && !includeBooleanAttr(value))) {
el.removeAttribute(key)
} else {
el.setAttribute(key, isBoolean ? '' : value)
}
}
}
// 2.x compat
const isEnumeratedAttr = __COMPAT__
? /*#__PURE__*/ makeMap('contenteditable,draggable,spellcheck')
: NOOP
export function compatCoerceAttr(
el: Element,
key: string,
value: unknown,
instance: ComponentInternalInstance | null = null
): boolean {
if (isEnumeratedAttr(key)) {
const v2CocercedValue =
value === null
? 'false'
: typeof value !== 'boolean' && value !== undefined
? 'true'
: null
if (
v2CocercedValue &&
compatUtils.softAssertCompatEnabled(
DeprecationTypes.ATTR_ENUMERATED_COERCION,
instance,
key,
value,
v2CocercedValue
)
) {
el.setAttribute(key, v2CocercedValue)
return true
}
} else if (
value === false &&
!isSpecialBooleanAttr(key) &&
compatUtils.softAssertCompatEnabled(
DeprecationTypes.ATTR_FALSE_VALUE,
instance,
key
)
) {
el.removeAttribute(key)
return true
}
return false
}
| packages/runtime-dom/src/modules/attrs.ts | 0 | https://github.com/vuejs/core/commit/7c4e4514d166b2fcb055baa091a79d9244458ab5 | [
0.00017853292229119688,
0.00017535292136017233,
0.00016842341574374586,
0.00017629809735808522,
0.00000303060733131133
] |
{
"id": 1,
"code_window": [
" expect(dummy).toBe(7)\n",
" })\n",
"\n",
" it('should warn onDispose() is called when there is no active effect scope', () => {\n",
" const spy = jest.fn()\n",
" const scope = new EffectScope()\n",
" scope.run(() => {\n",
" onScopeDispose(spy)\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" it('should warn onScopeDispose() is called when there is no active effect scope', () => {\n"
],
"file_path": "packages/reactivity/__tests__/effectScope.spec.ts",
"type": "replace",
"edit_start_line_idx": 194
} | // - Parse expressions in templates into compound expressions so that each
// identifier gets more accurate source-map locations.
//
// - Prefix identifiers with `_ctx.` or `$xxx` (for known binding types) so that
// they are accessed from the right source
//
// - This transform is only applied in non-browser builds because it relies on
// an additional JavaScript parser. In the browser, there is no source-map
// support and the code is wrapped in `with (this) { ... }`.
import { NodeTransform, TransformContext } from '../transform'
import {
NodeTypes,
createSimpleExpression,
ExpressionNode,
SimpleExpressionNode,
CompoundExpressionNode,
createCompoundExpression,
ConstantTypes
} from '../ast'
import { advancePositionWithClone, isSimpleIdentifier } from '../utils'
import {
isGloballyWhitelisted,
makeMap,
babelParserDefaultPlugins,
hasOwn,
isString
} from '@vue/shared'
import { createCompilerError, ErrorCodes } from '../errors'
import {
Node,
Function,
Identifier,
ObjectProperty,
AssignmentExpression,
UpdateExpression
} from '@babel/types'
import { validateBrowserExpression } from '../validateExpression'
import { parse } from '@babel/parser'
import { walk } from 'estree-walker'
import { IS_REF, UNREF } from '../runtimeHelpers'
import { BindingTypes } from '../options'
const isLiteralWhitelisted = /*#__PURE__*/ makeMap('true,false,null,this')
export const transformExpression: NodeTransform = (node, context) => {
if (node.type === NodeTypes.INTERPOLATION) {
node.content = processExpression(
node.content as SimpleExpressionNode,
context
)
} else if (node.type === NodeTypes.ELEMENT) {
// handle directives on element
for (let i = 0; i < node.props.length; i++) {
const dir = node.props[i]
// do not process for v-on & v-for since they are special handled
if (dir.type === NodeTypes.DIRECTIVE && dir.name !== 'for') {
const exp = dir.exp
const arg = dir.arg
// do not process exp if this is v-on:arg - we need special handling
// for wrapping inline statements.
if (
exp &&
exp.type === NodeTypes.SIMPLE_EXPRESSION &&
!(dir.name === 'on' && arg)
) {
dir.exp = processExpression(
exp,
context,
// slot args must be processed as function params
dir.name === 'slot'
)
}
if (arg && arg.type === NodeTypes.SIMPLE_EXPRESSION && !arg.isStatic) {
dir.arg = processExpression(arg, context)
}
}
}
}
}
interface PrefixMeta {
prefix?: string
isConstant: boolean
start: number
end: number
scopeIds?: Set<string>
}
// Important: since this function uses Node.js only dependencies, it should
// always be used with a leading !__BROWSER__ check so that it can be
// tree-shaken from the browser build.
export function processExpression(
node: SimpleExpressionNode,
context: TransformContext,
// some expressions like v-slot props & v-for aliases should be parsed as
// function params
asParams = false,
// v-on handler values may contain multiple statements
asRawStatements = false
): ExpressionNode {
if (__BROWSER__) {
if (__DEV__) {
// simple in-browser validation (same logic in 2.x)
validateBrowserExpression(node, context, asParams, asRawStatements)
}
return node
}
if (!context.prefixIdentifiers || !node.content.trim()) {
return node
}
const { inline, bindingMetadata } = context
const rewriteIdentifier = (raw: string, parent?: Node, id?: Identifier) => {
const type = hasOwn(bindingMetadata, raw) && bindingMetadata[raw]
if (inline) {
// x = y
const isAssignmentLVal =
parent && parent.type === 'AssignmentExpression' && parent.left === id
// x++
const isUpdateArg =
parent && parent.type === 'UpdateExpression' && parent.argument === id
// ({ x } = y)
const isDestructureAssignment =
parent && isInDestructureAssignment(parent, parentStack)
if (type === BindingTypes.SETUP_CONST) {
return raw
} else if (type === BindingTypes.SETUP_REF) {
return `${raw}.value`
} else if (type === BindingTypes.SETUP_MAYBE_REF) {
// const binding that may or may not be ref
// if it's not a ref, then assignments don't make sense -
// so we ignore the non-ref assignment case and generate code
// that assumes the value to be a ref for more efficiency
return isAssignmentLVal || isUpdateArg || isDestructureAssignment
? `${raw}.value`
: `${context.helperString(UNREF)}(${raw})`
} else if (type === BindingTypes.SETUP_LET) {
if (isAssignmentLVal) {
// let binding.
// this is a bit more tricky as we need to cover the case where
// let is a local non-ref value, and we need to replicate the
// right hand side value.
// x = y --> isRef(x) ? x.value = y : x = y
const { right: rVal, operator } = parent as AssignmentExpression
const rExp = rawExp.slice(rVal.start! - 1, rVal.end! - 1)
const rExpString = stringifyExpression(
processExpression(createSimpleExpression(rExp, false), context)
)
return `${context.helperString(IS_REF)}(${raw})${
context.isTS ? ` //@ts-ignore\n` : ``
} ? ${raw}.value ${operator} ${rExpString} : ${raw}`
} else if (isUpdateArg) {
// make id replace parent in the code range so the raw update operator
// is removed
id!.start = parent!.start
id!.end = parent!.end
const { prefix: isPrefix, operator } = parent as UpdateExpression
const prefix = isPrefix ? operator : ``
const postfix = isPrefix ? `` : operator
// let binding.
// x++ --> isRef(a) ? a.value++ : a++
return `${context.helperString(IS_REF)}(${raw})${
context.isTS ? ` //@ts-ignore\n` : ``
} ? ${prefix}${raw}.value${postfix} : ${prefix}${raw}${postfix}`
} else if (isDestructureAssignment) {
// TODO
// let binding in a destructure assignment - it's very tricky to
// handle both possible cases here without altering the original
// structure of the code, so we just assume it's not a ref here
// for now
return raw
} else {
return `${context.helperString(UNREF)}(${raw})`
}
} else if (type === BindingTypes.PROPS) {
// use __props which is generated by compileScript so in ts mode
// it gets correct type
return `__props.${raw}`
}
} else {
if (type && type.startsWith('setup')) {
// setup bindings in non-inline mode
return `$setup.${raw}`
} else if (type) {
return `$${type}.${raw}`
}
}
// fallback to ctx
return `_ctx.${raw}`
}
// fast path if expression is a simple identifier.
const rawExp = node.content
// bail constant on parens (function invocation) and dot (member access)
const bailConstant = rawExp.indexOf(`(`) > -1 || rawExp.indexOf('.') > 0
if (isSimpleIdentifier(rawExp)) {
const isScopeVarReference = context.identifiers[rawExp]
const isAllowedGlobal = isGloballyWhitelisted(rawExp)
const isLiteral = isLiteralWhitelisted(rawExp)
if (!asParams && !isScopeVarReference && !isAllowedGlobal && !isLiteral) {
// const bindings exposed from setup can be skipped for patching but
// cannot be hoisted to module scope
if (bindingMetadata[node.content] === BindingTypes.SETUP_CONST) {
node.constType = ConstantTypes.CAN_SKIP_PATCH
}
node.content = rewriteIdentifier(rawExp)
} else if (!isScopeVarReference) {
if (isLiteral) {
node.constType = ConstantTypes.CAN_STRINGIFY
} else {
node.constType = ConstantTypes.CAN_HOIST
}
}
return node
}
let ast: any
// exp needs to be parsed differently:
// 1. Multiple inline statements (v-on, with presence of `;`): parse as raw
// exp, but make sure to pad with spaces for consistent ranges
// 2. Expressions: wrap with parens (for e.g. object expressions)
// 3. Function arguments (v-for, v-slot): place in a function argument position
const source = asRawStatements
? ` ${rawExp} `
: `(${rawExp})${asParams ? `=>{}` : ``}`
try {
ast = parse(source, {
plugins: [...context.expressionPlugins, ...babelParserDefaultPlugins]
}).program
} catch (e) {
context.onError(
createCompilerError(
ErrorCodes.X_INVALID_EXPRESSION,
node.loc,
undefined,
e.message
)
)
return node
}
const ids: (Identifier & PrefixMeta)[] = []
const knownIds = Object.create(context.identifiers)
const isDuplicate = (node: Node & PrefixMeta): boolean =>
ids.some(id => id.start === node.start)
const parentStack: Node[] = []
// walk the AST and look for identifiers that need to be prefixed.
;(walk as any)(ast, {
enter(node: Node & PrefixMeta, parent: Node | undefined) {
parent && parentStack.push(parent)
if (node.type === 'Identifier') {
if (!isDuplicate(node)) {
// v2 wrapped filter call
if (__COMPAT__ && node.name.startsWith('_filter_')) {
return
}
const needPrefix = shouldPrefix(node, parent!, parentStack)
if (!knownIds[node.name] && needPrefix) {
if (isStaticProperty(parent!) && parent.shorthand) {
// property shorthand like { foo }, we need to add the key since
// we rewrite the value
node.prefix = `${node.name}: `
}
node.name = rewriteIdentifier(node.name, parent, node)
ids.push(node)
} else if (!isStaticPropertyKey(node, parent!)) {
// The identifier is considered constant unless it's pointing to a
// scope variable (a v-for alias, or a v-slot prop)
if (!(needPrefix && knownIds[node.name]) && !bailConstant) {
node.isConstant = true
}
// also generate sub-expressions for other identifiers for better
// source map support. (except for property keys which are static)
ids.push(node)
}
}
} else if (isFunction(node)) {
// walk function expressions and add its arguments to known identifiers
// so that we don't prefix them
node.params.forEach(p =>
(walk as any)(p, {
enter(child: Node, parent: Node) {
if (
child.type === 'Identifier' &&
// do not record as scope variable if is a destructured key
!isStaticPropertyKey(child, parent) &&
// do not record if this is a default value
// assignment of a destructured variable
!(
parent &&
parent.type === 'AssignmentPattern' &&
parent.right === child
)
) {
const { name } = child
if (node.scopeIds && node.scopeIds.has(name)) {
return
}
if (name in knownIds) {
knownIds[name]++
} else {
knownIds[name] = 1
}
;(node.scopeIds || (node.scopeIds = new Set())).add(name)
}
}
})
)
}
},
leave(node: Node & PrefixMeta, parent: Node | undefined) {
parent && parentStack.pop()
if (node !== ast.body[0].expression && node.scopeIds) {
node.scopeIds.forEach((id: string) => {
knownIds[id]--
if (knownIds[id] === 0) {
delete knownIds[id]
}
})
}
}
})
// We break up the compound expression into an array of strings and sub
// expressions (for identifiers that have been prefixed). In codegen, if
// an ExpressionNode has the `.children` property, it will be used instead of
// `.content`.
const children: CompoundExpressionNode['children'] = []
ids.sort((a, b) => a.start - b.start)
ids.forEach((id, i) => {
// range is offset by -1 due to the wrapping parens when parsed
const start = id.start - 1
const end = id.end - 1
const last = ids[i - 1]
const leadingText = rawExp.slice(last ? last.end - 1 : 0, start)
if (leadingText.length || id.prefix) {
children.push(leadingText + (id.prefix || ``))
}
const source = rawExp.slice(start, end)
children.push(
createSimpleExpression(
id.name,
false,
{
source,
start: advancePositionWithClone(node.loc.start, source, start),
end: advancePositionWithClone(node.loc.start, source, end)
},
id.isConstant ? ConstantTypes.CAN_STRINGIFY : ConstantTypes.NOT_CONSTANT
)
)
if (i === ids.length - 1 && end < rawExp.length) {
children.push(rawExp.slice(end))
}
})
let ret
if (children.length) {
ret = createCompoundExpression(children, node.loc)
} else {
ret = node
ret.constType = bailConstant
? ConstantTypes.NOT_CONSTANT
: ConstantTypes.CAN_STRINGIFY
}
ret.identifiers = Object.keys(knownIds)
return ret
}
const isFunction = (node: Node): node is Function => {
return /Function(?:Expression|Declaration)$|Method$/.test(node.type)
}
const isStaticProperty = (node: Node): node is ObjectProperty =>
node &&
(node.type === 'ObjectProperty' || node.type === 'ObjectMethod') &&
!node.computed
const isStaticPropertyKey = (node: Node, parent: Node) =>
isStaticProperty(parent) && parent.key === node
function shouldPrefix(id: Identifier, parent: Node, parentStack: Node[]) {
// declaration id
if (
(parent.type === 'VariableDeclarator' ||
parent.type === 'ClassDeclaration') &&
parent.id === id
) {
return false
}
if (isFunction(parent)) {
// function decalration/expression id
if ((parent as any).id === id) {
return false
}
// params list
if (parent.params.includes(id)) {
return false
}
}
// property key
// this also covers object destructure pattern
if (isStaticPropertyKey(id, parent)) {
return false
}
// non-assignment array destructure pattern
if (
parent.type === 'ArrayPattern' &&
!isInDestructureAssignment(parent, parentStack)
) {
return false
}
// member expression property
if (
(parent.type === 'MemberExpression' ||
parent.type === 'OptionalMemberExpression') &&
parent.property === id &&
!parent.computed
) {
return false
}
// is a special keyword but parsed as identifier
if (id.name === 'arguments') {
return false
}
// skip whitelisted globals
if (isGloballyWhitelisted(id.name)) {
return false
}
// special case for webpack compilation
if (id.name === 'require') {
return false
}
return true
}
function isInDestructureAssignment(parent: Node, parentStack: Node[]): boolean {
if (
parent &&
(parent.type === 'ObjectProperty' || parent.type === 'ArrayPattern')
) {
let i = parentStack.length
while (i--) {
const p = parentStack[i]
if (p.type === 'AssignmentExpression') {
return true
} else if (p.type !== 'ObjectProperty' && !p.type.endsWith('Pattern')) {
break
}
}
}
return false
}
function stringifyExpression(exp: ExpressionNode | string): string {
if (isString(exp)) {
return exp
} else if (exp.type === NodeTypes.SIMPLE_EXPRESSION) {
return exp.content
} else {
return (exp.children as (ExpressionNode | string)[])
.map(stringifyExpression)
.join('')
}
}
| packages/compiler-core/src/transforms/transformExpression.ts | 0 | https://github.com/vuejs/core/commit/7c4e4514d166b2fcb055baa091a79d9244458ab5 | [
0.0002761697396636009,
0.00017629656940698624,
0.00016520638018846512,
0.00017511729674879462,
0.000014949777323636226
] |
{
"id": 2,
"code_window": [
" expect(spy).toHaveBeenCalledTimes(0)\n",
"\n",
" onScopeDispose(spy)\n",
"\n",
" expect(\n",
" '[Vue warn] onDispose() is called when there is no active effect scope to be associated with.'\n",
" ).toHaveBeenWarned()\n",
"\n",
" scope.stop()\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" '[Vue warn] onScopeDispose() is called when there is no active effect scope to be associated with.'\n"
],
"file_path": "packages/reactivity/__tests__/effectScope.spec.ts",
"type": "replace",
"edit_start_line_idx": 206
} | import { nextTick, watch, watchEffect } from '@vue/runtime-core'
import {
reactive,
effect,
EffectScope,
onScopeDispose,
computed,
ref,
ComputedRef
} from '../src'
describe('reactivity/effect/scope', () => {
it('should run', () => {
const fnSpy = jest.fn(() => {})
new EffectScope().run(fnSpy)
expect(fnSpy).toHaveBeenCalledTimes(1)
})
it('should accept zero argument', () => {
const scope = new EffectScope()
expect(scope.effects.length).toBe(0)
})
it('should return run value', () => {
expect(new EffectScope().run(() => 1)).toBe(1)
})
it('should collect the effects', () => {
const scope = new EffectScope()
scope.run(() => {
let dummy
const counter = reactive({ num: 0 })
effect(() => (dummy = counter.num))
expect(dummy).toBe(0)
counter.num = 7
expect(dummy).toBe(7)
})
expect(scope.effects.length).toBe(1)
})
it('stop', () => {
let dummy, doubled
const counter = reactive({ num: 0 })
const scope = new EffectScope()
scope.run(() => {
effect(() => (dummy = counter.num))
effect(() => (doubled = counter.num * 2))
})
expect(scope.effects.length).toBe(2)
expect(dummy).toBe(0)
counter.num = 7
expect(dummy).toBe(7)
expect(doubled).toBe(14)
scope.stop()
counter.num = 6
expect(dummy).toBe(7)
expect(doubled).toBe(14)
})
it('should collect nested scope', () => {
let dummy, doubled
const counter = reactive({ num: 0 })
const scope = new EffectScope()
scope.run(() => {
effect(() => (dummy = counter.num))
// nested scope
new EffectScope().run(() => {
effect(() => (doubled = counter.num * 2))
})
})
expect(scope.effects.length).toBe(1)
expect(scope.scopes!.length).toBe(1)
expect(scope.scopes![0]).toBeInstanceOf(EffectScope)
expect(dummy).toBe(0)
counter.num = 7
expect(dummy).toBe(7)
expect(doubled).toBe(14)
// stop the nested scope as well
scope.stop()
counter.num = 6
expect(dummy).toBe(7)
expect(doubled).toBe(14)
})
it('nested scope can be escaped', () => {
let dummy, doubled
const counter = reactive({ num: 0 })
const scope = new EffectScope()
scope.run(() => {
effect(() => (dummy = counter.num))
// nested scope
new EffectScope(true).run(() => {
effect(() => (doubled = counter.num * 2))
})
})
expect(scope.effects.length).toBe(1)
expect(dummy).toBe(0)
counter.num = 7
expect(dummy).toBe(7)
expect(doubled).toBe(14)
scope.stop()
counter.num = 6
expect(dummy).toBe(7)
// nested scope should not be stoped
expect(doubled).toBe(12)
})
it('able to run the scope', () => {
let dummy, doubled
const counter = reactive({ num: 0 })
const scope = new EffectScope()
scope.run(() => {
effect(() => (dummy = counter.num))
})
expect(scope.effects.length).toBe(1)
scope.run(() => {
effect(() => (doubled = counter.num * 2))
})
expect(scope.effects.length).toBe(2)
counter.num = 7
expect(dummy).toBe(7)
expect(doubled).toBe(14)
scope.stop()
})
it('can not run an inactive scope', () => {
let dummy, doubled
const counter = reactive({ num: 0 })
const scope = new EffectScope()
scope.run(() => {
effect(() => (dummy = counter.num))
})
expect(scope.effects.length).toBe(1)
scope.stop()
scope.run(() => {
effect(() => (doubled = counter.num * 2))
})
expect('[Vue warn] cannot run an inactive effect scope.').toHaveBeenWarned()
expect(scope.effects.length).toBe(1)
counter.num = 7
expect(dummy).toBe(0)
expect(doubled).toBe(undefined)
})
it('should fire onDispose hook', () => {
let dummy = 0
const scope = new EffectScope()
scope.run(() => {
onScopeDispose(() => (dummy += 1))
onScopeDispose(() => (dummy += 2))
})
scope.run(() => {
onScopeDispose(() => (dummy += 4))
})
expect(dummy).toBe(0)
scope.stop()
expect(dummy).toBe(7)
})
it('should warn onDispose() is called when there is no active effect scope', () => {
const spy = jest.fn()
const scope = new EffectScope()
scope.run(() => {
onScopeDispose(spy)
})
expect(spy).toHaveBeenCalledTimes(0)
onScopeDispose(spy)
expect(
'[Vue warn] onDispose() is called when there is no active effect scope to be associated with.'
).toHaveBeenWarned()
scope.stop()
expect(spy).toHaveBeenCalledTimes(1)
})
it('should derefence child scope from parent scope after stopping child scope (no memleaks)', async () => {
const parent = new EffectScope()
const child = parent.run(() => new EffectScope())!
expect(parent.scopes!.includes(child)).toBe(true)
child.stop()
expect(parent.scopes!.includes(child)).toBe(false)
})
it('test with higher level APIs', async () => {
const r = ref(1)
const computedSpy = jest.fn()
const watchSpy = jest.fn()
const watchEffectSpy = jest.fn()
let c: ComputedRef
const scope = new EffectScope()
scope.run(() => {
c = computed(() => {
computedSpy()
return r.value + 1
})
watch(r, watchSpy)
watchEffect(() => {
watchEffectSpy()
r.value
})
})
c!.value // computed is lazy so trigger collection
expect(computedSpy).toHaveBeenCalledTimes(1)
expect(watchSpy).toHaveBeenCalledTimes(0)
expect(watchEffectSpy).toHaveBeenCalledTimes(1)
r.value++
c!.value
await nextTick()
expect(computedSpy).toHaveBeenCalledTimes(2)
expect(watchSpy).toHaveBeenCalledTimes(1)
expect(watchEffectSpy).toHaveBeenCalledTimes(2)
scope.stop()
r.value++
c!.value
await nextTick()
// should not trigger anymore
expect(computedSpy).toHaveBeenCalledTimes(2)
expect(watchSpy).toHaveBeenCalledTimes(1)
expect(watchEffectSpy).toHaveBeenCalledTimes(2)
})
})
| packages/reactivity/__tests__/effectScope.spec.ts | 1 | https://github.com/vuejs/core/commit/7c4e4514d166b2fcb055baa091a79d9244458ab5 | [
0.9927829504013062,
0.09782589972019196,
0.0001674809755058959,
0.001773133291862905,
0.2709875702857971
] |
{
"id": 2,
"code_window": [
" expect(spy).toHaveBeenCalledTimes(0)\n",
"\n",
" onScopeDispose(spy)\n",
"\n",
" expect(\n",
" '[Vue warn] onDispose() is called when there is no active effect scope to be associated with.'\n",
" ).toHaveBeenWarned()\n",
"\n",
" scope.stop()\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" '[Vue warn] onScopeDispose() is called when there is no active effect scope to be associated with.'\n"
],
"file_path": "packages/reactivity/__tests__/effectScope.spec.ts",
"type": "replace",
"edit_start_line_idx": 206
} | import { NodeTransform, NodeTypes, ElementTypes } from '@vue/compiler-core'
import { DOMErrorCodes, createDOMCompilerError } from '../errors'
export const ignoreSideEffectTags: NodeTransform = (node, context) => {
if (
node.type === NodeTypes.ELEMENT &&
node.tagType === ElementTypes.ELEMENT &&
(node.tag === 'script' || node.tag === 'style')
) {
context.onError(
createDOMCompilerError(DOMErrorCodes.X_IGNORED_SIDE_EFFECT_TAG, node.loc)
)
context.removeNode()
}
}
| packages/compiler-dom/src/transforms/ignoreSideEffectTags.ts | 0 | https://github.com/vuejs/core/commit/7c4e4514d166b2fcb055baa091a79d9244458ab5 | [
0.000304648419842124,
0.00024026866594795138,
0.00017588891205377877,
0.00024026866594795138,
0.00006437975389417261
] |
{
"id": 2,
"code_window": [
" expect(spy).toHaveBeenCalledTimes(0)\n",
"\n",
" onScopeDispose(spy)\n",
"\n",
" expect(\n",
" '[Vue warn] onDispose() is called when there is no active effect scope to be associated with.'\n",
" ).toHaveBeenWarned()\n",
"\n",
" scope.stop()\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" '[Vue warn] onScopeDispose() is called when there is no active effect scope to be associated with.'\n"
],
"file_path": "packages/reactivity/__tests__/effectScope.spec.ts",
"type": "replace",
"edit_start_line_idx": 206
} | // This directory contains a number of d.ts assertions
// use \@ts-expect-error where errors are expected.
export * from '@vue/runtime-dom'
export function describe(_name: string, _fn: () => void): void
export function expectType<T>(value: T): void
export function expectError<T>(value: T): void
export function expectAssignable<T, T2 extends T = T>(value: T2): void
export type IsUnion<T, U extends T = T> = (T extends any
? (U extends T ? false : true)
: never) extends false
? false
: true
| test-dts/index.d.ts | 0 | https://github.com/vuejs/core/commit/7c4e4514d166b2fcb055baa091a79d9244458ab5 | [
0.0004052827716805041,
0.000289425952360034,
0.00017356911848764867,
0.000289425952360034,
0.00011585682659642771
] |
{
"id": 2,
"code_window": [
" expect(spy).toHaveBeenCalledTimes(0)\n",
"\n",
" onScopeDispose(spy)\n",
"\n",
" expect(\n",
" '[Vue warn] onDispose() is called when there is no active effect scope to be associated with.'\n",
" ).toHaveBeenWarned()\n",
"\n",
" scope.stop()\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" '[Vue warn] onScopeDispose() is called when there is no active effect scope to be associated with.'\n"
],
"file_path": "packages/reactivity/__tests__/effectScope.spec.ts",
"type": "replace",
"edit_start_line_idx": 206
} | import { compileStyle } from '../src'
import { mockId, compileSFCScript, assertCode } from './utils'
describe('CSS vars injection', () => {
test('generating correct code for nested paths', () => {
const { content } = compileSFCScript(
`<script>const a = 1</script>\n` +
`<style>div{
color: v-bind(color);
font-size: v-bind('font.size');
}</style>`
)
expect(content).toMatch(`_useCssVars(_ctx => ({
"${mockId}-color": (_ctx.color),
"${mockId}-font_size": (_ctx.font.size)
})`)
assertCode(content)
})
test('w/ normal <script> binding analysis', () => {
const { content } = compileSFCScript(
`<script>
export default {
setup() {
return {
size: ref('100px')
}
}
}
</script>\n` +
`<style>
div {
font-size: v-bind(size);
}
</style>`
)
expect(content).toMatch(`_useCssVars(_ctx => ({
"${mockId}-size": (_ctx.size)
})`)
expect(content).toMatch(`import { useCssVars as _useCssVars } from 'vue'`)
assertCode(content)
})
test('w/ <script setup> binding analysis', () => {
const { content } = compileSFCScript(
`<script setup>
import { defineProps, ref } from 'vue'
const color = 'red'
const size = ref('10px')
defineProps({
foo: String
})
</script>\n` +
`<style>
div {
color: v-bind(color);
font-size: v-bind(size);
border: v-bind(foo);
}
</style>`
)
// should handle:
// 1. local const bindings
// 2. local potential ref bindings
// 3. props bindings (analyzed)
expect(content).toMatch(`_useCssVars(_ctx => ({
"${mockId}-color": (color),
"${mockId}-size": (size.value),
"${mockId}-foo": (__props.foo)
})`)
expect(content).toMatch(
`import { useCssVars as _useCssVars, unref as _unref } from 'vue'`
)
assertCode(content)
})
test('should rewrite CSS vars in compileStyle', () => {
const { code } = compileStyle({
source: `.foo {
color: v-bind(color);
font-size: v-bind('font.size');
}`,
filename: 'test.css',
id: 'data-v-test'
})
expect(code).toMatchInlineSnapshot(`
".foo {
color: var(--test-color);
font-size: var(--test-font_size);
}"
`)
})
test('prod mode', () => {
const { content } = compileSFCScript(
`<script>const a = 1</script>\n` +
`<style>div{
color: v-bind(color);
font-size: v-bind('font.size');
}</style>`,
{ isProd: true }
)
expect(content).toMatch(`_useCssVars(_ctx => ({
"4003f1a6": (_ctx.color),
"41b6490a": (_ctx.font.size)
}))}`)
const { code } = compileStyle({
source: `.foo {
color: v-bind(color);
font-size: v-bind('font.size');
}`,
filename: 'test.css',
id: mockId,
isProd: true
})
expect(code).toMatchInlineSnapshot(`
".foo {
color: var(--4003f1a6);
font-size: var(--41b6490a);
}"
`)
})
describe('codegen', () => {
test('<script> w/ no default export', () => {
assertCode(
compileSFCScript(
`<script>const a = 1</script>\n` +
`<style>div{ color: v-bind(color); }</style>`
).content
)
})
test('<script> w/ default export', () => {
assertCode(
compileSFCScript(
`<script>export default { setup() {} }</script>\n` +
`<style>div{ color: v-bind(color); }</style>`
).content
)
})
test('<script> w/ default export in strings/comments', () => {
assertCode(
compileSFCScript(
`<script>
// export default {}
export default {}
</script>\n` + `<style>div{ color: v-bind(color); }</style>`
).content
)
})
test('w/ <script setup>', () => {
assertCode(
compileSFCScript(
`<script setup>const color = 'red'</script>\n` +
`<style>div{ color: v-bind(color); }</style>`
).content
)
})
//#4185
test('should ignore comments', () => {
const { content } = compileSFCScript(
`<script setup>const color = 'red';const width = 100</script>\n` +
`<style>
/* comment **/
div{ /* color: v-bind(color); */ width:20; }
div{ width: v-bind(width); }
/* comment */
</style>`
)
expect(content).not.toMatch(`"${mockId}-color": (color)`)
expect(content).toMatch(`"${mockId}-width": (width)`)
assertCode(content)
})
test('w/ <script setup> using the same var multiple times', () => {
const { content } = compileSFCScript(
`<script setup>
const color = 'red'
</script>\n` +
`<style>
div {
color: v-bind(color);
}
p {
color: v-bind(color);
}
</style>`
)
// color should only be injected once, even if it is twice in style
expect(content).toMatch(`_useCssVars(_ctx => ({
"${mockId}-color": (color)
})`)
assertCode(content)
})
})
})
| packages/compiler-sfc/__tests__/cssVars.spec.ts | 0 | https://github.com/vuejs/core/commit/7c4e4514d166b2fcb055baa091a79d9244458ab5 | [
0.0001802982296794653,
0.00017584150191396475,
0.00016699446132406592,
0.0001764408516464755,
0.0000029455286494339816
] |
{
"id": 3,
"code_window": [
"export function onScopeDispose(fn: () => void) {\n",
" if (activeEffectScope) {\n",
" activeEffectScope.cleanups.push(fn)\n",
" } else if (__DEV__) {\n",
" warn(\n",
" `onDispose() is called when there is no active effect scope` +\n",
" ` to be associated with.`\n",
" )\n",
" }\n",
"}"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" `onScopeDispose() is called when there is no active effect scope` +\n"
],
"file_path": "packages/reactivity/src/effectScope.ts",
"type": "replace",
"edit_start_line_idx": 100
} | import { nextTick, watch, watchEffect } from '@vue/runtime-core'
import {
reactive,
effect,
EffectScope,
onScopeDispose,
computed,
ref,
ComputedRef
} from '../src'
describe('reactivity/effect/scope', () => {
it('should run', () => {
const fnSpy = jest.fn(() => {})
new EffectScope().run(fnSpy)
expect(fnSpy).toHaveBeenCalledTimes(1)
})
it('should accept zero argument', () => {
const scope = new EffectScope()
expect(scope.effects.length).toBe(0)
})
it('should return run value', () => {
expect(new EffectScope().run(() => 1)).toBe(1)
})
it('should collect the effects', () => {
const scope = new EffectScope()
scope.run(() => {
let dummy
const counter = reactive({ num: 0 })
effect(() => (dummy = counter.num))
expect(dummy).toBe(0)
counter.num = 7
expect(dummy).toBe(7)
})
expect(scope.effects.length).toBe(1)
})
it('stop', () => {
let dummy, doubled
const counter = reactive({ num: 0 })
const scope = new EffectScope()
scope.run(() => {
effect(() => (dummy = counter.num))
effect(() => (doubled = counter.num * 2))
})
expect(scope.effects.length).toBe(2)
expect(dummy).toBe(0)
counter.num = 7
expect(dummy).toBe(7)
expect(doubled).toBe(14)
scope.stop()
counter.num = 6
expect(dummy).toBe(7)
expect(doubled).toBe(14)
})
it('should collect nested scope', () => {
let dummy, doubled
const counter = reactive({ num: 0 })
const scope = new EffectScope()
scope.run(() => {
effect(() => (dummy = counter.num))
// nested scope
new EffectScope().run(() => {
effect(() => (doubled = counter.num * 2))
})
})
expect(scope.effects.length).toBe(1)
expect(scope.scopes!.length).toBe(1)
expect(scope.scopes![0]).toBeInstanceOf(EffectScope)
expect(dummy).toBe(0)
counter.num = 7
expect(dummy).toBe(7)
expect(doubled).toBe(14)
// stop the nested scope as well
scope.stop()
counter.num = 6
expect(dummy).toBe(7)
expect(doubled).toBe(14)
})
it('nested scope can be escaped', () => {
let dummy, doubled
const counter = reactive({ num: 0 })
const scope = new EffectScope()
scope.run(() => {
effect(() => (dummy = counter.num))
// nested scope
new EffectScope(true).run(() => {
effect(() => (doubled = counter.num * 2))
})
})
expect(scope.effects.length).toBe(1)
expect(dummy).toBe(0)
counter.num = 7
expect(dummy).toBe(7)
expect(doubled).toBe(14)
scope.stop()
counter.num = 6
expect(dummy).toBe(7)
// nested scope should not be stoped
expect(doubled).toBe(12)
})
it('able to run the scope', () => {
let dummy, doubled
const counter = reactive({ num: 0 })
const scope = new EffectScope()
scope.run(() => {
effect(() => (dummy = counter.num))
})
expect(scope.effects.length).toBe(1)
scope.run(() => {
effect(() => (doubled = counter.num * 2))
})
expect(scope.effects.length).toBe(2)
counter.num = 7
expect(dummy).toBe(7)
expect(doubled).toBe(14)
scope.stop()
})
it('can not run an inactive scope', () => {
let dummy, doubled
const counter = reactive({ num: 0 })
const scope = new EffectScope()
scope.run(() => {
effect(() => (dummy = counter.num))
})
expect(scope.effects.length).toBe(1)
scope.stop()
scope.run(() => {
effect(() => (doubled = counter.num * 2))
})
expect('[Vue warn] cannot run an inactive effect scope.').toHaveBeenWarned()
expect(scope.effects.length).toBe(1)
counter.num = 7
expect(dummy).toBe(0)
expect(doubled).toBe(undefined)
})
it('should fire onDispose hook', () => {
let dummy = 0
const scope = new EffectScope()
scope.run(() => {
onScopeDispose(() => (dummy += 1))
onScopeDispose(() => (dummy += 2))
})
scope.run(() => {
onScopeDispose(() => (dummy += 4))
})
expect(dummy).toBe(0)
scope.stop()
expect(dummy).toBe(7)
})
it('should warn onDispose() is called when there is no active effect scope', () => {
const spy = jest.fn()
const scope = new EffectScope()
scope.run(() => {
onScopeDispose(spy)
})
expect(spy).toHaveBeenCalledTimes(0)
onScopeDispose(spy)
expect(
'[Vue warn] onDispose() is called when there is no active effect scope to be associated with.'
).toHaveBeenWarned()
scope.stop()
expect(spy).toHaveBeenCalledTimes(1)
})
it('should derefence child scope from parent scope after stopping child scope (no memleaks)', async () => {
const parent = new EffectScope()
const child = parent.run(() => new EffectScope())!
expect(parent.scopes!.includes(child)).toBe(true)
child.stop()
expect(parent.scopes!.includes(child)).toBe(false)
})
it('test with higher level APIs', async () => {
const r = ref(1)
const computedSpy = jest.fn()
const watchSpy = jest.fn()
const watchEffectSpy = jest.fn()
let c: ComputedRef
const scope = new EffectScope()
scope.run(() => {
c = computed(() => {
computedSpy()
return r.value + 1
})
watch(r, watchSpy)
watchEffect(() => {
watchEffectSpy()
r.value
})
})
c!.value // computed is lazy so trigger collection
expect(computedSpy).toHaveBeenCalledTimes(1)
expect(watchSpy).toHaveBeenCalledTimes(0)
expect(watchEffectSpy).toHaveBeenCalledTimes(1)
r.value++
c!.value
await nextTick()
expect(computedSpy).toHaveBeenCalledTimes(2)
expect(watchSpy).toHaveBeenCalledTimes(1)
expect(watchEffectSpy).toHaveBeenCalledTimes(2)
scope.stop()
r.value++
c!.value
await nextTick()
// should not trigger anymore
expect(computedSpy).toHaveBeenCalledTimes(2)
expect(watchSpy).toHaveBeenCalledTimes(1)
expect(watchEffectSpy).toHaveBeenCalledTimes(2)
})
})
| packages/reactivity/__tests__/effectScope.spec.ts | 1 | https://github.com/vuejs/core/commit/7c4e4514d166b2fcb055baa091a79d9244458ab5 | [
0.9983721375465393,
0.14904636144638062,
0.00016681032138876617,
0.0008664774359203875,
0.35350847244262695
] |
{
"id": 3,
"code_window": [
"export function onScopeDispose(fn: () => void) {\n",
" if (activeEffectScope) {\n",
" activeEffectScope.cleanups.push(fn)\n",
" } else if (__DEV__) {\n",
" warn(\n",
" `onDispose() is called when there is no active effect scope` +\n",
" ` to be associated with.`\n",
" )\n",
" }\n",
"}"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" `onScopeDispose() is called when there is no active effect scope` +\n"
],
"file_path": "packages/reactivity/src/effectScope.ts",
"type": "replace",
"edit_start_line_idx": 100
} | import {
watch,
watchEffect,
reactive,
computed,
nextTick,
ref,
defineComponent,
getCurrentInstance,
ComponentInternalInstance,
ComponentPublicInstance
} from '../src/index'
import {
render,
nodeOps,
serializeInner,
TestElement,
h,
createApp,
watchPostEffect,
watchSyncEffect
} from '@vue/runtime-test'
import {
ITERATE_KEY,
DebuggerEvent,
TrackOpTypes,
TriggerOpTypes,
triggerRef,
shallowRef,
Ref,
effectScope
} from '@vue/reactivity'
// reference: https://vue-composition-api-rfc.netlify.com/api.html#watch
describe('api: watch', () => {
it('effect', async () => {
const state = reactive({ count: 0 })
let dummy
watchEffect(() => {
dummy = state.count
})
expect(dummy).toBe(0)
state.count++
await nextTick()
expect(dummy).toBe(1)
})
it('watching single source: getter', async () => {
const state = reactive({ count: 0 })
let dummy
watch(
() => state.count,
(count, prevCount) => {
dummy = [count, prevCount]
// assert types
count + 1
if (prevCount) {
prevCount + 1
}
}
)
state.count++
await nextTick()
expect(dummy).toMatchObject([1, 0])
})
it('watching single source: ref', async () => {
const count = ref(0)
let dummy
watch(count, (count, prevCount) => {
dummy = [count, prevCount]
// assert types
count + 1
if (prevCount) {
prevCount + 1
}
})
count.value++
await nextTick()
expect(dummy).toMatchObject([1, 0])
})
it('watching single source: array', async () => {
const array = reactive([] as number[])
const spy = jest.fn()
watch(array, spy)
array.push(1)
await nextTick()
expect(spy).toBeCalledTimes(1)
expect(spy).toBeCalledWith([1], expect.anything(), expect.anything())
})
it('should not fire if watched getter result did not change', async () => {
const spy = jest.fn()
const n = ref(0)
watch(() => n.value % 2, spy)
n.value++
await nextTick()
expect(spy).toBeCalledTimes(1)
n.value += 2
await nextTick()
// should not be called again because getter result did not change
expect(spy).toBeCalledTimes(1)
})
it('watching single source: computed ref', async () => {
const count = ref(0)
const plus = computed(() => count.value + 1)
let dummy
watch(plus, (count, prevCount) => {
dummy = [count, prevCount]
// assert types
count + 1
if (prevCount) {
prevCount + 1
}
})
count.value++
await nextTick()
expect(dummy).toMatchObject([2, 1])
})
it('watching primitive with deep: true', async () => {
const count = ref(0)
let dummy
watch(
count,
(c, prevCount) => {
dummy = [c, prevCount]
},
{
deep: true
}
)
count.value++
await nextTick()
expect(dummy).toMatchObject([1, 0])
})
it('directly watching reactive object (with automatic deep: true)', async () => {
const src = reactive({
count: 0
})
let dummy
watch(src, ({ count }) => {
dummy = count
})
src.count++
await nextTick()
expect(dummy).toBe(1)
})
it('watching multiple sources', async () => {
const state = reactive({ count: 1 })
const count = ref(1)
const plus = computed(() => count.value + 1)
let dummy
watch([() => state.count, count, plus], (vals, oldVals) => {
dummy = [vals, oldVals]
// assert types
vals.concat(1)
oldVals.concat(1)
})
state.count++
count.value++
await nextTick()
expect(dummy).toMatchObject([
[2, 2, 3],
[1, 1, 2]
])
})
it('watching multiple sources: readonly array', async () => {
const state = reactive({ count: 1 })
const status = ref(false)
let dummy
watch([() => state.count, status] as const, (vals, oldVals) => {
dummy = [vals, oldVals]
const [count] = vals
const [, oldStatus] = oldVals
// assert types
count + 1
oldStatus === true
})
state.count++
status.value = true
await nextTick()
expect(dummy).toMatchObject([
[2, true],
[1, false]
])
})
it('watching multiple sources: reactive object (with automatic deep: true)', async () => {
const src = reactive({ count: 0 })
let dummy
watch([src], ([state]) => {
dummy = state
// assert types
state.count === 1
})
src.count++
await nextTick()
expect(dummy).toMatchObject({ count: 1 })
})
it('warn invalid watch source', () => {
// @ts-ignore
watch(1, () => {})
expect(`Invalid watch source`).toHaveBeenWarned()
})
it('warn invalid watch source: multiple sources', () => {
watch([1], () => {})
expect(`Invalid watch source`).toHaveBeenWarned()
})
it('stopping the watcher (effect)', async () => {
const state = reactive({ count: 0 })
let dummy
const stop = watchEffect(() => {
dummy = state.count
})
expect(dummy).toBe(0)
stop()
state.count++
await nextTick()
// should not update
expect(dummy).toBe(0)
})
it('stopping the watcher (with source)', async () => {
const state = reactive({ count: 0 })
let dummy
const stop = watch(
() => state.count,
count => {
dummy = count
}
)
state.count++
await nextTick()
expect(dummy).toBe(1)
stop()
state.count++
await nextTick()
// should not update
expect(dummy).toBe(1)
})
it('cleanup registration (effect)', async () => {
const state = reactive({ count: 0 })
const cleanup = jest.fn()
let dummy
const stop = watchEffect(onCleanup => {
onCleanup(cleanup)
dummy = state.count
})
expect(dummy).toBe(0)
state.count++
await nextTick()
expect(cleanup).toHaveBeenCalledTimes(1)
expect(dummy).toBe(1)
stop()
expect(cleanup).toHaveBeenCalledTimes(2)
})
it('cleanup registration (with source)', async () => {
const count = ref(0)
const cleanup = jest.fn()
let dummy
const stop = watch(count, (count, prevCount, onCleanup) => {
onCleanup(cleanup)
dummy = count
})
count.value++
await nextTick()
expect(cleanup).toHaveBeenCalledTimes(0)
expect(dummy).toBe(1)
count.value++
await nextTick()
expect(cleanup).toHaveBeenCalledTimes(1)
expect(dummy).toBe(2)
stop()
expect(cleanup).toHaveBeenCalledTimes(2)
})
it('flush timing: pre (default)', async () => {
const count = ref(0)
const count2 = ref(0)
let callCount = 0
let result1
let result2
const assertion = jest.fn((count, count2Value) => {
callCount++
// on mount, the watcher callback should be called before DOM render
// on update, should be called before the count is updated
const expectedDOM = callCount === 1 ? `` : `${count - 1}`
result1 = serializeInner(root) === expectedDOM
// in a pre-flush callback, all state should have been updated
const expectedState = callCount - 1
result2 = count === expectedState && count2Value === expectedState
})
const Comp = {
setup() {
watchEffect(() => {
assertion(count.value, count2.value)
})
return () => count.value
}
}
const root = nodeOps.createElement('div')
render(h(Comp), root)
expect(assertion).toHaveBeenCalledTimes(1)
expect(result1).toBe(true)
expect(result2).toBe(true)
count.value++
count2.value++
await nextTick()
// two mutations should result in 1 callback execution
expect(assertion).toHaveBeenCalledTimes(2)
expect(result1).toBe(true)
expect(result2).toBe(true)
})
it('flush timing: post', async () => {
const count = ref(0)
let result
const assertion = jest.fn(count => {
result = serializeInner(root) === `${count}`
})
const Comp = {
setup() {
watchEffect(
() => {
assertion(count.value)
},
{ flush: 'post' }
)
return () => count.value
}
}
const root = nodeOps.createElement('div')
render(h(Comp), root)
expect(assertion).toHaveBeenCalledTimes(1)
expect(result).toBe(true)
count.value++
await nextTick()
expect(assertion).toHaveBeenCalledTimes(2)
expect(result).toBe(true)
})
it('watchPostEffect', async () => {
const count = ref(0)
let result
const assertion = jest.fn(count => {
result = serializeInner(root) === `${count}`
})
const Comp = {
setup() {
watchPostEffect(() => {
assertion(count.value)
})
return () => count.value
}
}
const root = nodeOps.createElement('div')
render(h(Comp), root)
expect(assertion).toHaveBeenCalledTimes(1)
expect(result).toBe(true)
count.value++
await nextTick()
expect(assertion).toHaveBeenCalledTimes(2)
expect(result).toBe(true)
})
it('flush timing: sync', async () => {
const count = ref(0)
const count2 = ref(0)
let callCount = 0
let result1
let result2
const assertion = jest.fn(count => {
callCount++
// on mount, the watcher callback should be called before DOM render
// on update, should be called before the count is updated
const expectedDOM = callCount === 1 ? `` : `${count - 1}`
result1 = serializeInner(root) === expectedDOM
// in a sync callback, state mutation on the next line should not have
// executed yet on the 2nd call, but will be on the 3rd call.
const expectedState = callCount < 3 ? 0 : 1
result2 = count2.value === expectedState
})
const Comp = {
setup() {
watchEffect(
() => {
assertion(count.value)
},
{
flush: 'sync'
}
)
return () => count.value
}
}
const root = nodeOps.createElement('div')
render(h(Comp), root)
expect(assertion).toHaveBeenCalledTimes(1)
expect(result1).toBe(true)
expect(result2).toBe(true)
count.value++
count2.value++
await nextTick()
expect(assertion).toHaveBeenCalledTimes(3)
expect(result1).toBe(true)
expect(result2).toBe(true)
})
it('watchSyncEffect', async () => {
const count = ref(0)
const count2 = ref(0)
let callCount = 0
let result1
let result2
const assertion = jest.fn(count => {
callCount++
// on mount, the watcher callback should be called before DOM render
// on update, should be called before the count is updated
const expectedDOM = callCount === 1 ? `` : `${count - 1}`
result1 = serializeInner(root) === expectedDOM
// in a sync callback, state mutation on the next line should not have
// executed yet on the 2nd call, but will be on the 3rd call.
const expectedState = callCount < 3 ? 0 : 1
result2 = count2.value === expectedState
})
const Comp = {
setup() {
watchSyncEffect(() => {
assertion(count.value)
})
return () => count.value
}
}
const root = nodeOps.createElement('div')
render(h(Comp), root)
expect(assertion).toHaveBeenCalledTimes(1)
expect(result1).toBe(true)
expect(result2).toBe(true)
count.value++
count2.value++
await nextTick()
expect(assertion).toHaveBeenCalledTimes(3)
expect(result1).toBe(true)
expect(result2).toBe(true)
})
it('should not fire on component unmount w/ flush: post', async () => {
const toggle = ref(true)
const cb = jest.fn()
const Comp = {
setup() {
watch(toggle, cb, { flush: 'post' })
},
render() {}
}
const App = {
render() {
return toggle.value ? h(Comp) : null
}
}
render(h(App), nodeOps.createElement('div'))
expect(cb).not.toHaveBeenCalled()
toggle.value = false
await nextTick()
expect(cb).not.toHaveBeenCalled()
})
it('should fire on component unmount w/ flush: pre', async () => {
const toggle = ref(true)
const cb = jest.fn()
const Comp = {
setup() {
watch(toggle, cb, { flush: 'pre' })
},
render() {}
}
const App = {
render() {
return toggle.value ? h(Comp) : null
}
}
render(h(App), nodeOps.createElement('div'))
expect(cb).not.toHaveBeenCalled()
toggle.value = false
await nextTick()
expect(cb).toHaveBeenCalledTimes(1)
})
// #1763
it('flush: pre watcher watching props should fire before child update', async () => {
const a = ref(0)
const b = ref(0)
const c = ref(0)
const calls: string[] = []
const Comp = {
props: ['a', 'b'],
setup(props: any) {
watch(
() => props.a + props.b,
() => {
calls.push('watcher 1')
c.value++
},
{ flush: 'pre' }
)
// #1777 chained pre-watcher
watch(
c,
() => {
calls.push('watcher 2')
},
{ flush: 'pre' }
)
return () => {
c.value
calls.push('render')
}
}
}
const App = {
render() {
return h(Comp, { a: a.value, b: b.value })
}
}
render(h(App), nodeOps.createElement('div'))
expect(calls).toEqual(['render'])
// both props are updated
// should trigger pre-flush watcher first and only once
// then trigger child render
a.value++
b.value++
await nextTick()
expect(calls).toEqual(['render', 'watcher 1', 'watcher 2', 'render'])
})
// #1852
it('flush: post watcher should fire after template refs updated', async () => {
const toggle = ref(false)
let dom: TestElement | null = null
const App = {
setup() {
const domRef = ref<TestElement | null>(null)
watch(
toggle,
() => {
dom = domRef.value
},
{ flush: 'post' }
)
return () => {
return toggle.value ? h('p', { ref: domRef }) : null
}
}
}
render(h(App), nodeOps.createElement('div'))
expect(dom).toBe(null)
toggle.value = true
await nextTick()
expect(dom!.tag).toBe('p')
})
it('deep', async () => {
const state = reactive({
nested: {
count: ref(0)
},
array: [1, 2, 3],
map: new Map([
['a', 1],
['b', 2]
]),
set: new Set([1, 2, 3])
})
let dummy
watch(
() => state,
state => {
dummy = [
state.nested.count,
state.array[0],
state.map.get('a'),
state.set.has(1)
]
},
{ deep: true }
)
state.nested.count++
await nextTick()
expect(dummy).toEqual([1, 1, 1, true])
// nested array mutation
state.array[0] = 2
await nextTick()
expect(dummy).toEqual([1, 2, 1, true])
// nested map mutation
state.map.set('a', 2)
await nextTick()
expect(dummy).toEqual([1, 2, 2, true])
// nested set mutation
state.set.delete(1)
await nextTick()
expect(dummy).toEqual([1, 2, 2, false])
})
it('watching deep ref', async () => {
const count = ref(0)
const double = computed(() => count.value * 2)
const state = reactive([count, double])
let dummy
watch(
() => state,
state => {
dummy = [state[0].value, state[1].value]
},
{ deep: true }
)
count.value++
await nextTick()
expect(dummy).toEqual([1, 2])
})
it('immediate', async () => {
const count = ref(0)
const cb = jest.fn()
watch(count, cb, { immediate: true })
expect(cb).toHaveBeenCalledTimes(1)
count.value++
await nextTick()
expect(cb).toHaveBeenCalledTimes(2)
})
it('immediate: triggers when initial value is null', async () => {
const state = ref(null)
const spy = jest.fn()
watch(() => state.value, spy, { immediate: true })
expect(spy).toHaveBeenCalled()
})
it('immediate: triggers when initial value is undefined', async () => {
const state = ref()
const spy = jest.fn()
watch(() => state.value, spy, { immediate: true })
expect(spy).toHaveBeenCalled()
state.value = 3
await nextTick()
expect(spy).toHaveBeenCalledTimes(2)
// testing if undefined can trigger the watcher
state.value = undefined
await nextTick()
expect(spy).toHaveBeenCalledTimes(3)
// it shouldn't trigger if the same value is set
state.value = undefined
await nextTick()
expect(spy).toHaveBeenCalledTimes(3)
})
it('warn immediate option when using effect', async () => {
const count = ref(0)
let dummy
watchEffect(
() => {
dummy = count.value
},
// @ts-ignore
{ immediate: false }
)
expect(dummy).toBe(0)
expect(`"immediate" option is only respected`).toHaveBeenWarned()
count.value++
await nextTick()
expect(dummy).toBe(1)
})
it('warn and not respect deep option when using effect', async () => {
const arr = ref([1, [2]])
const spy = jest.fn()
watchEffect(
() => {
spy()
return arr
},
// @ts-ignore
{ deep: true }
)
expect(spy).toHaveBeenCalledTimes(1)
;(arr.value[1] as Array<number>)[0] = 3
await nextTick()
expect(spy).toHaveBeenCalledTimes(1)
expect(`"deep" option is only respected`).toHaveBeenWarned()
})
it('onTrack', async () => {
const events: DebuggerEvent[] = []
let dummy
const onTrack = jest.fn((e: DebuggerEvent) => {
events.push(e)
})
const obj = reactive({ foo: 1, bar: 2 })
watchEffect(
() => {
dummy = [obj.foo, 'bar' in obj, Object.keys(obj)]
},
{ onTrack }
)
await nextTick()
expect(dummy).toEqual([1, true, ['foo', 'bar']])
expect(onTrack).toHaveBeenCalledTimes(3)
expect(events).toMatchObject([
{
target: obj,
type: TrackOpTypes.GET,
key: 'foo'
},
{
target: obj,
type: TrackOpTypes.HAS,
key: 'bar'
},
{
target: obj,
type: TrackOpTypes.ITERATE,
key: ITERATE_KEY
}
])
})
it('onTrigger', async () => {
const events: DebuggerEvent[] = []
let dummy
const onTrigger = jest.fn((e: DebuggerEvent) => {
events.push(e)
})
const obj = reactive({ foo: 1 })
watchEffect(
() => {
dummy = obj.foo
},
{ onTrigger }
)
await nextTick()
expect(dummy).toBe(1)
obj.foo++
await nextTick()
expect(dummy).toBe(2)
expect(onTrigger).toHaveBeenCalledTimes(1)
expect(events[0]).toMatchObject({
type: TriggerOpTypes.SET,
key: 'foo',
oldValue: 1,
newValue: 2
})
// @ts-ignore
delete obj.foo
await nextTick()
expect(dummy).toBeUndefined()
expect(onTrigger).toHaveBeenCalledTimes(2)
expect(events[1]).toMatchObject({
type: TriggerOpTypes.DELETE,
key: 'foo',
oldValue: 2
})
})
it('should work sync', () => {
const v = ref(1)
let calls = 0
watch(
v,
() => {
++calls
},
{
flush: 'sync'
}
)
expect(calls).toBe(0)
v.value++
expect(calls).toBe(1)
})
test('should force trigger on triggerRef when watching a shallow ref', async () => {
const v = shallowRef({ a: 1 })
let sideEffect = 0
watch(v, obj => {
sideEffect = obj.a
})
v.value = v.value
await nextTick()
// should not trigger
expect(sideEffect).toBe(0)
v.value.a++
await nextTick()
// should not trigger
expect(sideEffect).toBe(0)
triggerRef(v)
await nextTick()
// should trigger now
expect(sideEffect).toBe(2)
})
// #2125
test('watchEffect should not recursively trigger itself', async () => {
const spy = jest.fn()
const price = ref(10)
const history = ref<number[]>([])
watchEffect(() => {
history.value.push(price.value)
spy()
})
await nextTick()
expect(spy).toHaveBeenCalledTimes(1)
})
// #2231
test('computed refs should not trigger watch if value has no change', async () => {
const spy = jest.fn()
const source = ref(0)
const price = computed(() => source.value === 0)
watch(price, spy)
source.value++
await nextTick()
source.value++
await nextTick()
expect(spy).toHaveBeenCalledTimes(1)
})
// https://github.com/vuejs/vue-next/issues/2381
test('$watch should always register its effects with its own instance', async () => {
let instance: ComponentInternalInstance | null
let _show: Ref<boolean>
const Child = defineComponent({
render: () => h('div'),
mounted() {
instance = getCurrentInstance()
},
unmounted() {}
})
const Comp = defineComponent({
setup() {
const comp = ref<ComponentPublicInstance | undefined>()
const show = ref(true)
_show = show
return { comp, show }
},
render() {
return this.show
? h(Child, {
ref: vm => void (this.comp = vm as ComponentPublicInstance)
})
: null
},
mounted() {
// this call runs while Comp is currentInstance, but
// the effect for this `$watch` should nontheless be registered with Child
this.comp!.$watch(
() => this.show,
() => void 0
)
}
})
render(h(Comp), nodeOps.createElement('div'))
expect(instance!).toBeDefined()
expect(instance!.scope.effects).toBeInstanceOf(Array)
// includes the component's own render effect AND the watcher effect
expect(instance!.scope.effects.length).toBe(2)
_show!.value = false
await nextTick()
await nextTick()
expect(instance!.scope.effects[0].active).toBe(false)
})
test('this.$watch should pass `this.proxy` to watch source as the first argument ', () => {
let instance: any
const source = jest.fn()
const Comp = defineComponent({
render() {},
created(this: any) {
instance = this
this.$watch(source, function () {})
}
})
const root = nodeOps.createElement('div')
createApp(Comp).mount(root)
expect(instance).toBeDefined()
expect(source).toHaveBeenCalledWith(instance)
})
test('should not leak `this.proxy` to setup()', () => {
const source = jest.fn()
const Comp = defineComponent({
render() {},
setup() {
watch(source, () => {})
}
})
const root = nodeOps.createElement('div')
createApp(Comp).mount(root)
// should not have any arguments
expect(source.mock.calls[0]).toMatchObject([])
})
// #2728
test('pre watcher callbacks should not track dependencies', async () => {
const a = ref(0)
const b = ref(0)
const updated = jest.fn()
const Child = defineComponent({
props: ['a'],
updated,
watch: {
a() {
b.value
}
},
render() {
return h('div', this.a)
}
})
const Parent = defineComponent({
render() {
return h(Child, { a: a.value })
}
})
const root = nodeOps.createElement('div')
createApp(Parent).mount(root)
a.value++
await nextTick()
expect(updated).toHaveBeenCalledTimes(1)
b.value++
await nextTick()
// should not track b as dependency of Child
expect(updated).toHaveBeenCalledTimes(1)
})
test('watching keypath', async () => {
const spy = jest.fn()
const Comp = defineComponent({
render() {},
data() {
return {
a: {
b: 1
}
}
},
watch: {
'a.b': spy
},
created(this: any) {
this.$watch('a.b', spy)
},
mounted(this: any) {
this.a.b++
}
})
const root = nodeOps.createElement('div')
createApp(Comp).mount(root)
await nextTick()
expect(spy).toHaveBeenCalledTimes(2)
})
it('watching sources: ref<any[]>', async () => {
const foo = ref([1])
const spy = jest.fn()
watch(foo, () => {
spy()
})
foo.value = foo.value.slice()
await nextTick()
expect(spy).toBeCalledTimes(1)
})
it('watching multiple sources: computed', async () => {
let count = 0
const value = ref('1')
const plus = computed(() => !!value.value)
watch([plus], () => {
count++
})
value.value = '2'
await nextTick()
expect(plus.value).toBe(true)
expect(count).toBe(0)
})
// #4158
test('watch should not register in owner component if created inside detached scope', () => {
let instance: ComponentInternalInstance
const Comp = {
setup() {
instance = getCurrentInstance()!
effectScope(true).run(() => {
watch(
() => 1,
() => {}
)
})
return () => ''
}
}
const root = nodeOps.createElement('div')
createApp(Comp).mount(root)
// should not record watcher in detached scope and only the instance's
// own update effect
expect(instance!.scope.effects.length).toBe(1)
})
})
| packages/runtime-core/__tests__/apiWatch.spec.ts | 0 | https://github.com/vuejs/core/commit/7c4e4514d166b2fcb055baa091a79d9244458ab5 | [
0.001468628877773881,
0.00020644284086301923,
0.0001652969658607617,
0.00017463498807046562,
0.00016332886298187077
] |
{
"id": 3,
"code_window": [
"export function onScopeDispose(fn: () => void) {\n",
" if (activeEffectScope) {\n",
" activeEffectScope.cleanups.push(fn)\n",
" } else if (__DEV__) {\n",
" warn(\n",
" `onDispose() is called when there is no active effect scope` +\n",
" ` to be associated with.`\n",
" )\n",
" }\n",
"}"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" `onScopeDispose() is called when there is no active effect scope` +\n"
],
"file_path": "packages/reactivity/src/effectScope.ts",
"type": "replace",
"edit_start_line_idx": 100
} | dist
.DS_Store
node_modules
coverage
temp
explorations
TODOs.md
*.log
| .gitignore | 0 | https://github.com/vuejs/core/commit/7c4e4514d166b2fcb055baa091a79d9244458ab5 | [
0.00017446729179937392,
0.00017446729179937392,
0.00017446729179937392,
0.00017446729179937392,
0
] |
{
"id": 3,
"code_window": [
"export function onScopeDispose(fn: () => void) {\n",
" if (activeEffectScope) {\n",
" activeEffectScope.cleanups.push(fn)\n",
" } else if (__DEV__) {\n",
" warn(\n",
" `onDispose() is called when there is no active effect scope` +\n",
" ` to be associated with.`\n",
" )\n",
" }\n",
"}"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" `onScopeDispose() is called when there is no active effect scope` +\n"
],
"file_path": "packages/reactivity/src/effectScope.ts",
"type": "replace",
"edit_start_line_idx": 100
} | <script src="../../../../node_modules/lodash/lodash.min.js"></script>
<script src="../../dist/vue.global.js"></script>
<div id="app">
<button @click="insert">insert at random index</button>
<button @click="reset">reset</button>
<button @click="shuffle">shuffle</button>
<transition-group tag="ul" name="fade" class="container">
<item v-for="item in items"
class="item"
:msg="item"
:key="item"
@rm="remove(item)">
</item>
</transition-group>
</div>
<script>
const getInitialItems = () => [1, 2, 3, 4, 5]
let id = getInitialItems().length + 1
const Item = {
props: ['msg'],
template: `<div>{{ msg }} <button @click="$emit('rm')">x</button></div>`
}
Vue.createApp({
components: {
Item
},
data() {
return {
items: getInitialItems()
}
},
methods: {
insert () {
const i = Math.round(Math.random() * this.items.length)
this.items.splice(i, 0, id++)
},
reset () {
this.items = getInitialItems()
},
shuffle () {
this.items = _.shuffle(this.items)
},
remove (item) {
const i = this.items.indexOf(item)
if (i > -1) {
this.items.splice(i, 1)
}
}
}
}).mount('#app')
</script>
<style>
.container {
position: relative;
padding: 0;
}
.item {
width: 100%;
height: 30px;
background-color: #f3f3f3;
border: 1px solid #666;
box-sizing: border-box;
}
/* 1. declare transition */
.fade-move, .fade-enter-active, .fade-leave-active {
transition: all .5s cubic-bezier(.55,0,.1,1);
}
/* 2. declare enter from and leave to state */
.fade-enter-from, .fade-leave-to {
opacity: 0;
transform: scaleY(0.01) translate(30px, 0);
}
/* 3. ensure leaving items are taken out of layout flow so that moving
animations can be calculated correctly. */
.fade-leave-active {
position: absolute;
}
</style>
| packages/vue/examples/transition/list.html | 0 | https://github.com/vuejs/core/commit/7c4e4514d166b2fcb055baa091a79d9244458ab5 | [
0.00017581899010110646,
0.0001735380501486361,
0.0001702287991065532,
0.00017463073891121894,
0.0000019002650333277415
] |
{
"id": 0,
"code_window": [
"import { IFileDialogService } from 'vs/platform/dialogs/common/dialogs';\n",
"import { INotificationService } from 'vs/platform/notification/common/notification';\n",
"import { Schemas } from 'vs/base/common/network';\n",
"import { IWorkbenchEnvironmentService } from 'vs/workbench/services/environment/common/environmentService';\n",
"\n",
"export class OpenFileAction extends Action {\n",
"\n",
"\tstatic readonly ID = 'workbench.action.files.openFile';\n",
"\tstatic LABEL = nls.localize('openFile', \"Open File...\");\n"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"import { ITextFileService, ISaveOptions } from 'vs/workbench/services/textfile/common/textfiles';\n",
"import { toResource } from 'vs/workbench/common/editor';\n",
"import { URI } from 'vs/base/common/uri';\n"
],
"file_path": "src/vs/workbench/browser/actions/workspaceActions.ts",
"type": "add",
"edit_start_line_idx": 19
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import { Action } from 'vs/base/common/actions';
import * as nls from 'vs/nls';
import { IWindowService } from 'vs/platform/windows/common/windows';
import { ITelemetryData } from 'vs/platform/telemetry/common/telemetry';
import { IWorkspaceContextService, WorkbenchState, IWorkspaceFolder } from 'vs/platform/workspace/common/workspace';
import { IWorkspaceEditingService } from 'vs/workbench/services/workspace/common/workspaceEditing';
import { IWorkspacesService } from 'vs/platform/workspaces/common/workspaces';
import { IEditorService } from 'vs/workbench/services/editor/common/editorService';
import { ICommandService } from 'vs/platform/commands/common/commands';
import { ADD_ROOT_FOLDER_COMMAND_ID, ADD_ROOT_FOLDER_LABEL, PICK_WORKSPACE_FOLDER_COMMAND_ID } from 'vs/workbench/browser/actions/workspaceCommands';
import { IFileDialogService } from 'vs/platform/dialogs/common/dialogs';
import { INotificationService } from 'vs/platform/notification/common/notification';
import { Schemas } from 'vs/base/common/network';
import { IWorkbenchEnvironmentService } from 'vs/workbench/services/environment/common/environmentService';
export class OpenFileAction extends Action {
static readonly ID = 'workbench.action.files.openFile';
static LABEL = nls.localize('openFile', "Open File...");
constructor(
id: string,
label: string,
@IFileDialogService private readonly dialogService: IFileDialogService
) {
super(id, label);
}
run(event?: any, data?: ITelemetryData): Promise<any> {
return this.dialogService.pickFileAndOpen({ forceNewWindow: false, telemetryExtraData: data });
}
}
export class OpenLocalFileAction extends Action {
static readonly ID = 'workbench.action.files.openLocalFile';
static LABEL = nls.localize('openLocalFile', "Open Local File...");
constructor(
id: string,
label: string,
@IFileDialogService private readonly dialogService: IFileDialogService
) {
super(id, label);
}
run(event?: any, data?: ITelemetryData): Promise<any> {
return this.dialogService.pickFileAndOpen({ forceNewWindow: false, telemetryExtraData: data, availableFileSystems: [Schemas.file] });
}
}
export class SaveLocalFileAction extends Action {
static readonly ID = 'workbench.action.files.saveLocalFile';
static LABEL = nls.localize('saveLocalFile', "Save Local File...");
constructor(
id: string,
label: string,
@IFileDialogService private readonly dialogService: IFileDialogService
) {
super(id, label);
}
run(event?: any, data?: ITelemetryData): Promise<any> {
return this.dialogService.pickFileToSave({ availableFileSystems: [Schemas.file] });
}
}
export class OpenFolderAction extends Action {
static readonly ID = 'workbench.action.files.openFolder';
static LABEL = nls.localize('openFolder', "Open Folder...");
constructor(
id: string,
label: string,
@IFileDialogService private readonly dialogService: IFileDialogService
) {
super(id, label);
}
run(event?: any, data?: ITelemetryData): Promise<any> {
return this.dialogService.pickFolderAndOpen({ forceNewWindow: false, telemetryExtraData: data });
}
}
export class OpenLocalFolderAction extends Action {
static readonly ID = 'workbench.action.files.openLocalFolder';
static LABEL = nls.localize('openLocalFolder', "Open Local Folder...");
constructor(
id: string,
label: string,
@IFileDialogService private readonly dialogService: IFileDialogService
) {
super(id, label);
}
run(event?: any, data?: ITelemetryData): Promise<any> {
return this.dialogService.pickFolderAndOpen({ forceNewWindow: false, telemetryExtraData: data, availableFileSystems: [Schemas.file] });
}
}
export class OpenFileFolderAction extends Action {
static readonly ID = 'workbench.action.files.openFileFolder';
static LABEL = nls.localize('openFileFolder', "Open...");
constructor(
id: string,
label: string,
@IFileDialogService private readonly dialogService: IFileDialogService
) {
super(id, label);
}
run(event?: any, data?: ITelemetryData): Promise<any> {
return this.dialogService.pickFileFolderAndOpen({ forceNewWindow: false, telemetryExtraData: data });
}
}
export class OpenLocalFileFolderAction extends Action {
static readonly ID = 'workbench.action.files.openLocalFileFolder';
static LABEL = nls.localize('openLocalFileFolder', "Open Local...");
constructor(
id: string,
label: string,
@IFileDialogService private readonly dialogService: IFileDialogService
) {
super(id, label);
}
run(event?: any, data?: ITelemetryData): Promise<any> {
return this.dialogService.pickFileFolderAndOpen({ forceNewWindow: false, telemetryExtraData: data, availableFileSystems: [Schemas.file] });
}
}
export class AddRootFolderAction extends Action {
static readonly ID = 'workbench.action.addRootFolder';
static LABEL = ADD_ROOT_FOLDER_LABEL;
constructor(
id: string,
label: string,
@ICommandService private readonly commandService: ICommandService
) {
super(id, label);
}
run(): Promise<any> {
return this.commandService.executeCommand(ADD_ROOT_FOLDER_COMMAND_ID);
}
}
export class GlobalRemoveRootFolderAction extends Action {
static readonly ID = 'workbench.action.removeRootFolder';
static LABEL = nls.localize('globalRemoveFolderFromWorkspace', "Remove Folder from Workspace...");
constructor(
id: string,
label: string,
@IWorkspaceEditingService private readonly workspaceEditingService: IWorkspaceEditingService,
@IWorkspaceContextService private readonly contextService: IWorkspaceContextService,
@ICommandService private readonly commandService: ICommandService
) {
super(id, label);
}
async run(): Promise<any> {
const state = this.contextService.getWorkbenchState();
// Workspace / Folder
if (state === WorkbenchState.WORKSPACE || state === WorkbenchState.FOLDER) {
const folder = await this.commandService.executeCommand<IWorkspaceFolder>(PICK_WORKSPACE_FOLDER_COMMAND_ID);
if (folder) {
await this.workspaceEditingService.removeFolders([folder.uri]);
}
}
return true;
}
}
export class SaveWorkspaceAsAction extends Action {
static readonly ID = 'workbench.action.saveWorkspaceAs';
static LABEL = nls.localize('saveWorkspaceAsAction', "Save Workspace As...");
constructor(
id: string,
label: string,
@IWorkspaceContextService private readonly contextService: IWorkspaceContextService,
@IWorkspaceEditingService private readonly workspaceEditingService: IWorkspaceEditingService
) {
super(id, label);
}
async run(): Promise<any> {
const configPathUri = await this.workspaceEditingService.pickNewWorkspacePath();
if (configPathUri) {
switch (this.contextService.getWorkbenchState()) {
case WorkbenchState.EMPTY:
case WorkbenchState.FOLDER:
const folders = this.contextService.getWorkspace().folders.map(folder => ({ uri: folder.uri }));
return this.workspaceEditingService.createAndEnterWorkspace(folders, configPathUri);
case WorkbenchState.WORKSPACE:
return this.workspaceEditingService.saveAndEnterWorkspace(configPathUri);
}
}
}
}
export class OpenWorkspaceAction extends Action {
static readonly ID = 'workbench.action.openWorkspace';
static LABEL = nls.localize('openWorkspaceAction', "Open Workspace...");
constructor(
id: string,
label: string,
@IFileDialogService private readonly dialogService: IFileDialogService
) {
super(id, label);
}
run(event?: any, data?: ITelemetryData): Promise<any> {
return this.dialogService.pickWorkspaceAndOpen({ telemetryExtraData: data });
}
}
export class CloseWorkspaceAction extends Action {
static readonly ID = 'workbench.action.closeFolder';
static LABEL = nls.localize('closeWorkspace', "Close Workspace");
constructor(
id: string,
label: string,
@IWorkspaceContextService private readonly contextService: IWorkspaceContextService,
@INotificationService private readonly notificationService: INotificationService,
@IWindowService private readonly windowService: IWindowService
) {
super(id, label);
}
run(): Promise<void> {
if (this.contextService.getWorkbenchState() === WorkbenchState.EMPTY) {
this.notificationService.info(nls.localize('noWorkspaceOpened', "There is currently no workspace opened in this instance to close."));
return Promise.resolve(undefined);
}
return this.windowService.closeWorkspace();
}
}
export class OpenWorkspaceConfigFileAction extends Action {
static readonly ID = 'workbench.action.openWorkspaceConfigFile';
static readonly LABEL = nls.localize('openWorkspaceConfigFile', "Open Workspace Configuration File");
constructor(
id: string,
label: string,
@IWorkspaceContextService private readonly workspaceContextService: IWorkspaceContextService,
@IEditorService private readonly editorService: IEditorService
) {
super(id, label);
this.enabled = !!this.workspaceContextService.getWorkspace().configuration;
}
run(): Promise<any> {
const configuration = this.workspaceContextService.getWorkspace().configuration;
if (configuration) {
return this.editorService.openEditor({ resource: configuration });
}
return Promise.resolve();
}
}
export class DuplicateWorkspaceInNewWindowAction extends Action {
static readonly ID = 'workbench.action.duplicateWorkspaceInNewWindow';
static readonly LABEL = nls.localize('duplicateWorkspaceInNewWindow', "Duplicate Workspace in New Window");
constructor(
id: string,
label: string,
@IWorkspaceContextService private readonly workspaceContextService: IWorkspaceContextService,
@IWorkspaceEditingService private readonly workspaceEditingService: IWorkspaceEditingService,
@IWindowService private readonly windowService: IWindowService,
@IWorkspacesService private readonly workspacesService: IWorkspacesService,
@IWorkbenchEnvironmentService private readonly environmentService: IWorkbenchEnvironmentService
) {
super(id, label);
}
async run(): Promise<any> {
const folders = this.workspaceContextService.getWorkspace().folders;
const remoteAuthority = this.environmentService.configuration.remoteAuthority;
const newWorkspace = await this.workspacesService.createUntitledWorkspace(folders, remoteAuthority);
await this.workspaceEditingService.copyWorkspaceSettings(newWorkspace);
return this.windowService.openWindow([{ workspaceUri: newWorkspace.configPath }], { forceNewWindow: true });
}
}
| src/vs/workbench/browser/actions/workspaceActions.ts | 1 | https://github.com/microsoft/vscode/commit/985de26b3446636f86e2bb2b14dbeb9ec1e33207 | [
0.997576892375946,
0.1690661907196045,
0.00016516147297807038,
0.003323317039757967,
0.3381706476211548
] |
{
"id": 0,
"code_window": [
"import { IFileDialogService } from 'vs/platform/dialogs/common/dialogs';\n",
"import { INotificationService } from 'vs/platform/notification/common/notification';\n",
"import { Schemas } from 'vs/base/common/network';\n",
"import { IWorkbenchEnvironmentService } from 'vs/workbench/services/environment/common/environmentService';\n",
"\n",
"export class OpenFileAction extends Action {\n",
"\n",
"\tstatic readonly ID = 'workbench.action.files.openFile';\n",
"\tstatic LABEL = nls.localize('openFile', \"Open File...\");\n"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"import { ITextFileService, ISaveOptions } from 'vs/workbench/services/textfile/common/textfiles';\n",
"import { toResource } from 'vs/workbench/common/editor';\n",
"import { URI } from 'vs/base/common/uri';\n"
],
"file_path": "src/vs/workbench/browser/actions/workspaceActions.ts",
"type": "add",
"edit_start_line_idx": 19
} | <svg width="16" height="16" viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg">
<g clip-path="url(#clip0)">
<path d="M6 13C6 13.3956 6.1173 13.7822 6.33706 14.1111C6.55682 14.44 6.86918 14.6964 7.23463 14.8478C7.60008 14.9991 8.00222 15.0387 8.39018 14.9616C8.77814 14.8844 9.13451 14.6939 9.41421 14.4142C9.69392 14.1345 9.8844 13.7781 9.96157 13.3902C10.0387 13.0022 9.99913 12.6001 9.84776 12.2346C9.69638 11.8692 9.44004 11.5568 9.11114 11.3371C8.78224 11.1173 8.39556 11 8 11C7.46957 11 6.96086 11.2107 6.58579 11.5858C6.21071 11.9609 6 12.4696 6 13Z" fill="#C5C5C5"/>
<path d="M0.999998 2V8H7V6H4.763C5.27303 5.23323 6.00693 4.64224 6.86481 4.30742C7.72269 3.97261 8.6629 3.91024 9.55749 4.12881C10.4521 4.34737 11.2576 4.83626 11.8644 5.52893C12.4713 6.22161 12.85 7.08443 12.949 8H14.975C14.8733 6.6352 14.3422 5.3376 13.4579 4.29312C12.5736 3.24863 11.3813 2.51086 10.052 2.18549C8.72262 1.86012 7.3244 1.96385 6.05763 2.48183C4.79085 2.99981 3.72053 3.90545 3 5.069V2H0.999998Z" fill="#75BEFF"/>
</g>
<defs>
<clipPath id="clip0">
<rect width="16" height="16" fill="white" transform="matrix(-1 0 0 1 16 0)"/>
</clipPath>
</defs>
</svg>
| src/vs/workbench/contrib/debug/browser/media/step-back-inverse.svg | 0 | https://github.com/microsoft/vscode/commit/985de26b3446636f86e2bb2b14dbeb9ec1e33207 | [
0.0008444093982689083,
0.0005082701682113111,
0.00017213095270562917,
0.0005082701682113111,
0.00033613923005759716
] |
{
"id": 0,
"code_window": [
"import { IFileDialogService } from 'vs/platform/dialogs/common/dialogs';\n",
"import { INotificationService } from 'vs/platform/notification/common/notification';\n",
"import { Schemas } from 'vs/base/common/network';\n",
"import { IWorkbenchEnvironmentService } from 'vs/workbench/services/environment/common/environmentService';\n",
"\n",
"export class OpenFileAction extends Action {\n",
"\n",
"\tstatic readonly ID = 'workbench.action.files.openFile';\n",
"\tstatic LABEL = nls.localize('openFile', \"Open File...\");\n"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"import { ITextFileService, ISaveOptions } from 'vs/workbench/services/textfile/common/textfiles';\n",
"import { toResource } from 'vs/workbench/common/editor';\n",
"import { URI } from 'vs/base/common/uri';\n"
],
"file_path": "src/vs/workbench/browser/actions/workspaceActions.ts",
"type": "add",
"edit_start_line_idx": 19
} | {
"name": "vs/base",
"dependencies": [
{
"name": "vs",
"internal": false
}
],
"libs": [
"lib.core.d.ts"
],
"sources": [
"**/*.ts"
],
"declares": []
}
| src/vs/base/common/buildunit.json | 0 | https://github.com/microsoft/vscode/commit/985de26b3446636f86e2bb2b14dbeb9ec1e33207 | [
0.0001717407867545262,
0.0001708325871732086,
0.00016992440214380622,
0.0001708325871732086,
9.081923053599894e-7
] |
{
"id": 0,
"code_window": [
"import { IFileDialogService } from 'vs/platform/dialogs/common/dialogs';\n",
"import { INotificationService } from 'vs/platform/notification/common/notification';\n",
"import { Schemas } from 'vs/base/common/network';\n",
"import { IWorkbenchEnvironmentService } from 'vs/workbench/services/environment/common/environmentService';\n",
"\n",
"export class OpenFileAction extends Action {\n",
"\n",
"\tstatic readonly ID = 'workbench.action.files.openFile';\n",
"\tstatic LABEL = nls.localize('openFile', \"Open File...\");\n"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"import { ITextFileService, ISaveOptions } from 'vs/workbench/services/textfile/common/textfiles';\n",
"import { toResource } from 'vs/workbench/common/editor';\n",
"import { URI } from 'vs/base/common/uri';\n"
],
"file_path": "src/vs/workbench/browser/actions/workspaceActions.ts",
"type": "add",
"edit_start_line_idx": 19
} | {
"prettier.semi": true,
"prettier.singleQuote": true,
"prettier.printWidth": 120,
} | extensions/css-language-features/.vscode/settings.json | 0 | https://github.com/microsoft/vscode/commit/985de26b3446636f86e2bb2b14dbeb9ec1e33207 | [
0.0001748600188875571,
0.0001748600188875571,
0.0001748600188875571,
0.0001748600188875571,
0
] |
{
"id": 1,
"code_window": [
"\tstatic LABEL = nls.localize('saveLocalFile', \"Save Local File...\");\n",
"\n",
"\tconstructor(\n",
"\t\tid: string,\n",
"\t\tlabel: string,\n",
"\t\t@IFileDialogService private readonly dialogService: IFileDialogService\n",
"\t) {\n",
"\t\tsuper(id, label);\n",
"\t}\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\t@ITextFileService private readonly textFileService: ITextFileService,\n",
"\t\t@IEditorService private readonly editorService: IEditorService\n"
],
"file_path": "src/vs/workbench/browser/actions/workspaceActions.ts",
"type": "replace",
"edit_start_line_idx": 64
} | /*---------------------------------------------------------------------------------------------
* 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 resources from 'vs/base/common/resources';
import * as objects from 'vs/base/common/objects';
import { IFileService, IFileStat, FileKind } from 'vs/platform/files/common/files';
import { IQuickInputService, IQuickPickItem, IQuickPick } from 'vs/platform/quickinput/common/quickInput';
import { URI } from 'vs/base/common/uri';
import { isWindows, OperatingSystem } from 'vs/base/common/platform';
import { ISaveDialogOptions, IOpenDialogOptions, IFileDialogService } from 'vs/platform/dialogs/common/dialogs';
import { REMOTE_HOST_SCHEME } from 'vs/platform/remote/common/remoteHosts';
import { ILabelService } from 'vs/platform/label/common/label';
import { IWorkspaceContextService } from 'vs/platform/workspace/common/workspace';
import { INotificationService } from 'vs/platform/notification/common/notification';
import { IModelService } from 'vs/editor/common/services/modelService';
import { IModeService } from 'vs/editor/common/services/modeService';
import { getIconClasses } from 'vs/editor/common/services/getIconClasses';
import { Schemas } from 'vs/base/common/network';
import { IWorkbenchEnvironmentService } from 'vs/workbench/services/environment/common/environmentService';
import { IRemoteAgentService } from 'vs/workbench/services/remote/common/remoteAgentService';
import { IContextKeyService, IContextKey } from 'vs/platform/contextkey/common/contextkey';
import { equalsIgnoreCase, format, startsWithIgnoreCase } from 'vs/base/common/strings';
import { OpenLocalFileAction, OpenLocalFileFolderAction, OpenLocalFolderAction, SaveLocalFileAction } from 'vs/workbench/browser/actions/workspaceActions';
import { IKeybindingService } from 'vs/platform/keybinding/common/keybinding';
import { IRemoteAgentEnvironment } from 'vs/platform/remote/common/remoteAgentEnvironment';
import { isValidBasename } from 'vs/base/common/extpath';
import { RemoteFileDialogContext } from 'vs/workbench/browser/contextkeys';
import { Emitter } from 'vs/base/common/event';
import { IDisposable, dispose } from 'vs/base/common/lifecycle';
interface FileQuickPickItem extends IQuickPickItem {
uri: URI;
isFolder: boolean;
}
enum UpdateResult {
Updated,
Updating,
NotUpdated,
InvalidPath
}
export class RemoteFileDialog {
private options: IOpenDialogOptions;
private currentFolder: URI;
private filePickBox: IQuickPick<FileQuickPickItem>;
private hidden: boolean;
private allowFileSelection: boolean;
private allowFolderSelection: boolean;
private remoteAuthority: string | undefined;
private requiresTrailing: boolean;
private trailing: string | undefined;
private scheme: string = REMOTE_HOST_SCHEME;
private contextKey: IContextKey<boolean>;
private userEnteredPathSegment: string;
private autoCompletePathSegment: string;
private activeItem: FileQuickPickItem;
private userHome: URI;
private badPath: string | undefined;
private remoteAgentEnvironment: IRemoteAgentEnvironment | null;
private separator: string;
private onBusyChangeEmitter = new Emitter<boolean>();
protected disposables: IDisposable[] = [
this.onBusyChangeEmitter
];
constructor(
@IFileService private readonly fileService: IFileService,
@IQuickInputService private readonly quickInputService: IQuickInputService,
@ILabelService private readonly labelService: ILabelService,
@IWorkspaceContextService private readonly workspaceContextService: IWorkspaceContextService,
@INotificationService private readonly notificationService: INotificationService,
@IFileDialogService private readonly fileDialogService: IFileDialogService,
@IModelService private readonly modelService: IModelService,
@IModeService private readonly modeService: IModeService,
@IWorkbenchEnvironmentService private readonly environmentService: IWorkbenchEnvironmentService,
@IRemoteAgentService private readonly remoteAgentService: IRemoteAgentService,
@IKeybindingService private readonly keybindingService: IKeybindingService,
@IContextKeyService contextKeyService: IContextKeyService,
) {
this.remoteAuthority = this.environmentService.configuration.remoteAuthority;
this.contextKey = RemoteFileDialogContext.bindTo(contextKeyService);
}
set busy(busy: boolean) {
if (this.filePickBox.busy !== busy) {
this.filePickBox.busy = busy;
this.onBusyChangeEmitter.fire(busy);
}
}
get busy(): boolean {
return this.filePickBox.busy;
}
public async showOpenDialog(options: IOpenDialogOptions = {}): Promise<URI | undefined> {
this.scheme = this.getScheme(options.defaultUri, options.availableFileSystems);
this.userHome = await this.getUserHome();
const newOptions = await this.getOptions(options);
if (!newOptions) {
return Promise.resolve(undefined);
}
this.options = newOptions;
return this.pickResource();
}
public async showSaveDialog(options: ISaveDialogOptions): Promise<URI | undefined> {
this.scheme = this.getScheme(options.defaultUri, options.availableFileSystems);
this.userHome = await this.getUserHome();
this.requiresTrailing = true;
const newOptions = await this.getOptions(options, true);
if (!newOptions) {
return Promise.resolve(undefined);
}
this.options = newOptions;
this.options.canSelectFolders = true;
this.options.canSelectFiles = true;
return new Promise<URI | undefined>((resolve) => {
this.pickResource(true).then(folderUri => {
resolve(folderUri);
});
});
}
private getOptions(options: ISaveDialogOptions | IOpenDialogOptions, isSave: boolean = false): IOpenDialogOptions | undefined {
let defaultUri = options.defaultUri;
const filename = (defaultUri && isSave && (resources.dirname(defaultUri).path === '/')) ? resources.basename(defaultUri) : undefined;
if (!defaultUri || filename) {
defaultUri = this.userHome;
if (filename) {
defaultUri = resources.joinPath(defaultUri, filename);
}
}
if ((this.scheme !== Schemas.file) && !this.fileService.canHandleResource(defaultUri)) {
this.notificationService.info(nls.localize('remoteFileDialog.notConnectedToRemote', 'File system provider for {0} is not available.', defaultUri.toString()));
return undefined;
}
const newOptions: IOpenDialogOptions = objects.deepClone(options);
newOptions.defaultUri = defaultUri;
return newOptions;
}
private remoteUriFrom(path: string): URI {
path = path.replace(/\\/g, '/');
return resources.toLocalResource(URI.from({ scheme: this.scheme, path }), this.scheme === Schemas.file ? undefined : this.remoteAuthority);
}
private getScheme(defaultUri: URI | undefined, available: string[] | undefined): string {
return defaultUri ? defaultUri.scheme : (available ? available[0] : Schemas.file);
}
private async getRemoteAgentEnvironment(): Promise<IRemoteAgentEnvironment | null> {
if (this.remoteAgentEnvironment === undefined) {
this.remoteAgentEnvironment = await this.remoteAgentService.getEnvironment();
}
return this.remoteAgentEnvironment;
}
private async getUserHome(): Promise<URI> {
if (this.scheme !== Schemas.file) {
const env = await this.getRemoteAgentEnvironment();
if (env) {
return env.userHome;
}
}
return URI.from({ scheme: this.scheme, path: this.environmentService.userHome });
}
private async pickResource(isSave: boolean = false): Promise<URI | undefined> {
this.allowFolderSelection = !!this.options.canSelectFolders;
this.allowFileSelection = !!this.options.canSelectFiles;
this.separator = this.labelService.getSeparator(this.scheme, this.remoteAuthority);
this.hidden = false;
let homedir: URI = this.options.defaultUri ? this.options.defaultUri : this.workspaceContextService.getWorkspace().folders[0].uri;
let stat: IFileStat | undefined;
let ext: string = resources.extname(homedir);
if (this.options.defaultUri) {
try {
stat = await this.fileService.resolve(this.options.defaultUri);
} catch (e) {
// The file or folder doesn't exist
}
if (!stat || !stat.isDirectory) {
homedir = resources.dirname(this.options.defaultUri);
this.trailing = resources.basename(this.options.defaultUri);
}
// append extension
if (isSave && !ext && this.options.filters) {
for (let i = 0; i < this.options.filters.length; i++) {
if (this.options.filters[i].extensions[0] !== '*') {
ext = '.' + this.options.filters[i].extensions[0];
this.trailing = this.trailing ? this.trailing + ext : ext;
break;
}
}
}
}
return new Promise<URI | undefined>(async (resolve) => {
this.filePickBox = this.quickInputService.createQuickPick<FileQuickPickItem>();
this.busy = true;
this.filePickBox.matchOnLabel = false;
this.filePickBox.autoFocusOnList = false;
this.filePickBox.ignoreFocusOut = true;
this.filePickBox.ok = true;
if (this.options && this.options.availableFileSystems && (this.options.availableFileSystems.length > 1)) {
this.filePickBox.customButton = true;
this.filePickBox.customLabel = nls.localize('remoteFileDialog.local', 'Show Local');
let action;
if (isSave) {
action = SaveLocalFileAction;
} else {
action = this.allowFileSelection ? (this.allowFolderSelection ? OpenLocalFileFolderAction : OpenLocalFileAction) : OpenLocalFolderAction;
}
const keybinding = this.keybindingService.lookupKeybinding(action.ID);
if (keybinding) {
const label = keybinding.getLabel();
if (label) {
this.filePickBox.customHover = format('{0} ({1})', action.LABEL, label);
}
}
}
let isResolving: number = 0;
let isAcceptHandled = false;
this.currentFolder = homedir;
this.userEnteredPathSegment = '';
this.autoCompletePathSegment = '';
this.filePickBox.title = this.options.title;
this.filePickBox.value = this.pathFromUri(this.currentFolder, true);
this.filePickBox.valueSelection = [this.filePickBox.value.length, this.filePickBox.value.length];
this.filePickBox.items = [];
function doResolve(dialog: RemoteFileDialog, uri: URI | undefined) {
resolve(uri);
dialog.contextKey.set(false);
dialog.filePickBox.dispose();
dispose(dialog.disposables);
}
this.filePickBox.onDidCustom(() => {
if (isAcceptHandled || this.busy) {
return;
}
isAcceptHandled = true;
isResolving++;
if (this.options.availableFileSystems && (this.options.availableFileSystems.length > 1)) {
this.options.availableFileSystems.shift();
}
this.options.defaultUri = undefined;
this.filePickBox.hide();
if (isSave) {
// Remove defaultUri and filters to get a consistant experience with the keybinding.
this.options.defaultUri = undefined;
this.options.filters = undefined;
return this.fileDialogService.showSaveDialog(this.options).then(result => {
doResolve(this, result);
});
} else {
return this.fileDialogService.showOpenDialog(this.options).then(result => {
doResolve(this, result ? result[0] : undefined);
});
}
});
function handleAccept(dialog: RemoteFileDialog) {
if (dialog.busy) {
// Save the accept until the file picker is not busy.
dialog.onBusyChangeEmitter.event((busy: boolean) => {
if (!busy) {
handleAccept(dialog);
}
});
return;
} else if (isAcceptHandled) {
return;
}
isAcceptHandled = true;
isResolving++;
dialog.onDidAccept().then(resolveValue => {
if (resolveValue) {
dialog.filePickBox.hide();
doResolve(dialog, resolveValue);
} else if (dialog.hidden) {
doResolve(dialog, undefined);
} else {
isResolving--;
isAcceptHandled = false;
}
});
}
this.filePickBox.onDidAccept(_ => {
handleAccept(this);
});
this.filePickBox.onDidChangeActive(i => {
isAcceptHandled = false;
// update input box to match the first selected item
if ((i.length === 1) && this.isChangeFromUser()) {
this.filePickBox.validationMessage = undefined;
this.setAutoComplete(this.constructFullUserPath(), this.userEnteredPathSegment, i[0], true);
}
});
this.filePickBox.onDidChangeValue(async value => {
try {
// onDidChangeValue can also be triggered by the auto complete, so if it looks like the auto complete, don't do anything
if (this.isChangeFromUser()) {
// If the user has just entered more bad path, don't change anything
if (!equalsIgnoreCase(value, this.constructFullUserPath()) && !this.isBadSubpath(value)) {
this.filePickBox.validationMessage = undefined;
const filePickBoxUri = this.filePickBoxValue();
let updated: UpdateResult = UpdateResult.NotUpdated;
if (!resources.isEqual(this.currentFolder, filePickBoxUri, true)) {
updated = await this.tryUpdateItems(value, filePickBoxUri);
}
if (updated === UpdateResult.NotUpdated) {
this.setActiveItems(value);
}
} else {
this.filePickBox.activeItems = [];
}
}
} catch {
// Since any text can be entered in the input box, there is potential for error causing input. If this happens, do nothing.
}
});
this.filePickBox.onDidHide(() => {
this.hidden = true;
if (isResolving === 0) {
doResolve(this, undefined);
}
});
this.filePickBox.show();
this.contextKey.set(true);
await this.updateItems(homedir, true, this.trailing);
if (this.trailing) {
this.filePickBox.valueSelection = [this.filePickBox.value.length - this.trailing.length, this.filePickBox.value.length - ext.length];
} else {
this.filePickBox.valueSelection = [this.filePickBox.value.length, this.filePickBox.value.length];
}
this.busy = false;
});
}
private isBadSubpath(value: string) {
return this.badPath && (value.length > this.badPath.length) && equalsIgnoreCase(value.substring(0, this.badPath.length), this.badPath);
}
private isChangeFromUser(): boolean {
if (equalsIgnoreCase(this.filePickBox.value, this.pathAppend(this.currentFolder, this.userEnteredPathSegment + this.autoCompletePathSegment))
&& (this.activeItem === (this.filePickBox.activeItems ? this.filePickBox.activeItems[0] : undefined))) {
return false;
}
return true;
}
private constructFullUserPath(): string {
return this.pathAppend(this.currentFolder, this.userEnteredPathSegment);
}
private filePickBoxValue(): URI {
// The file pick box can't render everything, so we use the current folder to create the uri so that it is an existing path.
const directUri = this.remoteUriFrom(this.filePickBox.value);
const currentPath = this.pathFromUri(this.currentFolder);
if (equalsIgnoreCase(this.filePickBox.value, currentPath)) {
return this.currentFolder;
}
const currentDisplayUri = this.remoteUriFrom(currentPath);
const relativePath = resources.relativePath(currentDisplayUri, directUri);
const isSameRoot = (this.filePickBox.value.length > 1 && currentPath.length > 1) ? equalsIgnoreCase(this.filePickBox.value.substr(0, 2), currentPath.substr(0, 2)) : false;
if (relativePath && isSameRoot) {
const path = resources.joinPath(this.currentFolder, relativePath);
return resources.hasTrailingPathSeparator(directUri) ? resources.addTrailingPathSeparator(path) : path;
} else {
return directUri;
}
}
private async onDidAccept(): Promise<URI | undefined> {
this.busy = true;
if (this.filePickBox.activeItems.length === 1) {
const item = this.filePickBox.selectedItems[0];
if (item.isFolder) {
if (this.trailing) {
await this.updateItems(item.uri, true, this.trailing);
} else {
// When possible, cause the update to happen by modifying the input box.
// This allows all input box updates to happen first, and uses the same code path as the user typing.
const newPath = this.pathFromUri(item.uri);
if (startsWithIgnoreCase(newPath, this.filePickBox.value) && (equalsIgnoreCase(item.label, resources.basename(item.uri)))) {
this.filePickBox.valueSelection = [this.pathFromUri(this.currentFolder).length, this.filePickBox.value.length];
this.insertText(newPath, item.label);
} else if ((item.label === '..') && startsWithIgnoreCase(this.filePickBox.value, newPath)) {
this.filePickBox.valueSelection = [newPath.length, this.filePickBox.value.length];
this.insertText(newPath, '');
} else {
await this.updateItems(item.uri, true);
}
}
this.filePickBox.busy = false;
return;
}
} else {
// If the items have updated, don't try to resolve
if ((await this.tryUpdateItems(this.filePickBox.value, this.filePickBoxValue())) !== UpdateResult.NotUpdated) {
this.filePickBox.busy = false;
return;
}
}
let resolveValue: URI | undefined;
// Find resolve value
if (this.filePickBox.activeItems.length === 0) {
resolveValue = this.filePickBoxValue();
} else if (this.filePickBox.activeItems.length === 1) {
resolveValue = this.filePickBox.selectedItems[0].uri;
}
if (resolveValue) {
resolveValue = this.addPostfix(resolveValue);
}
if (await this.validate(resolveValue)) {
this.busy = false;
return resolveValue;
}
this.busy = false;
return undefined;
}
private async tryUpdateItems(value: string, valueUri: URI): Promise<UpdateResult> {
if ((value.length > 0) && ((value[value.length - 1] === '~') || (value[0] === '~'))) {
let newDir = this.userHome;
if ((value[0] === '~') && (value.length > 1)) {
newDir = resources.joinPath(newDir, value.substring(1));
}
await this.updateItems(newDir, true);
return UpdateResult.Updated;
} else if (!resources.isEqual(this.currentFolder, valueUri, true) && (this.endsWithSlash(value) || (!resources.isEqual(this.currentFolder, resources.dirname(valueUri), true) && resources.isEqualOrParent(this.currentFolder, resources.dirname(valueUri), true)))) {
let stat: IFileStat | undefined;
try {
stat = await this.fileService.resolve(valueUri);
} catch (e) {
// do nothing
}
if (stat && stat.isDirectory && (resources.basename(valueUri) !== '.') && this.endsWithSlash(value)) {
await this.updateItems(valueUri);
return UpdateResult.Updated;
} else if (this.endsWithSlash(value)) {
// The input box contains a path that doesn't exist on the system.
this.filePickBox.validationMessage = nls.localize('remoteFileDialog.badPath', 'The path does not exist.');
// Save this bad path. It can take too long to to a stat on every user entered character, but once a user enters a bad path they are likely
// to keep typing more bad path. We can compare against this bad path and see if the user entered path starts with it.
this.badPath = value;
return UpdateResult.InvalidPath;
} else {
const inputUriDirname = resources.dirname(valueUri);
if (!resources.isEqual(resources.removeTrailingPathSeparator(this.currentFolder), inputUriDirname, true)) {
let statWithoutTrailing: IFileStat | undefined;
try {
statWithoutTrailing = await this.fileService.resolve(inputUriDirname);
} catch (e) {
// do nothing
}
if (statWithoutTrailing && statWithoutTrailing.isDirectory && (resources.basename(valueUri) !== '.')) {
await this.updateItems(inputUriDirname, false, resources.basename(valueUri));
this.badPath = undefined;
return UpdateResult.Updated;
}
}
}
}
this.badPath = undefined;
return UpdateResult.NotUpdated;
}
private setActiveItems(value: string) {
const inputBasename = resources.basename(this.remoteUriFrom(value));
// Make sure that the folder whose children we are currently viewing matches the path in the input
const userPath = this.constructFullUserPath();
if (equalsIgnoreCase(userPath, value.substring(0, userPath.length))) {
let hasMatch = false;
for (let i = 0; i < this.filePickBox.items.length; i++) {
const item = <FileQuickPickItem>this.filePickBox.items[i];
if (this.setAutoComplete(value, inputBasename, item)) {
hasMatch = true;
break;
}
}
if (!hasMatch) {
this.userEnteredPathSegment = inputBasename;
this.autoCompletePathSegment = '';
this.filePickBox.activeItems = [];
}
} else {
if (!equalsIgnoreCase(inputBasename, resources.basename(this.currentFolder))) {
this.userEnteredPathSegment = inputBasename;
} else {
this.userEnteredPathSegment = '';
}
this.autoCompletePathSegment = '';
}
}
private setAutoComplete(startingValue: string, startingBasename: string, quickPickItem: FileQuickPickItem, force: boolean = false): boolean {
if (this.busy) {
// We're in the middle of something else. Doing an auto complete now can result jumbled or incorrect autocompletes.
this.userEnteredPathSegment = startingBasename;
this.autoCompletePathSegment = '';
return false;
}
const itemBasename = this.trimTrailingSlash(quickPickItem.label);
// Either force the autocomplete, or the old value should be one smaller than the new value and match the new value.
if (itemBasename === '..') {
// Don't match on the up directory item ever.
this.userEnteredPathSegment = startingValue;
this.autoCompletePathSegment = '';
this.activeItem = quickPickItem;
if (force) {
// clear any selected text
this.insertText(this.userEnteredPathSegment, '');
}
return false;
} else if (!force && (itemBasename.length >= startingBasename.length) && equalsIgnoreCase(itemBasename.substr(0, startingBasename.length), startingBasename)) {
this.userEnteredPathSegment = startingBasename;
this.activeItem = quickPickItem;
// Changing the active items will trigger the onDidActiveItemsChanged. Clear the autocomplete first, then set it after.
this.autoCompletePathSegment = '';
this.filePickBox.activeItems = [quickPickItem];
return true;
} else if (force && (!equalsIgnoreCase(quickPickItem.label, (this.userEnteredPathSegment + this.autoCompletePathSegment)))) {
this.userEnteredPathSegment = '';
this.autoCompletePathSegment = this.trimTrailingSlash(itemBasename);
this.activeItem = quickPickItem;
this.filePickBox.valueSelection = [this.pathFromUri(this.currentFolder, true).length, this.filePickBox.value.length];
// use insert text to preserve undo buffer
this.insertText(this.pathAppend(this.currentFolder, this.autoCompletePathSegment), this.autoCompletePathSegment);
this.filePickBox.valueSelection = [this.filePickBox.value.length - this.autoCompletePathSegment.length, this.filePickBox.value.length];
return true;
} else {
this.userEnteredPathSegment = startingBasename;
this.autoCompletePathSegment = '';
return false;
}
}
private insertText(wholeValue: string, insertText: string) {
if (this.filePickBox.inputHasFocus()) {
document.execCommand('insertText', false, insertText);
} else {
this.filePickBox.value = wholeValue;
}
}
private addPostfix(uri: URI): URI {
let result = uri;
if (this.requiresTrailing && this.options.filters && this.options.filters.length > 0) {
// Make sure that the suffix is added. If the user deleted it, we automatically add it here
let hasExt: boolean = false;
const currentExt = resources.extname(uri).substr(1);
for (let i = 0; i < this.options.filters.length; i++) {
for (let j = 0; j < this.options.filters[i].extensions.length; j++) {
if ((this.options.filters[i].extensions[j] === '*') || (this.options.filters[i].extensions[j] === currentExt)) {
hasExt = true;
break;
}
}
if (hasExt) {
break;
}
}
if (!hasExt) {
result = resources.joinPath(resources.dirname(uri), resources.basename(uri) + '.' + this.options.filters[0].extensions[0]);
}
}
return result;
}
private trimTrailingSlash(path: string): string {
return ((path.length > 1) && this.endsWithSlash(path)) ? path.substr(0, path.length - 1) : path;
}
private yesNoPrompt(uri: URI, message: string): Promise<boolean> {
interface YesNoItem extends IQuickPickItem {
value: boolean;
}
const prompt = this.quickInputService.createQuickPick<YesNoItem>();
prompt.title = message;
prompt.ignoreFocusOut = true;
prompt.ok = true;
prompt.customButton = true;
prompt.customLabel = nls.localize('remoteFileDialog.cancel', 'Cancel');
prompt.value = this.pathFromUri(uri);
let isResolving = false;
return new Promise<boolean>(resolve => {
prompt.onDidAccept(() => {
isResolving = true;
prompt.hide();
resolve(true);
});
prompt.onDidHide(() => {
if (!isResolving) {
resolve(false);
}
this.filePickBox.show();
this.hidden = false;
this.filePickBox.items = this.filePickBox.items;
prompt.dispose();
});
prompt.onDidChangeValue(() => {
prompt.hide();
});
prompt.onDidCustom(() => {
prompt.hide();
});
prompt.show();
});
}
private async validate(uri: URI | undefined): Promise<boolean> {
if (uri === undefined) {
this.filePickBox.validationMessage = nls.localize('remoteFileDialog.invalidPath', 'Please enter a valid path.');
return Promise.resolve(false);
}
let stat: IFileStat | undefined;
let statDirname: IFileStat | undefined;
try {
statDirname = await this.fileService.resolve(resources.dirname(uri));
stat = await this.fileService.resolve(uri);
} catch (e) {
// do nothing
}
if (this.requiresTrailing) { // save
if (stat && stat.isDirectory) {
// Can't do this
this.filePickBox.validationMessage = nls.localize('remoteFileDialog.validateFolder', 'The folder already exists. Please use a new file name.');
return Promise.resolve(false);
} else if (stat) {
// Replacing a file.
// Show a yes/no prompt
const message = nls.localize('remoteFileDialog.validateExisting', '{0} already exists. Are you sure you want to overwrite it?', resources.basename(uri));
return this.yesNoPrompt(uri, message);
} else if (!(isValidBasename(resources.basename(uri), await this.isWindowsOS()))) {
// Filename not allowed
this.filePickBox.validationMessage = nls.localize('remoteFileDialog.validateBadFilename', 'Please enter a valid file name.');
return Promise.resolve(false);
} else if (!statDirname || !statDirname.isDirectory) {
// Folder to save in doesn't exist
this.filePickBox.validationMessage = nls.localize('remoteFileDialog.validateNonexistentDir', 'Please enter a path that exists.');
return Promise.resolve(false);
}
} else { // open
if (!stat) {
// File or folder doesn't exist
this.filePickBox.validationMessage = nls.localize('remoteFileDialog.validateNonexistentDir', 'Please enter a path that exists.');
return Promise.resolve(false);
} else if (stat.isDirectory && !this.allowFolderSelection) {
// Folder selected when folder selection not permitted
this.filePickBox.validationMessage = nls.localize('remoteFileDialog.validateFileOnly', 'Please select a file.');
return Promise.resolve(false);
} else if (!stat.isDirectory && !this.allowFileSelection) {
// File selected when file selection not permitted
this.filePickBox.validationMessage = nls.localize('remoteFileDialog.validateFolderOnly', 'Please select a folder.');
return Promise.resolve(false);
}
}
return Promise.resolve(true);
}
private async updateItems(newFolder: URI, force: boolean = false, trailing?: string) {
this.busy = true;
this.userEnteredPathSegment = trailing ? trailing : '';
this.autoCompletePathSegment = '';
const newValue = trailing ? this.pathFromUri(resources.joinPath(newFolder, trailing)) : this.pathFromUri(newFolder, true);
this.currentFolder = resources.addTrailingPathSeparator(newFolder, this.separator);
return this.createItems(this.currentFolder).then(items => {
this.filePickBox.items = items;
if (this.allowFolderSelection) {
this.filePickBox.activeItems = [];
}
// the user might have continued typing while we were updating. Only update the input box if it doesn't match the directory.
if (!equalsIgnoreCase(this.filePickBox.value, newValue) && force) {
this.filePickBox.valueSelection = [0, this.filePickBox.value.length];
this.insertText(newValue, newValue);
}
if (force && trailing) {
// Keep the cursor position in front of the save as name.
this.filePickBox.valueSelection = [this.filePickBox.value.length - trailing.length, this.filePickBox.value.length - trailing.length];
} else if (!trailing) {
// If there is trailing, we don't move the cursor. If there is no trailing, cursor goes at the end.
this.filePickBox.valueSelection = [this.filePickBox.value.length, this.filePickBox.value.length];
}
this.busy = false;
});
}
private pathFromUri(uri: URI, endWithSeparator: boolean = false): string {
let result: string = uri.fsPath.replace(/\n/g, '');
if (this.separator === '/') {
result = result.replace(/\\/g, this.separator);
} else {
result = result.replace(/\//g, this.separator);
}
if (endWithSeparator && !this.endsWithSlash(result)) {
result = result + this.separator;
}
return result;
}
private pathAppend(uri: URI, additional: string): string {
if ((additional === '..') || (additional === '.')) {
const basePath = this.pathFromUri(uri);
return basePath + (this.endsWithSlash(basePath) ? '' : this.separator) + additional;
} else {
return this.pathFromUri(resources.joinPath(uri, additional));
}
}
private async isWindowsOS(): Promise<boolean> {
let isWindowsOS = isWindows;
const env = await this.getRemoteAgentEnvironment();
if (env) {
isWindowsOS = env.os === OperatingSystem.Windows;
}
return isWindowsOS;
}
private endsWithSlash(s: string) {
return /[\/\\]$/.test(s);
}
private basenameWithTrailingSlash(fullPath: URI): string {
const child = this.pathFromUri(fullPath, true);
const parent = this.pathFromUri(resources.dirname(fullPath), true);
return child.substring(parent.length);
}
private createBackItem(currFolder: URI): FileQuickPickItem | null {
const parentFolder = resources.dirname(currFolder)!;
if (!resources.isEqual(currFolder, parentFolder, true)) {
return { label: '..', uri: resources.addTrailingPathSeparator(parentFolder, this.separator), isFolder: true };
}
return null;
}
private async createItems(currentFolder: URI): Promise<FileQuickPickItem[]> {
const result: FileQuickPickItem[] = [];
const backDir = this.createBackItem(currentFolder);
try {
const folder = await this.fileService.resolve(currentFolder);
const fileNames = folder.children ? folder.children.map(child => child.name) : [];
const items = await Promise.all(fileNames.map(fileName => this.createItem(fileName, currentFolder)));
for (let item of items) {
if (item) {
result.push(item);
}
}
} catch (e) {
// ignore
console.log(e);
}
const sorted = result.sort((i1, i2) => {
if (i1.isFolder !== i2.isFolder) {
return i1.isFolder ? -1 : 1;
}
const trimmed1 = this.endsWithSlash(i1.label) ? i1.label.substr(0, i1.label.length - 1) : i1.label;
const trimmed2 = this.endsWithSlash(i2.label) ? i2.label.substr(0, i2.label.length - 1) : i2.label;
return trimmed1.localeCompare(trimmed2);
});
if (backDir) {
sorted.unshift(backDir);
}
return sorted;
}
private filterFile(file: URI): boolean {
if (this.options.filters) {
const ext = resources.extname(file);
for (let i = 0; i < this.options.filters.length; i++) {
for (let j = 0; j < this.options.filters[i].extensions.length; j++) {
if (ext === ('.' + this.options.filters[i].extensions[j])) {
return true;
}
}
}
return false;
}
return true;
}
private async createItem(filename: string, parent: URI): Promise<FileQuickPickItem | undefined> {
let fullPath = resources.joinPath(parent, filename);
try {
const stat = await this.fileService.resolve(fullPath);
if (stat.isDirectory) {
filename = this.basenameWithTrailingSlash(fullPath);
fullPath = resources.addTrailingPathSeparator(fullPath, this.separator);
return { label: filename, uri: fullPath, isFolder: true, iconClasses: getIconClasses(this.modelService, this.modeService, fullPath || undefined, FileKind.FOLDER) };
} else if (!stat.isDirectory && this.allowFileSelection && this.filterFile(fullPath)) {
return { label: filename, uri: fullPath, isFolder: false, iconClasses: getIconClasses(this.modelService, this.modeService, fullPath || undefined) };
}
return undefined;
} catch (e) {
return undefined;
}
}
} | src/vs/workbench/services/dialogs/browser/remoteFileDialog.ts | 1 | https://github.com/microsoft/vscode/commit/985de26b3446636f86e2bb2b14dbeb9ec1e33207 | [
0.0011883208062499762,
0.00019465250079520047,
0.00016437828890047967,
0.00017172227671835572,
0.00012977559526916593
] |
{
"id": 1,
"code_window": [
"\tstatic LABEL = nls.localize('saveLocalFile', \"Save Local File...\");\n",
"\n",
"\tconstructor(\n",
"\t\tid: string,\n",
"\t\tlabel: string,\n",
"\t\t@IFileDialogService private readonly dialogService: IFileDialogService\n",
"\t) {\n",
"\t\tsuper(id, label);\n",
"\t}\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\t@ITextFileService private readonly textFileService: ITextFileService,\n",
"\t\t@IEditorService private readonly editorService: IEditorService\n"
],
"file_path": "src/vs/workbench/browser/actions/workspaceActions.ts",
"type": "replace",
"edit_start_line_idx": 64
} | test/**
src/**/*.ts
tsconfig.json
cgmanifest.json
| extensions/javascript/.vscodeignore | 0 | https://github.com/microsoft/vscode/commit/985de26b3446636f86e2bb2b14dbeb9ec1e33207 | [
0.00017364908126182854,
0.00017364908126182854,
0.00017364908126182854,
0.00017364908126182854,
0
] |
{
"id": 1,
"code_window": [
"\tstatic LABEL = nls.localize('saveLocalFile', \"Save Local File...\");\n",
"\n",
"\tconstructor(\n",
"\t\tid: string,\n",
"\t\tlabel: string,\n",
"\t\t@IFileDialogService private readonly dialogService: IFileDialogService\n",
"\t) {\n",
"\t\tsuper(id, label);\n",
"\t}\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\t@ITextFileService private readonly textFileService: ITextFileService,\n",
"\t\t@IEditorService private readonly editorService: IEditorService\n"
],
"file_path": "src/vs/workbench/browser/actions/workspaceActions.ts",
"type": "replace",
"edit_start_line_idx": 64
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import * as browser from 'vs/base/browser/browser';
import { domEvent } from 'vs/base/browser/event';
import { IKeyboardEvent, StandardKeyboardEvent } from 'vs/base/browser/keyboardEvent';
import { IMouseEvent, StandardMouseEvent } from 'vs/base/browser/mouseEvent';
import { TimeoutTimer } from 'vs/base/common/async';
import { CharCode } from 'vs/base/common/charCode';
import { onUnexpectedError } from 'vs/base/common/errors';
import { Emitter, Event } from 'vs/base/common/event';
import { Disposable, IDisposable, toDisposable } from 'vs/base/common/lifecycle';
import * as platform from 'vs/base/common/platform';
import { coalesce } from 'vs/base/common/arrays';
export function clearNode(node: HTMLElement): void {
while (node.firstChild) {
node.removeChild(node.firstChild);
}
}
export function removeNode(node: HTMLElement): void {
if (node.parentNode) {
node.parentNode.removeChild(node);
}
}
export function isInDOM(node: Node | null): boolean {
while (node) {
if (node === document.body) {
return true;
}
node = node.parentNode;
}
return false;
}
interface IDomClassList {
hasClass(node: HTMLElement, className: string): boolean;
addClass(node: HTMLElement, className: string): void;
addClasses(node: HTMLElement, ...classNames: string[]): void;
removeClass(node: HTMLElement, className: string): void;
removeClasses(node: HTMLElement, ...classNames: string[]): void;
toggleClass(node: HTMLElement, className: string, shouldHaveIt?: boolean): void;
}
const _manualClassList = new class implements IDomClassList {
private _lastStart: number;
private _lastEnd: number;
private _findClassName(node: HTMLElement, className: string): void {
let classes = node.className;
if (!classes) {
this._lastStart = -1;
return;
}
className = className.trim();
let classesLen = classes.length,
classLen = className.length;
if (classLen === 0) {
this._lastStart = -1;
return;
}
if (classesLen < classLen) {
this._lastStart = -1;
return;
}
if (classes === className) {
this._lastStart = 0;
this._lastEnd = classesLen;
return;
}
let idx = -1,
idxEnd: number;
while ((idx = classes.indexOf(className, idx + 1)) >= 0) {
idxEnd = idx + classLen;
// a class that is followed by another class
if ((idx === 0 || classes.charCodeAt(idx - 1) === CharCode.Space) && classes.charCodeAt(idxEnd) === CharCode.Space) {
this._lastStart = idx;
this._lastEnd = idxEnd + 1;
return;
}
// last class
if (idx > 0 && classes.charCodeAt(idx - 1) === CharCode.Space && idxEnd === classesLen) {
this._lastStart = idx - 1;
this._lastEnd = idxEnd;
return;
}
// equal - duplicate of cmp above
if (idx === 0 && idxEnd === classesLen) {
this._lastStart = 0;
this._lastEnd = idxEnd;
return;
}
}
this._lastStart = -1;
}
hasClass(node: HTMLElement, className: string): boolean {
this._findClassName(node, className);
return this._lastStart !== -1;
}
addClasses(node: HTMLElement, ...classNames: string[]): void {
classNames.forEach(nameValue => nameValue.split(' ').forEach(name => this.addClass(node, name)));
}
addClass(node: HTMLElement, className: string): void {
if (!node.className) { // doesn't have it for sure
node.className = className;
} else {
this._findClassName(node, className); // see if it's already there
if (this._lastStart === -1) {
node.className = node.className + ' ' + className;
}
}
}
removeClass(node: HTMLElement, className: string): void {
this._findClassName(node, className);
if (this._lastStart === -1) {
return; // Prevent styles invalidation if not necessary
} else {
node.className = node.className.substring(0, this._lastStart) + node.className.substring(this._lastEnd);
}
}
removeClasses(node: HTMLElement, ...classNames: string[]): void {
classNames.forEach(nameValue => nameValue.split(' ').forEach(name => this.removeClass(node, name)));
}
toggleClass(node: HTMLElement, className: string, shouldHaveIt?: boolean): void {
this._findClassName(node, className);
if (this._lastStart !== -1 && (shouldHaveIt === undefined || !shouldHaveIt)) {
this.removeClass(node, className);
}
if (this._lastStart === -1 && (shouldHaveIt === undefined || shouldHaveIt)) {
this.addClass(node, className);
}
}
};
const _nativeClassList = new class implements IDomClassList {
hasClass(node: HTMLElement, className: string): boolean {
return Boolean(className) && node.classList && node.classList.contains(className);
}
addClasses(node: HTMLElement, ...classNames: string[]): void {
classNames.forEach(nameValue => nameValue.split(' ').forEach(name => this.addClass(node, name)));
}
addClass(node: HTMLElement, className: string): void {
if (className && node.classList) {
node.classList.add(className);
}
}
removeClass(node: HTMLElement, className: string): void {
if (className && node.classList) {
node.classList.remove(className);
}
}
removeClasses(node: HTMLElement, ...classNames: string[]): void {
classNames.forEach(nameValue => nameValue.split(' ').forEach(name => this.removeClass(node, name)));
}
toggleClass(node: HTMLElement, className: string, shouldHaveIt?: boolean): void {
if (node.classList) {
node.classList.toggle(className, shouldHaveIt);
}
}
};
// In IE11 there is only partial support for `classList` which makes us keep our
// custom implementation. Otherwise use the native implementation, see: http://caniuse.com/#search=classlist
const _classList: IDomClassList = browser.isIE ? _manualClassList : _nativeClassList;
export const hasClass: (node: HTMLElement, className: string) => boolean = _classList.hasClass.bind(_classList);
export const addClass: (node: HTMLElement, className: string) => void = _classList.addClass.bind(_classList);
export const addClasses: (node: HTMLElement, ...classNames: string[]) => void = _classList.addClasses.bind(_classList);
export const removeClass: (node: HTMLElement, className: string) => void = _classList.removeClass.bind(_classList);
export const removeClasses: (node: HTMLElement, ...classNames: string[]) => void = _classList.removeClasses.bind(_classList);
export const toggleClass: (node: HTMLElement, className: string, shouldHaveIt?: boolean) => void = _classList.toggleClass.bind(_classList);
class DomListener implements IDisposable {
private _handler: (e: any) => void;
private _node: Element | Window | Document;
private readonly _type: string;
private readonly _useCapture: boolean;
constructor(node: Element | Window | Document, type: string, handler: (e: any) => void, useCapture?: boolean) {
this._node = node;
this._type = type;
this._handler = handler;
this._useCapture = (useCapture || false);
this._node.addEventListener(this._type, this._handler, this._useCapture);
}
public dispose(): void {
if (!this._handler) {
// Already disposed
return;
}
this._node.removeEventListener(this._type, this._handler, this._useCapture);
// Prevent leakers from holding on to the dom or handler func
this._node = null!;
this._handler = null!;
}
}
export function addDisposableListener<K extends keyof GlobalEventHandlersEventMap>(node: Element | Window | Document, type: K, handler: (event: GlobalEventHandlersEventMap[K]) => void, useCapture?: boolean): IDisposable;
export function addDisposableListener(node: Element | Window | Document, type: string, handler: (event: any) => void, useCapture?: boolean): IDisposable;
export function addDisposableListener(node: Element | Window | Document, type: string, handler: (event: any) => void, useCapture?: boolean): IDisposable {
return new DomListener(node, type, handler, useCapture);
}
export interface IAddStandardDisposableListenerSignature {
(node: HTMLElement, type: 'click', handler: (event: IMouseEvent) => void, useCapture?: boolean): IDisposable;
(node: HTMLElement, type: 'mousedown', handler: (event: IMouseEvent) => void, useCapture?: boolean): IDisposable;
(node: HTMLElement, type: 'keydown', handler: (event: IKeyboardEvent) => void, useCapture?: boolean): IDisposable;
(node: HTMLElement, type: 'keypress', handler: (event: IKeyboardEvent) => void, useCapture?: boolean): IDisposable;
(node: HTMLElement, type: 'keyup', handler: (event: IKeyboardEvent) => void, useCapture?: boolean): IDisposable;
(node: HTMLElement, type: string, handler: (event: any) => void, useCapture?: boolean): IDisposable;
}
function _wrapAsStandardMouseEvent(handler: (e: IMouseEvent) => void): (e: MouseEvent) => void {
return function (e: MouseEvent) {
return handler(new StandardMouseEvent(e));
};
}
function _wrapAsStandardKeyboardEvent(handler: (e: IKeyboardEvent) => void): (e: KeyboardEvent) => void {
return function (e: KeyboardEvent) {
return handler(new StandardKeyboardEvent(e));
};
}
export let addStandardDisposableListener: IAddStandardDisposableListenerSignature = function addStandardDisposableListener(node: HTMLElement, type: string, handler: (event: any) => void, useCapture?: boolean): IDisposable {
let wrapHandler = handler;
if (type === 'click' || type === 'mousedown') {
wrapHandler = _wrapAsStandardMouseEvent(handler);
} else if (type === 'keydown' || type === 'keypress' || type === 'keyup') {
wrapHandler = _wrapAsStandardKeyboardEvent(handler);
}
return addDisposableListener(node, type, wrapHandler, useCapture);
};
export function addDisposableNonBubblingMouseOutListener(node: Element, handler: (event: MouseEvent) => void): IDisposable {
return addDisposableListener(node, 'mouseout', (e: MouseEvent) => {
// Mouse out bubbles, so this is an attempt to ignore faux mouse outs coming from children elements
let toElement: Node | null = <Node>(e.relatedTarget || e.target);
while (toElement && toElement !== node) {
toElement = toElement.parentNode;
}
if (toElement === node) {
return;
}
handler(e);
});
}
interface IRequestAnimationFrame {
(callback: (time: number) => void): number;
}
let _animationFrame: IRequestAnimationFrame | null = null;
function doRequestAnimationFrame(callback: (time: number) => void): number {
if (!_animationFrame) {
const emulatedRequestAnimationFrame = (callback: (time: number) => void): any => {
return setTimeout(() => callback(new Date().getTime()), 0);
};
_animationFrame = (
self.requestAnimationFrame
|| (<any>self).msRequestAnimationFrame
|| (<any>self).webkitRequestAnimationFrame
|| (<any>self).mozRequestAnimationFrame
|| (<any>self).oRequestAnimationFrame
|| emulatedRequestAnimationFrame
);
}
return _animationFrame.call(self, callback);
}
/**
* Schedule a callback to be run at the next animation frame.
* This allows multiple parties to register callbacks that should run at the next animation frame.
* If currently in an animation frame, `runner` will be executed immediately.
* @return token that can be used to cancel the scheduled runner (only if `runner` was not executed immediately).
*/
export let runAtThisOrScheduleAtNextAnimationFrame: (runner: () => void, priority?: number) => IDisposable;
/**
* Schedule a callback to be run at the next animation frame.
* This allows multiple parties to register callbacks that should run at the next animation frame.
* If currently in an animation frame, `runner` will be executed at the next animation frame.
* @return token that can be used to cancel the scheduled runner.
*/
export let scheduleAtNextAnimationFrame: (runner: () => void, priority?: number) => IDisposable;
class AnimationFrameQueueItem implements IDisposable {
private _runner: () => void;
public priority: number;
private _canceled: boolean;
constructor(runner: () => void, priority: number = 0) {
this._runner = runner;
this.priority = priority;
this._canceled = false;
}
public dispose(): void {
this._canceled = true;
}
public execute(): void {
if (this._canceled) {
return;
}
try {
this._runner();
} catch (e) {
onUnexpectedError(e);
}
}
// Sort by priority (largest to lowest)
public static sort(a: AnimationFrameQueueItem, b: AnimationFrameQueueItem): number {
return b.priority - a.priority;
}
}
(function () {
/**
* The runners scheduled at the next animation frame
*/
let NEXT_QUEUE: AnimationFrameQueueItem[] = [];
/**
* The runners scheduled at the current animation frame
*/
let CURRENT_QUEUE: AnimationFrameQueueItem[] | null = null;
/**
* A flag to keep track if the native requestAnimationFrame was already called
*/
let animFrameRequested = false;
/**
* A flag to indicate if currently handling a native requestAnimationFrame callback
*/
let inAnimationFrameRunner = false;
let animationFrameRunner = () => {
animFrameRequested = false;
CURRENT_QUEUE = NEXT_QUEUE;
NEXT_QUEUE = [];
inAnimationFrameRunner = true;
while (CURRENT_QUEUE.length > 0) {
CURRENT_QUEUE.sort(AnimationFrameQueueItem.sort);
let top = CURRENT_QUEUE.shift()!;
top.execute();
}
inAnimationFrameRunner = false;
};
scheduleAtNextAnimationFrame = (runner: () => void, priority: number = 0) => {
let item = new AnimationFrameQueueItem(runner, priority);
NEXT_QUEUE.push(item);
if (!animFrameRequested) {
animFrameRequested = true;
doRequestAnimationFrame(animationFrameRunner);
}
return item;
};
runAtThisOrScheduleAtNextAnimationFrame = (runner: () => void, priority?: number) => {
if (inAnimationFrameRunner) {
let item = new AnimationFrameQueueItem(runner, priority);
CURRENT_QUEUE!.push(item);
return item;
} else {
return scheduleAtNextAnimationFrame(runner, priority);
}
};
})();
export function measure(callback: () => void): IDisposable {
return scheduleAtNextAnimationFrame(callback, 10000 /* must be early */);
}
export function modify(callback: () => void): IDisposable {
return scheduleAtNextAnimationFrame(callback, -10000 /* must be late */);
}
/**
* Add a throttled listener. `handler` is fired at most every 16ms or with the next animation frame (if browser supports it).
*/
export interface IEventMerger<R, E> {
(lastEvent: R | null, currentEvent: E): R;
}
export interface DOMEvent {
preventDefault(): void;
stopPropagation(): void;
}
const MINIMUM_TIME_MS = 16;
const DEFAULT_EVENT_MERGER: IEventMerger<DOMEvent, DOMEvent> = function (lastEvent: DOMEvent, currentEvent: DOMEvent) {
return currentEvent;
};
class TimeoutThrottledDomListener<R, E extends DOMEvent> extends Disposable {
constructor(node: any, type: string, handler: (event: R) => void, eventMerger: IEventMerger<R, E> = <any>DEFAULT_EVENT_MERGER, minimumTimeMs: number = MINIMUM_TIME_MS) {
super();
let lastEvent: R | null = null;
let lastHandlerTime = 0;
let timeout = this._register(new TimeoutTimer());
let invokeHandler = () => {
lastHandlerTime = (new Date()).getTime();
handler(<R>lastEvent);
lastEvent = null;
};
this._register(addDisposableListener(node, type, (e) => {
lastEvent = eventMerger(lastEvent, e);
let elapsedTime = (new Date()).getTime() - lastHandlerTime;
if (elapsedTime >= minimumTimeMs) {
timeout.cancel();
invokeHandler();
} else {
timeout.setIfNotSet(invokeHandler, minimumTimeMs - elapsedTime);
}
}));
}
}
export function addDisposableThrottledListener<R, E extends DOMEvent = DOMEvent>(node: any, type: string, handler: (event: R) => void, eventMerger?: IEventMerger<R, E>, minimumTimeMs?: number): IDisposable {
return new TimeoutThrottledDomListener<R, E>(node, type, handler, eventMerger, minimumTimeMs);
}
export function getComputedStyle(el: HTMLElement): CSSStyleDeclaration {
return document.defaultView!.getComputedStyle(el, null);
}
export function getClientArea(element: HTMLElement): Dimension {
// Try with DOM clientWidth / clientHeight
if (element !== document.body) {
return new Dimension(element.clientWidth, element.clientHeight);
}
// Try innerWidth / innerHeight
if (window.innerWidth && window.innerHeight) {
return new Dimension(window.innerWidth, window.innerHeight);
}
// Try with document.body.clientWidth / document.body.clientHeight
if (document.body && document.body.clientWidth && document.body.clientHeight) {
return new Dimension(document.body.clientWidth, document.body.clientHeight);
}
// Try with document.documentElement.clientWidth / document.documentElement.clientHeight
if (document.documentElement && document.documentElement.clientWidth && document.documentElement.clientHeight) {
return new Dimension(document.documentElement.clientWidth, document.documentElement.clientHeight);
}
throw new Error('Unable to figure out browser width and height');
}
class SizeUtils {
// Adapted from WinJS
// Converts a CSS positioning string for the specified element to pixels.
private static convertToPixels(element: HTMLElement, value: string): number {
return parseFloat(value) || 0;
}
private static getDimension(element: HTMLElement, cssPropertyName: string, jsPropertyName: string): number {
let computedStyle: CSSStyleDeclaration = getComputedStyle(element);
let value = '0';
if (computedStyle) {
if (computedStyle.getPropertyValue) {
value = computedStyle.getPropertyValue(cssPropertyName);
} else {
// IE8
value = (<any>computedStyle).getAttribute(jsPropertyName);
}
}
return SizeUtils.convertToPixels(element, value);
}
static getBorderLeftWidth(element: HTMLElement): number {
return SizeUtils.getDimension(element, 'border-left-width', 'borderLeftWidth');
}
static getBorderRightWidth(element: HTMLElement): number {
return SizeUtils.getDimension(element, 'border-right-width', 'borderRightWidth');
}
static getBorderTopWidth(element: HTMLElement): number {
return SizeUtils.getDimension(element, 'border-top-width', 'borderTopWidth');
}
static getBorderBottomWidth(element: HTMLElement): number {
return SizeUtils.getDimension(element, 'border-bottom-width', 'borderBottomWidth');
}
static getPaddingLeft(element: HTMLElement): number {
return SizeUtils.getDimension(element, 'padding-left', 'paddingLeft');
}
static getPaddingRight(element: HTMLElement): number {
return SizeUtils.getDimension(element, 'padding-right', 'paddingRight');
}
static getPaddingTop(element: HTMLElement): number {
return SizeUtils.getDimension(element, 'padding-top', 'paddingTop');
}
static getPaddingBottom(element: HTMLElement): number {
return SizeUtils.getDimension(element, 'padding-bottom', 'paddingBottom');
}
static getMarginLeft(element: HTMLElement): number {
return SizeUtils.getDimension(element, 'margin-left', 'marginLeft');
}
static getMarginTop(element: HTMLElement): number {
return SizeUtils.getDimension(element, 'margin-top', 'marginTop');
}
static getMarginRight(element: HTMLElement): number {
return SizeUtils.getDimension(element, 'margin-right', 'marginRight');
}
static getMarginBottom(element: HTMLElement): number {
return SizeUtils.getDimension(element, 'margin-bottom', 'marginBottom');
}
}
// ----------------------------------------------------------------------------------------
// Position & Dimension
export class Dimension {
public width: number;
public height: number;
constructor(width: number, height: number) {
this.width = width;
this.height = height;
}
static equals(a: Dimension | undefined, b: Dimension | undefined): boolean {
if (a === b) {
return true;
}
if (!a || !b) {
return false;
}
return a.width === b.width && a.height === b.height;
}
}
export function getTopLeftOffset(element: HTMLElement): { left: number; top: number; } {
// Adapted from WinJS.Utilities.getPosition
// and added borders to the mix
let offsetParent = element.offsetParent, top = element.offsetTop, left = element.offsetLeft;
while ((element = <HTMLElement>element.parentNode) !== null && element !== document.body && element !== document.documentElement) {
top -= element.scrollTop;
let c = getComputedStyle(element);
if (c) {
left -= c.direction !== 'rtl' ? element.scrollLeft : -element.scrollLeft;
}
if (element === offsetParent) {
left += SizeUtils.getBorderLeftWidth(element);
top += SizeUtils.getBorderTopWidth(element);
top += element.offsetTop;
left += element.offsetLeft;
offsetParent = element.offsetParent;
}
}
return {
left: left,
top: top
};
}
export interface IDomNodePagePosition {
left: number;
top: number;
width: number;
height: number;
}
export function size(element: HTMLElement, width: number | null, height: number | null): void {
if (typeof width === 'number') {
element.style.width = `${width}px`;
}
if (typeof height === 'number') {
element.style.height = `${height}px`;
}
}
export function position(element: HTMLElement, top: number, right?: number, bottom?: number, left?: number, position: string = 'absolute'): void {
if (typeof top === 'number') {
element.style.top = `${top}px`;
}
if (typeof right === 'number') {
element.style.right = `${right}px`;
}
if (typeof bottom === 'number') {
element.style.bottom = `${bottom}px`;
}
if (typeof left === 'number') {
element.style.left = `${left}px`;
}
element.style.position = position;
}
/**
* Returns the position of a dom node relative to the entire page.
*/
export function getDomNodePagePosition(domNode: HTMLElement): IDomNodePagePosition {
let bb = domNode.getBoundingClientRect();
return {
left: bb.left + StandardWindow.scrollX,
top: bb.top + StandardWindow.scrollY,
width: bb.width,
height: bb.height
};
}
export interface IStandardWindow {
readonly scrollX: number;
readonly scrollY: number;
}
export const StandardWindow: IStandardWindow = new class implements IStandardWindow {
get scrollX(): number {
if (typeof window.scrollX === 'number') {
// modern browsers
return window.scrollX;
} else {
return document.body.scrollLeft + document.documentElement!.scrollLeft;
}
}
get scrollY(): number {
if (typeof window.scrollY === 'number') {
// modern browsers
return window.scrollY;
} else {
return document.body.scrollTop + document.documentElement!.scrollTop;
}
}
};
// Adapted from WinJS
// Gets the width of the element, including margins.
export function getTotalWidth(element: HTMLElement): number {
let margin = SizeUtils.getMarginLeft(element) + SizeUtils.getMarginRight(element);
return element.offsetWidth + margin;
}
export function getContentWidth(element: HTMLElement): number {
let border = SizeUtils.getBorderLeftWidth(element) + SizeUtils.getBorderRightWidth(element);
let padding = SizeUtils.getPaddingLeft(element) + SizeUtils.getPaddingRight(element);
return element.offsetWidth - border - padding;
}
export function getTotalScrollWidth(element: HTMLElement): number {
let margin = SizeUtils.getMarginLeft(element) + SizeUtils.getMarginRight(element);
return element.scrollWidth + margin;
}
// Adapted from WinJS
// Gets the height of the content of the specified element. The content height does not include borders or padding.
export function getContentHeight(element: HTMLElement): number {
let border = SizeUtils.getBorderTopWidth(element) + SizeUtils.getBorderBottomWidth(element);
let padding = SizeUtils.getPaddingTop(element) + SizeUtils.getPaddingBottom(element);
return element.offsetHeight - border - padding;
}
// Adapted from WinJS
// Gets the height of the element, including its margins.
export function getTotalHeight(element: HTMLElement): number {
let margin = SizeUtils.getMarginTop(element) + SizeUtils.getMarginBottom(element);
return element.offsetHeight + margin;
}
// Gets the left coordinate of the specified element relative to the specified parent.
function getRelativeLeft(element: HTMLElement, parent: HTMLElement): number {
if (element === null) {
return 0;
}
let elementPosition = getTopLeftOffset(element);
let parentPosition = getTopLeftOffset(parent);
return elementPosition.left - parentPosition.left;
}
export function getLargestChildWidth(parent: HTMLElement, children: HTMLElement[]): number {
let childWidths = children.map((child) => {
return Math.max(getTotalScrollWidth(child), getTotalWidth(child)) + getRelativeLeft(child, parent) || 0;
});
let maxWidth = Math.max(...childWidths);
return maxWidth;
}
// ----------------------------------------------------------------------------------------
export function isAncestor(testChild: Node | null, testAncestor: Node | null): boolean {
while (testChild) {
if (testChild === testAncestor) {
return true;
}
testChild = testChild.parentNode;
}
return false;
}
export function findParentWithClass(node: HTMLElement, clazz: string, stopAtClazzOrNode?: string | HTMLElement): HTMLElement | null {
while (node) {
if (hasClass(node, clazz)) {
return node;
}
if (stopAtClazzOrNode) {
if (typeof stopAtClazzOrNode === 'string') {
if (hasClass(node, stopAtClazzOrNode)) {
return null;
}
} else {
if (node === stopAtClazzOrNode) {
return null;
}
}
}
node = <HTMLElement>node.parentNode;
}
return null;
}
export function hasParentWithClass(node: HTMLElement, clazz: string, stopAtClazzOrNode?: string | HTMLElement): boolean {
return !!findParentWithClass(node, clazz, stopAtClazzOrNode);
}
export function createStyleSheet(container: HTMLElement = document.getElementsByTagName('head')[0]): HTMLStyleElement {
let style = document.createElement('style');
style.type = 'text/css';
style.media = 'screen';
container.appendChild(style);
return style;
}
let _sharedStyleSheet: HTMLStyleElement | null = null;
function getSharedStyleSheet(): HTMLStyleElement {
if (!_sharedStyleSheet) {
_sharedStyleSheet = createStyleSheet();
}
return _sharedStyleSheet;
}
function getDynamicStyleSheetRules(style: any) {
if (style && style.sheet && style.sheet.rules) {
// Chrome, IE
return style.sheet.rules;
}
if (style && style.sheet && style.sheet.cssRules) {
// FF
return style.sheet.cssRules;
}
return [];
}
export function createCSSRule(selector: string, cssText: string, style: HTMLStyleElement = getSharedStyleSheet()): void {
if (!style || !cssText) {
return;
}
(<CSSStyleSheet>style.sheet).insertRule(selector + '{' + cssText + '}', 0);
}
export function removeCSSRulesContainingSelector(ruleName: string, style: HTMLStyleElement = getSharedStyleSheet()): void {
if (!style) {
return;
}
let rules = getDynamicStyleSheetRules(style);
let toDelete: number[] = [];
for (let i = 0; i < rules.length; i++) {
let rule = rules[i];
if (rule.selectorText.indexOf(ruleName) !== -1) {
toDelete.push(i);
}
}
for (let i = toDelete.length - 1; i >= 0; i--) {
(<any>style.sheet).deleteRule(toDelete[i]);
}
}
export function isHTMLElement(o: any): o is HTMLElement {
if (typeof HTMLElement === 'object') {
return o instanceof HTMLElement;
}
return o && typeof o === 'object' && o.nodeType === 1 && typeof o.nodeName === 'string';
}
export const EventType = {
// Mouse
CLICK: 'click',
DBLCLICK: 'dblclick',
MOUSE_UP: 'mouseup',
MOUSE_DOWN: 'mousedown',
MOUSE_OVER: 'mouseover',
MOUSE_MOVE: 'mousemove',
MOUSE_OUT: 'mouseout',
MOUSE_ENTER: 'mouseenter',
MOUSE_LEAVE: 'mouseleave',
CONTEXT_MENU: 'contextmenu',
WHEEL: 'wheel',
// Keyboard
KEY_DOWN: 'keydown',
KEY_PRESS: 'keypress',
KEY_UP: 'keyup',
// HTML Document
LOAD: 'load',
UNLOAD: 'unload',
ABORT: 'abort',
ERROR: 'error',
RESIZE: 'resize',
SCROLL: 'scroll',
// Form
SELECT: 'select',
CHANGE: 'change',
SUBMIT: 'submit',
RESET: 'reset',
FOCUS: 'focus',
FOCUS_IN: 'focusin',
FOCUS_OUT: 'focusout',
BLUR: 'blur',
INPUT: 'input',
// Local Storage
STORAGE: 'storage',
// Drag
DRAG_START: 'dragstart',
DRAG: 'drag',
DRAG_ENTER: 'dragenter',
DRAG_LEAVE: 'dragleave',
DRAG_OVER: 'dragover',
DROP: 'drop',
DRAG_END: 'dragend',
// Animation
ANIMATION_START: browser.isWebKit ? 'webkitAnimationStart' : 'animationstart',
ANIMATION_END: browser.isWebKit ? 'webkitAnimationEnd' : 'animationend',
ANIMATION_ITERATION: browser.isWebKit ? 'webkitAnimationIteration' : 'animationiteration'
} as const;
export interface EventLike {
preventDefault(): void;
stopPropagation(): void;
}
export const EventHelper = {
stop: function (e: EventLike, cancelBubble?: boolean) {
if (e.preventDefault) {
e.preventDefault();
} else {
// IE8
(<any>e).returnValue = false;
}
if (cancelBubble) {
if (e.stopPropagation) {
e.stopPropagation();
} else {
// IE8
(<any>e).cancelBubble = true;
}
}
}
};
export interface IFocusTracker extends Disposable {
onDidFocus: Event<void>;
onDidBlur: Event<void>;
}
export function saveParentsScrollTop(node: Element): number[] {
let r: number[] = [];
for (let i = 0; node && node.nodeType === node.ELEMENT_NODE; i++) {
r[i] = node.scrollTop;
node = <Element>node.parentNode;
}
return r;
}
export function restoreParentsScrollTop(node: Element, state: number[]): void {
for (let i = 0; node && node.nodeType === node.ELEMENT_NODE; i++) {
if (node.scrollTop !== state[i]) {
node.scrollTop = state[i];
}
node = <Element>node.parentNode;
}
}
class FocusTracker extends Disposable implements IFocusTracker {
private readonly _onDidFocus = this._register(new Emitter<void>());
public readonly onDidFocus: Event<void> = this._onDidFocus.event;
private readonly _onDidBlur = this._register(new Emitter<void>());
public readonly onDidBlur: Event<void> = this._onDidBlur.event;
constructor(element: HTMLElement | Window) {
super();
let hasFocus = isAncestor(document.activeElement, <HTMLElement>element);
let loosingFocus = false;
const onFocus = () => {
loosingFocus = false;
if (!hasFocus) {
hasFocus = true;
this._onDidFocus.fire();
}
};
const onBlur = () => {
if (hasFocus) {
loosingFocus = true;
window.setTimeout(() => {
if (loosingFocus) {
loosingFocus = false;
hasFocus = false;
this._onDidBlur.fire();
}
}, 0);
}
};
this._register(domEvent(element, EventType.FOCUS, true)(onFocus));
this._register(domEvent(element, EventType.BLUR, true)(onBlur));
}
}
export function trackFocus(element: HTMLElement | Window): IFocusTracker {
return new FocusTracker(element);
}
export function append<T extends Node>(parent: HTMLElement, ...children: T[]): T {
children.forEach(child => parent.appendChild(child));
return children[children.length - 1];
}
export function prepend<T extends Node>(parent: HTMLElement, child: T): T {
parent.insertBefore(child, parent.firstChild);
return child;
}
const SELECTOR_REGEX = /([\w\-]+)?(#([\w\-]+))?((.([\w\-]+))*)/;
export function $<T extends HTMLElement>(description: string, attrs?: { [key: string]: any; }, ...children: Array<Node | string>): T {
let match = SELECTOR_REGEX.exec(description);
if (!match) {
throw new Error('Bad use of emmet');
}
let result = document.createElement(match[1] || 'div');
if (match[3]) {
result.id = match[3];
}
if (match[4]) {
result.className = match[4].replace(/\./g, ' ').trim();
}
attrs = attrs || {};
Object.keys(attrs).forEach(name => {
const value = attrs![name];
if (/^on\w+$/.test(name)) {
(<any>result)[name] = value;
} else if (name === 'selected') {
if (value) {
result.setAttribute(name, 'true');
}
} else {
result.setAttribute(name, value);
}
});
coalesce(children)
.forEach(child => {
if (child instanceof Node) {
result.appendChild(child);
} else {
result.appendChild(document.createTextNode(child as string));
}
});
return result as T;
}
export function join(nodes: Node[], separator: Node | string): Node[] {
const result: Node[] = [];
nodes.forEach((node, index) => {
if (index > 0) {
if (separator instanceof Node) {
result.push(separator.cloneNode());
} else {
result.push(document.createTextNode(separator));
}
}
result.push(node);
});
return result;
}
export function show(...elements: HTMLElement[]): void {
for (let element of elements) {
element.style.display = '';
element.removeAttribute('aria-hidden');
}
}
export function hide(...elements: HTMLElement[]): void {
for (let element of elements) {
element.style.display = 'none';
element.setAttribute('aria-hidden', 'true');
}
}
function findParentWithAttribute(node: Node | null, attribute: string): HTMLElement | null {
while (node) {
if (node instanceof HTMLElement && node.hasAttribute(attribute)) {
return node;
}
node = node.parentNode;
}
return null;
}
export function removeTabIndexAndUpdateFocus(node: HTMLElement): void {
if (!node || !node.hasAttribute('tabIndex')) {
return;
}
// If we are the currently focused element and tabIndex is removed,
// standard DOM behavior is to move focus to the <body> element. We
// typically never want that, rather put focus to the closest element
// in the hierarchy of the parent DOM nodes.
if (document.activeElement === node) {
let parentFocusable = findParentWithAttribute(node.parentElement, 'tabIndex');
if (parentFocusable) {
parentFocusable.focus();
}
}
node.removeAttribute('tabindex');
}
export function getElementsByTagName(tag: string): HTMLElement[] {
return Array.prototype.slice.call(document.getElementsByTagName(tag), 0);
}
export function finalHandler<T extends DOMEvent>(fn: (event: T) => any): (event: T) => any {
return e => {
e.preventDefault();
e.stopPropagation();
fn(e);
};
}
export function domContentLoaded(): Promise<any> {
return new Promise<any>(resolve => {
const readyState = document.readyState;
if (readyState === 'complete' || (document && document.body !== null)) {
platform.setImmediate(resolve);
} else {
window.addEventListener('DOMContentLoaded', resolve, false);
}
});
}
/**
* Find a value usable for a dom node size such that the likelihood that it would be
* displayed with constant screen pixels size is as high as possible.
*
* e.g. We would desire for the cursors to be 2px (CSS px) wide. Under a devicePixelRatio
* of 1.25, the cursor will be 2.5 screen pixels wide. Depending on how the dom node aligns/"snaps"
* with the screen pixels, it will sometimes be rendered with 2 screen pixels, and sometimes with 3 screen pixels.
*/
export function computeScreenAwareSize(cssPx: number): number {
const screenPx = window.devicePixelRatio * cssPx;
return Math.max(1, Math.floor(screenPx)) / window.devicePixelRatio;
}
/**
* See https://github.com/Microsoft/monaco-editor/issues/601
* To protect against malicious code in the linked site, particularly phishing attempts,
* the window.opener should be set to null to prevent the linked site from having access
* to change the location of the current page.
* See https://mathiasbynens.github.io/rel-noopener/
*/
export function windowOpenNoOpener(url: string): void {
if (platform.isNative || browser.isEdgeWebView) {
// In VSCode, window.open() always returns null...
// The same is true for a WebView (see https://github.com/Microsoft/monaco-editor/issues/628)
window.open(url);
} else {
let newTab = window.open();
if (newTab) {
(newTab as any).opener = null;
newTab.location.href = url;
}
}
}
export function animate(fn: () => void): IDisposable {
const step = () => {
fn();
stepDisposable = scheduleAtNextAnimationFrame(step);
};
let stepDisposable = scheduleAtNextAnimationFrame(step);
return toDisposable(() => stepDisposable.dispose());
}
| src/vs/base/browser/dom.ts | 0 | https://github.com/microsoft/vscode/commit/985de26b3446636f86e2bb2b14dbeb9ec1e33207 | [
0.0005561850848607719,
0.00017510545148979872,
0.00016445948858745396,
0.00017110150656662881,
0.00003604696394177154
] |
{
"id": 1,
"code_window": [
"\tstatic LABEL = nls.localize('saveLocalFile', \"Save Local File...\");\n",
"\n",
"\tconstructor(\n",
"\t\tid: string,\n",
"\t\tlabel: string,\n",
"\t\t@IFileDialogService private readonly dialogService: IFileDialogService\n",
"\t) {\n",
"\t\tsuper(id, label);\n",
"\t}\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\t@ITextFileService private readonly textFileService: ITextFileService,\n",
"\t\t@IEditorService private readonly editorService: IEditorService\n"
],
"file_path": "src/vs/workbench/browser/actions/workspaceActions.ts",
"type": "replace",
"edit_start_line_idx": 64
} | {
"displayName": "Git",
"description": "Git SCM Integration",
"command.clone": "Clone",
"command.init": "Initialize Repository",
"command.openRepository": "Open Repository",
"command.close": "Close Repository",
"command.refresh": "Refresh",
"command.openChange": "Open Changes",
"command.openFile": "Open File",
"command.openHEADFile": "Open File (HEAD)",
"command.stage": "Stage Changes",
"command.stageAll": "Stage All Changes",
"command.stageSelectedRanges": "Stage Selected Ranges",
"command.revertSelectedRanges": "Revert Selected Ranges",
"command.stageChange": "Stage Change",
"command.revertChange": "Revert Change",
"command.unstage": "Unstage Changes",
"command.unstageAll": "Unstage All Changes",
"command.unstageSelectedRanges": "Unstage Selected Ranges",
"command.clean": "Discard Changes",
"command.cleanAll": "Discard All Changes",
"command.commit": "Commit",
"command.commitStaged": "Commit Staged",
"command.commitEmpty": "Commit Empty",
"command.commitStagedSigned": "Commit Staged (Signed Off)",
"command.commitStagedAmend": "Commit Staged (Amend)",
"command.commitAll": "Commit All",
"command.commitAllSigned": "Commit All (Signed Off)",
"command.commitAllAmend": "Commit All (Amend)",
"command.restoreCommitTemplate": "Restore Commit Template",
"command.undoCommit": "Undo Last Commit",
"command.checkout": "Checkout to...",
"command.branch": "Create Branch...",
"command.branchFrom": "Create Branch From...",
"command.deleteBranch": "Delete Branch...",
"command.renameBranch": "Rename Branch...",
"command.merge": "Merge Branch...",
"command.createTag": "Create Tag",
"command.fetch": "Fetch",
"command.fetchPrune": "Fetch (Prune)",
"command.fetchAll": "Fetch From All Remotes",
"command.pull": "Pull",
"command.pullRebase": "Pull (Rebase)",
"command.pullFrom": "Pull from...",
"command.push": "Push",
"command.pushForce": "Push (Force)",
"command.pushTo": "Push to...",
"command.pushToForce": "Push to... (Force)",
"command.pushFollowTags": "Push (Follow Tags)",
"command.pushFollowTagsForce": "Push (Follow Tags, Force)",
"command.addRemote": "Add Remote",
"command.removeRemote": "Remove Remote",
"command.sync": "Sync",
"command.syncRebase": "Sync (Rebase)",
"command.publish": "Publish Branch",
"command.showOutput": "Show Git Output",
"command.ignore": "Add File to .gitignore",
"command.stashIncludeUntracked": "Stash (Include Untracked)",
"command.stash": "Stash",
"command.stashPop": "Pop Stash...",
"command.stashPopLatest": "Pop Latest Stash",
"command.stashApply": "Apply Stash...",
"command.stashApplyLatest": "Apply Latest Stash",
"config.enabled": "Whether git is enabled.",
"config.path": "Path and filename of the git executable, e.g. `C:\\Program Files\\Git\\bin\\git.exe` (Windows).",
"config.autoRepositoryDetection": "Configures when repositories should be automatically detected.",
"config.autoRepositoryDetection.true": "Scan for both subfolders of the current opened folder and parent folders of open files.",
"config.autoRepositoryDetection.false": "Disable automatic repository scanning.",
"config.autoRepositoryDetection.subFolders": "Scan for subfolders of the currently opened folder.",
"config.autoRepositoryDetection.openEditors": "Scan for parent folders of open files.",
"config.autorefresh": "Whether auto refreshing is enabled.",
"config.autofetch": "When enabled, commits will automatically be fetched from the default remote of the current Git repository.",
"config.autofetchPeriod": "Duration in seconds between each automatic git fetch, when `git.autofetch` is enabled.",
"config.confirmSync": "Confirm before synchronizing git repositories.",
"config.countBadge": "Controls the git badge counter.",
"config.countBadge.all": "Count all changes.",
"config.countBadge.tracked": "Count only tracked changes.",
"config.countBadge.off": "Turn off counter.",
"config.checkoutType": "Controls what type of branches are listed when running `Checkout to...`.",
"config.checkoutType.all": "Show all references.",
"config.checkoutType.local": "Show only local branches.",
"config.checkoutType.tags": "Show only tags.",
"config.checkoutType.remote": "Show only remote branches.",
"config.branchValidationRegex": "A regular expression to validate new branch names.",
"config.branchWhitespaceChar": "The character to replace whitespace in new branch names.",
"config.ignoreLegacyWarning": "Ignores the legacy Git warning.",
"config.ignoreMissingGitWarning": "Ignores the warning when Git is missing.",
"config.ignoreLimitWarning": "Ignores the warning when there are too many changes in a repository.",
"config.defaultCloneDirectory": "The default location to clone a git repository.",
"config.enableSmartCommit": "Commit all changes when there are no staged changes.",
"config.enableCommitSigning": "Enables commit signing with GPG.",
"config.discardAllScope": "Controls what changes are discarded by the `Discard all changes` command. `all` discards all changes. `tracked` discards only tracked files. `prompt` shows a prompt dialog every time the action is run.",
"config.decorations.enabled": "Controls whether Git contributes colors and badges to the explorer and the open editors view.",
"config.promptToSaveFilesBeforeCommit": "Controls whether Git should check for unsaved files before committing.",
"config.postCommitCommand": "Runs a git command after a successful commit.",
"config.postCommitCommand.none": "Don't run any command after a commit.",
"config.postCommitCommand.push": "Run 'Git Push' after a successful commit.",
"config.postCommitCommand.sync": "Run 'Git Sync' after a successful commit.",
"config.showInlineOpenFileAction": "Controls whether to show an inline Open File action in the Git changes view.",
"config.showPushSuccessNotification": "Controls whether to show a notification when a push is successful.",
"config.inputValidation": "Controls when to show commit message input validation.",
"config.inputValidationLength": "Controls the commit message length threshold for showing a warning.",
"config.inputValidationSubjectLength": "Controls the commit message subject length threshold for showing a warning. Unset it to inherit the value of `config.inputValidationLength`.",
"config.detectSubmodules": "Controls whether to automatically detect git submodules.",
"config.detectSubmodulesLimit": "Controls the limit of git submodules detected.",
"config.alwaysShowStagedChangesResourceGroup": "Always show the Staged Changes resource group.",
"config.alwaysSignOff": "Controls the signoff flag for all commits.",
"config.ignoredRepositories": "List of git repositories to ignore.",
"config.scanRepositories": "List of paths to search for git repositories in.",
"config.showProgress": "Controls whether git actions should show progress.",
"config.rebaseWhenSync": "Force git to use rebase when running the sync command.",
"config.confirmEmptyCommits": "Always confirm the creation of empty commits.",
"config.fetchOnPull": "Fetch all branches when pulling or just the current one.",
"config.pullTags": "Fetch all tags when pulling.",
"config.autoStash": "Stash any changes before pulling and restore them after successful pull.",
"config.allowForcePush": "Controls whether force push (with or without lease) is enabled.",
"config.useForcePushWithLease": "Controls whether force pushing uses the safer force-with-lease variant.",
"config.confirmForcePush": "Controls whether to ask for confirmation before force-pushing.",
"config.openDiffOnClick": "Controls whether the diff editor should be opened when clicking a change. Otherwise the regular editor will be opened.",
"colors.added": "Color for added resources.",
"colors.modified": "Color for modified resources.",
"colors.deleted": "Color for deleted resources.",
"colors.untracked": "Color for untracked resources.",
"colors.ignored": "Color for ignored resources.",
"colors.conflict": "Color for resources with conflicts.",
"colors.submodule": "Color for submodule resources."
} | extensions/git/package.nls.json | 0 | https://github.com/microsoft/vscode/commit/985de26b3446636f86e2bb2b14dbeb9ec1e33207 | [
0.00017352924623992294,
0.0001695608807494864,
0.0001657616376178339,
0.00016955698083620518,
0.000002373511506448267
] |
{
"id": 2,
"code_window": [
"\t) {\n",
"\t\tsuper(id, label);\n",
"\t}\n",
"\n",
"\trun(event?: any, data?: ITelemetryData): Promise<any> {\n",
"\t\treturn this.dialogService.pickFileToSave({ availableFileSystems: [Schemas.file] });\n",
"\t}\n",
"}\n",
"\n",
"export class OpenFolderAction extends Action {\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\tasync run(event?: any, data?: ITelemetryData): Promise<any> {\n",
"\t\tlet resource: URI | undefined = toResource(this.editorService.activeEditor);\n",
"\t\tconst options: ISaveOptions = { force: true, availableFileSystems: [Schemas.file] };\n",
"\t\tif (resource) {\n",
"\t\t\treturn this.textFileService.saveAs(resource, undefined, options);\n",
"\t\t}\n"
],
"file_path": "src/vs/workbench/browser/actions/workspaceActions.ts",
"type": "replace",
"edit_start_line_idx": 69
} | /*---------------------------------------------------------------------------------------------
* 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 resources from 'vs/base/common/resources';
import * as objects from 'vs/base/common/objects';
import { IFileService, IFileStat, FileKind } from 'vs/platform/files/common/files';
import { IQuickInputService, IQuickPickItem, IQuickPick } from 'vs/platform/quickinput/common/quickInput';
import { URI } from 'vs/base/common/uri';
import { isWindows, OperatingSystem } from 'vs/base/common/platform';
import { ISaveDialogOptions, IOpenDialogOptions, IFileDialogService } from 'vs/platform/dialogs/common/dialogs';
import { REMOTE_HOST_SCHEME } from 'vs/platform/remote/common/remoteHosts';
import { ILabelService } from 'vs/platform/label/common/label';
import { IWorkspaceContextService } from 'vs/platform/workspace/common/workspace';
import { INotificationService } from 'vs/platform/notification/common/notification';
import { IModelService } from 'vs/editor/common/services/modelService';
import { IModeService } from 'vs/editor/common/services/modeService';
import { getIconClasses } from 'vs/editor/common/services/getIconClasses';
import { Schemas } from 'vs/base/common/network';
import { IWorkbenchEnvironmentService } from 'vs/workbench/services/environment/common/environmentService';
import { IRemoteAgentService } from 'vs/workbench/services/remote/common/remoteAgentService';
import { IContextKeyService, IContextKey } from 'vs/platform/contextkey/common/contextkey';
import { equalsIgnoreCase, format, startsWithIgnoreCase } from 'vs/base/common/strings';
import { OpenLocalFileAction, OpenLocalFileFolderAction, OpenLocalFolderAction, SaveLocalFileAction } from 'vs/workbench/browser/actions/workspaceActions';
import { IKeybindingService } from 'vs/platform/keybinding/common/keybinding';
import { IRemoteAgentEnvironment } from 'vs/platform/remote/common/remoteAgentEnvironment';
import { isValidBasename } from 'vs/base/common/extpath';
import { RemoteFileDialogContext } from 'vs/workbench/browser/contextkeys';
import { Emitter } from 'vs/base/common/event';
import { IDisposable, dispose } from 'vs/base/common/lifecycle';
interface FileQuickPickItem extends IQuickPickItem {
uri: URI;
isFolder: boolean;
}
enum UpdateResult {
Updated,
Updating,
NotUpdated,
InvalidPath
}
export class RemoteFileDialog {
private options: IOpenDialogOptions;
private currentFolder: URI;
private filePickBox: IQuickPick<FileQuickPickItem>;
private hidden: boolean;
private allowFileSelection: boolean;
private allowFolderSelection: boolean;
private remoteAuthority: string | undefined;
private requiresTrailing: boolean;
private trailing: string | undefined;
private scheme: string = REMOTE_HOST_SCHEME;
private contextKey: IContextKey<boolean>;
private userEnteredPathSegment: string;
private autoCompletePathSegment: string;
private activeItem: FileQuickPickItem;
private userHome: URI;
private badPath: string | undefined;
private remoteAgentEnvironment: IRemoteAgentEnvironment | null;
private separator: string;
private onBusyChangeEmitter = new Emitter<boolean>();
protected disposables: IDisposable[] = [
this.onBusyChangeEmitter
];
constructor(
@IFileService private readonly fileService: IFileService,
@IQuickInputService private readonly quickInputService: IQuickInputService,
@ILabelService private readonly labelService: ILabelService,
@IWorkspaceContextService private readonly workspaceContextService: IWorkspaceContextService,
@INotificationService private readonly notificationService: INotificationService,
@IFileDialogService private readonly fileDialogService: IFileDialogService,
@IModelService private readonly modelService: IModelService,
@IModeService private readonly modeService: IModeService,
@IWorkbenchEnvironmentService private readonly environmentService: IWorkbenchEnvironmentService,
@IRemoteAgentService private readonly remoteAgentService: IRemoteAgentService,
@IKeybindingService private readonly keybindingService: IKeybindingService,
@IContextKeyService contextKeyService: IContextKeyService,
) {
this.remoteAuthority = this.environmentService.configuration.remoteAuthority;
this.contextKey = RemoteFileDialogContext.bindTo(contextKeyService);
}
set busy(busy: boolean) {
if (this.filePickBox.busy !== busy) {
this.filePickBox.busy = busy;
this.onBusyChangeEmitter.fire(busy);
}
}
get busy(): boolean {
return this.filePickBox.busy;
}
public async showOpenDialog(options: IOpenDialogOptions = {}): Promise<URI | undefined> {
this.scheme = this.getScheme(options.defaultUri, options.availableFileSystems);
this.userHome = await this.getUserHome();
const newOptions = await this.getOptions(options);
if (!newOptions) {
return Promise.resolve(undefined);
}
this.options = newOptions;
return this.pickResource();
}
public async showSaveDialog(options: ISaveDialogOptions): Promise<URI | undefined> {
this.scheme = this.getScheme(options.defaultUri, options.availableFileSystems);
this.userHome = await this.getUserHome();
this.requiresTrailing = true;
const newOptions = await this.getOptions(options, true);
if (!newOptions) {
return Promise.resolve(undefined);
}
this.options = newOptions;
this.options.canSelectFolders = true;
this.options.canSelectFiles = true;
return new Promise<URI | undefined>((resolve) => {
this.pickResource(true).then(folderUri => {
resolve(folderUri);
});
});
}
private getOptions(options: ISaveDialogOptions | IOpenDialogOptions, isSave: boolean = false): IOpenDialogOptions | undefined {
let defaultUri = options.defaultUri;
const filename = (defaultUri && isSave && (resources.dirname(defaultUri).path === '/')) ? resources.basename(defaultUri) : undefined;
if (!defaultUri || filename) {
defaultUri = this.userHome;
if (filename) {
defaultUri = resources.joinPath(defaultUri, filename);
}
}
if ((this.scheme !== Schemas.file) && !this.fileService.canHandleResource(defaultUri)) {
this.notificationService.info(nls.localize('remoteFileDialog.notConnectedToRemote', 'File system provider for {0} is not available.', defaultUri.toString()));
return undefined;
}
const newOptions: IOpenDialogOptions = objects.deepClone(options);
newOptions.defaultUri = defaultUri;
return newOptions;
}
private remoteUriFrom(path: string): URI {
path = path.replace(/\\/g, '/');
return resources.toLocalResource(URI.from({ scheme: this.scheme, path }), this.scheme === Schemas.file ? undefined : this.remoteAuthority);
}
private getScheme(defaultUri: URI | undefined, available: string[] | undefined): string {
return defaultUri ? defaultUri.scheme : (available ? available[0] : Schemas.file);
}
private async getRemoteAgentEnvironment(): Promise<IRemoteAgentEnvironment | null> {
if (this.remoteAgentEnvironment === undefined) {
this.remoteAgentEnvironment = await this.remoteAgentService.getEnvironment();
}
return this.remoteAgentEnvironment;
}
private async getUserHome(): Promise<URI> {
if (this.scheme !== Schemas.file) {
const env = await this.getRemoteAgentEnvironment();
if (env) {
return env.userHome;
}
}
return URI.from({ scheme: this.scheme, path: this.environmentService.userHome });
}
private async pickResource(isSave: boolean = false): Promise<URI | undefined> {
this.allowFolderSelection = !!this.options.canSelectFolders;
this.allowFileSelection = !!this.options.canSelectFiles;
this.separator = this.labelService.getSeparator(this.scheme, this.remoteAuthority);
this.hidden = false;
let homedir: URI = this.options.defaultUri ? this.options.defaultUri : this.workspaceContextService.getWorkspace().folders[0].uri;
let stat: IFileStat | undefined;
let ext: string = resources.extname(homedir);
if (this.options.defaultUri) {
try {
stat = await this.fileService.resolve(this.options.defaultUri);
} catch (e) {
// The file or folder doesn't exist
}
if (!stat || !stat.isDirectory) {
homedir = resources.dirname(this.options.defaultUri);
this.trailing = resources.basename(this.options.defaultUri);
}
// append extension
if (isSave && !ext && this.options.filters) {
for (let i = 0; i < this.options.filters.length; i++) {
if (this.options.filters[i].extensions[0] !== '*') {
ext = '.' + this.options.filters[i].extensions[0];
this.trailing = this.trailing ? this.trailing + ext : ext;
break;
}
}
}
}
return new Promise<URI | undefined>(async (resolve) => {
this.filePickBox = this.quickInputService.createQuickPick<FileQuickPickItem>();
this.busy = true;
this.filePickBox.matchOnLabel = false;
this.filePickBox.autoFocusOnList = false;
this.filePickBox.ignoreFocusOut = true;
this.filePickBox.ok = true;
if (this.options && this.options.availableFileSystems && (this.options.availableFileSystems.length > 1)) {
this.filePickBox.customButton = true;
this.filePickBox.customLabel = nls.localize('remoteFileDialog.local', 'Show Local');
let action;
if (isSave) {
action = SaveLocalFileAction;
} else {
action = this.allowFileSelection ? (this.allowFolderSelection ? OpenLocalFileFolderAction : OpenLocalFileAction) : OpenLocalFolderAction;
}
const keybinding = this.keybindingService.lookupKeybinding(action.ID);
if (keybinding) {
const label = keybinding.getLabel();
if (label) {
this.filePickBox.customHover = format('{0} ({1})', action.LABEL, label);
}
}
}
let isResolving: number = 0;
let isAcceptHandled = false;
this.currentFolder = homedir;
this.userEnteredPathSegment = '';
this.autoCompletePathSegment = '';
this.filePickBox.title = this.options.title;
this.filePickBox.value = this.pathFromUri(this.currentFolder, true);
this.filePickBox.valueSelection = [this.filePickBox.value.length, this.filePickBox.value.length];
this.filePickBox.items = [];
function doResolve(dialog: RemoteFileDialog, uri: URI | undefined) {
resolve(uri);
dialog.contextKey.set(false);
dialog.filePickBox.dispose();
dispose(dialog.disposables);
}
this.filePickBox.onDidCustom(() => {
if (isAcceptHandled || this.busy) {
return;
}
isAcceptHandled = true;
isResolving++;
if (this.options.availableFileSystems && (this.options.availableFileSystems.length > 1)) {
this.options.availableFileSystems.shift();
}
this.options.defaultUri = undefined;
this.filePickBox.hide();
if (isSave) {
// Remove defaultUri and filters to get a consistant experience with the keybinding.
this.options.defaultUri = undefined;
this.options.filters = undefined;
return this.fileDialogService.showSaveDialog(this.options).then(result => {
doResolve(this, result);
});
} else {
return this.fileDialogService.showOpenDialog(this.options).then(result => {
doResolve(this, result ? result[0] : undefined);
});
}
});
function handleAccept(dialog: RemoteFileDialog) {
if (dialog.busy) {
// Save the accept until the file picker is not busy.
dialog.onBusyChangeEmitter.event((busy: boolean) => {
if (!busy) {
handleAccept(dialog);
}
});
return;
} else if (isAcceptHandled) {
return;
}
isAcceptHandled = true;
isResolving++;
dialog.onDidAccept().then(resolveValue => {
if (resolveValue) {
dialog.filePickBox.hide();
doResolve(dialog, resolveValue);
} else if (dialog.hidden) {
doResolve(dialog, undefined);
} else {
isResolving--;
isAcceptHandled = false;
}
});
}
this.filePickBox.onDidAccept(_ => {
handleAccept(this);
});
this.filePickBox.onDidChangeActive(i => {
isAcceptHandled = false;
// update input box to match the first selected item
if ((i.length === 1) && this.isChangeFromUser()) {
this.filePickBox.validationMessage = undefined;
this.setAutoComplete(this.constructFullUserPath(), this.userEnteredPathSegment, i[0], true);
}
});
this.filePickBox.onDidChangeValue(async value => {
try {
// onDidChangeValue can also be triggered by the auto complete, so if it looks like the auto complete, don't do anything
if (this.isChangeFromUser()) {
// If the user has just entered more bad path, don't change anything
if (!equalsIgnoreCase(value, this.constructFullUserPath()) && !this.isBadSubpath(value)) {
this.filePickBox.validationMessage = undefined;
const filePickBoxUri = this.filePickBoxValue();
let updated: UpdateResult = UpdateResult.NotUpdated;
if (!resources.isEqual(this.currentFolder, filePickBoxUri, true)) {
updated = await this.tryUpdateItems(value, filePickBoxUri);
}
if (updated === UpdateResult.NotUpdated) {
this.setActiveItems(value);
}
} else {
this.filePickBox.activeItems = [];
}
}
} catch {
// Since any text can be entered in the input box, there is potential for error causing input. If this happens, do nothing.
}
});
this.filePickBox.onDidHide(() => {
this.hidden = true;
if (isResolving === 0) {
doResolve(this, undefined);
}
});
this.filePickBox.show();
this.contextKey.set(true);
await this.updateItems(homedir, true, this.trailing);
if (this.trailing) {
this.filePickBox.valueSelection = [this.filePickBox.value.length - this.trailing.length, this.filePickBox.value.length - ext.length];
} else {
this.filePickBox.valueSelection = [this.filePickBox.value.length, this.filePickBox.value.length];
}
this.busy = false;
});
}
private isBadSubpath(value: string) {
return this.badPath && (value.length > this.badPath.length) && equalsIgnoreCase(value.substring(0, this.badPath.length), this.badPath);
}
private isChangeFromUser(): boolean {
if (equalsIgnoreCase(this.filePickBox.value, this.pathAppend(this.currentFolder, this.userEnteredPathSegment + this.autoCompletePathSegment))
&& (this.activeItem === (this.filePickBox.activeItems ? this.filePickBox.activeItems[0] : undefined))) {
return false;
}
return true;
}
private constructFullUserPath(): string {
return this.pathAppend(this.currentFolder, this.userEnteredPathSegment);
}
private filePickBoxValue(): URI {
// The file pick box can't render everything, so we use the current folder to create the uri so that it is an existing path.
const directUri = this.remoteUriFrom(this.filePickBox.value);
const currentPath = this.pathFromUri(this.currentFolder);
if (equalsIgnoreCase(this.filePickBox.value, currentPath)) {
return this.currentFolder;
}
const currentDisplayUri = this.remoteUriFrom(currentPath);
const relativePath = resources.relativePath(currentDisplayUri, directUri);
const isSameRoot = (this.filePickBox.value.length > 1 && currentPath.length > 1) ? equalsIgnoreCase(this.filePickBox.value.substr(0, 2), currentPath.substr(0, 2)) : false;
if (relativePath && isSameRoot) {
const path = resources.joinPath(this.currentFolder, relativePath);
return resources.hasTrailingPathSeparator(directUri) ? resources.addTrailingPathSeparator(path) : path;
} else {
return directUri;
}
}
private async onDidAccept(): Promise<URI | undefined> {
this.busy = true;
if (this.filePickBox.activeItems.length === 1) {
const item = this.filePickBox.selectedItems[0];
if (item.isFolder) {
if (this.trailing) {
await this.updateItems(item.uri, true, this.trailing);
} else {
// When possible, cause the update to happen by modifying the input box.
// This allows all input box updates to happen first, and uses the same code path as the user typing.
const newPath = this.pathFromUri(item.uri);
if (startsWithIgnoreCase(newPath, this.filePickBox.value) && (equalsIgnoreCase(item.label, resources.basename(item.uri)))) {
this.filePickBox.valueSelection = [this.pathFromUri(this.currentFolder).length, this.filePickBox.value.length];
this.insertText(newPath, item.label);
} else if ((item.label === '..') && startsWithIgnoreCase(this.filePickBox.value, newPath)) {
this.filePickBox.valueSelection = [newPath.length, this.filePickBox.value.length];
this.insertText(newPath, '');
} else {
await this.updateItems(item.uri, true);
}
}
this.filePickBox.busy = false;
return;
}
} else {
// If the items have updated, don't try to resolve
if ((await this.tryUpdateItems(this.filePickBox.value, this.filePickBoxValue())) !== UpdateResult.NotUpdated) {
this.filePickBox.busy = false;
return;
}
}
let resolveValue: URI | undefined;
// Find resolve value
if (this.filePickBox.activeItems.length === 0) {
resolveValue = this.filePickBoxValue();
} else if (this.filePickBox.activeItems.length === 1) {
resolveValue = this.filePickBox.selectedItems[0].uri;
}
if (resolveValue) {
resolveValue = this.addPostfix(resolveValue);
}
if (await this.validate(resolveValue)) {
this.busy = false;
return resolveValue;
}
this.busy = false;
return undefined;
}
private async tryUpdateItems(value: string, valueUri: URI): Promise<UpdateResult> {
if ((value.length > 0) && ((value[value.length - 1] === '~') || (value[0] === '~'))) {
let newDir = this.userHome;
if ((value[0] === '~') && (value.length > 1)) {
newDir = resources.joinPath(newDir, value.substring(1));
}
await this.updateItems(newDir, true);
return UpdateResult.Updated;
} else if (!resources.isEqual(this.currentFolder, valueUri, true) && (this.endsWithSlash(value) || (!resources.isEqual(this.currentFolder, resources.dirname(valueUri), true) && resources.isEqualOrParent(this.currentFolder, resources.dirname(valueUri), true)))) {
let stat: IFileStat | undefined;
try {
stat = await this.fileService.resolve(valueUri);
} catch (e) {
// do nothing
}
if (stat && stat.isDirectory && (resources.basename(valueUri) !== '.') && this.endsWithSlash(value)) {
await this.updateItems(valueUri);
return UpdateResult.Updated;
} else if (this.endsWithSlash(value)) {
// The input box contains a path that doesn't exist on the system.
this.filePickBox.validationMessage = nls.localize('remoteFileDialog.badPath', 'The path does not exist.');
// Save this bad path. It can take too long to to a stat on every user entered character, but once a user enters a bad path they are likely
// to keep typing more bad path. We can compare against this bad path and see if the user entered path starts with it.
this.badPath = value;
return UpdateResult.InvalidPath;
} else {
const inputUriDirname = resources.dirname(valueUri);
if (!resources.isEqual(resources.removeTrailingPathSeparator(this.currentFolder), inputUriDirname, true)) {
let statWithoutTrailing: IFileStat | undefined;
try {
statWithoutTrailing = await this.fileService.resolve(inputUriDirname);
} catch (e) {
// do nothing
}
if (statWithoutTrailing && statWithoutTrailing.isDirectory && (resources.basename(valueUri) !== '.')) {
await this.updateItems(inputUriDirname, false, resources.basename(valueUri));
this.badPath = undefined;
return UpdateResult.Updated;
}
}
}
}
this.badPath = undefined;
return UpdateResult.NotUpdated;
}
private setActiveItems(value: string) {
const inputBasename = resources.basename(this.remoteUriFrom(value));
// Make sure that the folder whose children we are currently viewing matches the path in the input
const userPath = this.constructFullUserPath();
if (equalsIgnoreCase(userPath, value.substring(0, userPath.length))) {
let hasMatch = false;
for (let i = 0; i < this.filePickBox.items.length; i++) {
const item = <FileQuickPickItem>this.filePickBox.items[i];
if (this.setAutoComplete(value, inputBasename, item)) {
hasMatch = true;
break;
}
}
if (!hasMatch) {
this.userEnteredPathSegment = inputBasename;
this.autoCompletePathSegment = '';
this.filePickBox.activeItems = [];
}
} else {
if (!equalsIgnoreCase(inputBasename, resources.basename(this.currentFolder))) {
this.userEnteredPathSegment = inputBasename;
} else {
this.userEnteredPathSegment = '';
}
this.autoCompletePathSegment = '';
}
}
private setAutoComplete(startingValue: string, startingBasename: string, quickPickItem: FileQuickPickItem, force: boolean = false): boolean {
if (this.busy) {
// We're in the middle of something else. Doing an auto complete now can result jumbled or incorrect autocompletes.
this.userEnteredPathSegment = startingBasename;
this.autoCompletePathSegment = '';
return false;
}
const itemBasename = this.trimTrailingSlash(quickPickItem.label);
// Either force the autocomplete, or the old value should be one smaller than the new value and match the new value.
if (itemBasename === '..') {
// Don't match on the up directory item ever.
this.userEnteredPathSegment = startingValue;
this.autoCompletePathSegment = '';
this.activeItem = quickPickItem;
if (force) {
// clear any selected text
this.insertText(this.userEnteredPathSegment, '');
}
return false;
} else if (!force && (itemBasename.length >= startingBasename.length) && equalsIgnoreCase(itemBasename.substr(0, startingBasename.length), startingBasename)) {
this.userEnteredPathSegment = startingBasename;
this.activeItem = quickPickItem;
// Changing the active items will trigger the onDidActiveItemsChanged. Clear the autocomplete first, then set it after.
this.autoCompletePathSegment = '';
this.filePickBox.activeItems = [quickPickItem];
return true;
} else if (force && (!equalsIgnoreCase(quickPickItem.label, (this.userEnteredPathSegment + this.autoCompletePathSegment)))) {
this.userEnteredPathSegment = '';
this.autoCompletePathSegment = this.trimTrailingSlash(itemBasename);
this.activeItem = quickPickItem;
this.filePickBox.valueSelection = [this.pathFromUri(this.currentFolder, true).length, this.filePickBox.value.length];
// use insert text to preserve undo buffer
this.insertText(this.pathAppend(this.currentFolder, this.autoCompletePathSegment), this.autoCompletePathSegment);
this.filePickBox.valueSelection = [this.filePickBox.value.length - this.autoCompletePathSegment.length, this.filePickBox.value.length];
return true;
} else {
this.userEnteredPathSegment = startingBasename;
this.autoCompletePathSegment = '';
return false;
}
}
private insertText(wholeValue: string, insertText: string) {
if (this.filePickBox.inputHasFocus()) {
document.execCommand('insertText', false, insertText);
} else {
this.filePickBox.value = wholeValue;
}
}
private addPostfix(uri: URI): URI {
let result = uri;
if (this.requiresTrailing && this.options.filters && this.options.filters.length > 0) {
// Make sure that the suffix is added. If the user deleted it, we automatically add it here
let hasExt: boolean = false;
const currentExt = resources.extname(uri).substr(1);
for (let i = 0; i < this.options.filters.length; i++) {
for (let j = 0; j < this.options.filters[i].extensions.length; j++) {
if ((this.options.filters[i].extensions[j] === '*') || (this.options.filters[i].extensions[j] === currentExt)) {
hasExt = true;
break;
}
}
if (hasExt) {
break;
}
}
if (!hasExt) {
result = resources.joinPath(resources.dirname(uri), resources.basename(uri) + '.' + this.options.filters[0].extensions[0]);
}
}
return result;
}
private trimTrailingSlash(path: string): string {
return ((path.length > 1) && this.endsWithSlash(path)) ? path.substr(0, path.length - 1) : path;
}
private yesNoPrompt(uri: URI, message: string): Promise<boolean> {
interface YesNoItem extends IQuickPickItem {
value: boolean;
}
const prompt = this.quickInputService.createQuickPick<YesNoItem>();
prompt.title = message;
prompt.ignoreFocusOut = true;
prompt.ok = true;
prompt.customButton = true;
prompt.customLabel = nls.localize('remoteFileDialog.cancel', 'Cancel');
prompt.value = this.pathFromUri(uri);
let isResolving = false;
return new Promise<boolean>(resolve => {
prompt.onDidAccept(() => {
isResolving = true;
prompt.hide();
resolve(true);
});
prompt.onDidHide(() => {
if (!isResolving) {
resolve(false);
}
this.filePickBox.show();
this.hidden = false;
this.filePickBox.items = this.filePickBox.items;
prompt.dispose();
});
prompt.onDidChangeValue(() => {
prompt.hide();
});
prompt.onDidCustom(() => {
prompt.hide();
});
prompt.show();
});
}
private async validate(uri: URI | undefined): Promise<boolean> {
if (uri === undefined) {
this.filePickBox.validationMessage = nls.localize('remoteFileDialog.invalidPath', 'Please enter a valid path.');
return Promise.resolve(false);
}
let stat: IFileStat | undefined;
let statDirname: IFileStat | undefined;
try {
statDirname = await this.fileService.resolve(resources.dirname(uri));
stat = await this.fileService.resolve(uri);
} catch (e) {
// do nothing
}
if (this.requiresTrailing) { // save
if (stat && stat.isDirectory) {
// Can't do this
this.filePickBox.validationMessage = nls.localize('remoteFileDialog.validateFolder', 'The folder already exists. Please use a new file name.');
return Promise.resolve(false);
} else if (stat) {
// Replacing a file.
// Show a yes/no prompt
const message = nls.localize('remoteFileDialog.validateExisting', '{0} already exists. Are you sure you want to overwrite it?', resources.basename(uri));
return this.yesNoPrompt(uri, message);
} else if (!(isValidBasename(resources.basename(uri), await this.isWindowsOS()))) {
// Filename not allowed
this.filePickBox.validationMessage = nls.localize('remoteFileDialog.validateBadFilename', 'Please enter a valid file name.');
return Promise.resolve(false);
} else if (!statDirname || !statDirname.isDirectory) {
// Folder to save in doesn't exist
this.filePickBox.validationMessage = nls.localize('remoteFileDialog.validateNonexistentDir', 'Please enter a path that exists.');
return Promise.resolve(false);
}
} else { // open
if (!stat) {
// File or folder doesn't exist
this.filePickBox.validationMessage = nls.localize('remoteFileDialog.validateNonexistentDir', 'Please enter a path that exists.');
return Promise.resolve(false);
} else if (stat.isDirectory && !this.allowFolderSelection) {
// Folder selected when folder selection not permitted
this.filePickBox.validationMessage = nls.localize('remoteFileDialog.validateFileOnly', 'Please select a file.');
return Promise.resolve(false);
} else if (!stat.isDirectory && !this.allowFileSelection) {
// File selected when file selection not permitted
this.filePickBox.validationMessage = nls.localize('remoteFileDialog.validateFolderOnly', 'Please select a folder.');
return Promise.resolve(false);
}
}
return Promise.resolve(true);
}
private async updateItems(newFolder: URI, force: boolean = false, trailing?: string) {
this.busy = true;
this.userEnteredPathSegment = trailing ? trailing : '';
this.autoCompletePathSegment = '';
const newValue = trailing ? this.pathFromUri(resources.joinPath(newFolder, trailing)) : this.pathFromUri(newFolder, true);
this.currentFolder = resources.addTrailingPathSeparator(newFolder, this.separator);
return this.createItems(this.currentFolder).then(items => {
this.filePickBox.items = items;
if (this.allowFolderSelection) {
this.filePickBox.activeItems = [];
}
// the user might have continued typing while we were updating. Only update the input box if it doesn't match the directory.
if (!equalsIgnoreCase(this.filePickBox.value, newValue) && force) {
this.filePickBox.valueSelection = [0, this.filePickBox.value.length];
this.insertText(newValue, newValue);
}
if (force && trailing) {
// Keep the cursor position in front of the save as name.
this.filePickBox.valueSelection = [this.filePickBox.value.length - trailing.length, this.filePickBox.value.length - trailing.length];
} else if (!trailing) {
// If there is trailing, we don't move the cursor. If there is no trailing, cursor goes at the end.
this.filePickBox.valueSelection = [this.filePickBox.value.length, this.filePickBox.value.length];
}
this.busy = false;
});
}
private pathFromUri(uri: URI, endWithSeparator: boolean = false): string {
let result: string = uri.fsPath.replace(/\n/g, '');
if (this.separator === '/') {
result = result.replace(/\\/g, this.separator);
} else {
result = result.replace(/\//g, this.separator);
}
if (endWithSeparator && !this.endsWithSlash(result)) {
result = result + this.separator;
}
return result;
}
private pathAppend(uri: URI, additional: string): string {
if ((additional === '..') || (additional === '.')) {
const basePath = this.pathFromUri(uri);
return basePath + (this.endsWithSlash(basePath) ? '' : this.separator) + additional;
} else {
return this.pathFromUri(resources.joinPath(uri, additional));
}
}
private async isWindowsOS(): Promise<boolean> {
let isWindowsOS = isWindows;
const env = await this.getRemoteAgentEnvironment();
if (env) {
isWindowsOS = env.os === OperatingSystem.Windows;
}
return isWindowsOS;
}
private endsWithSlash(s: string) {
return /[\/\\]$/.test(s);
}
private basenameWithTrailingSlash(fullPath: URI): string {
const child = this.pathFromUri(fullPath, true);
const parent = this.pathFromUri(resources.dirname(fullPath), true);
return child.substring(parent.length);
}
private createBackItem(currFolder: URI): FileQuickPickItem | null {
const parentFolder = resources.dirname(currFolder)!;
if (!resources.isEqual(currFolder, parentFolder, true)) {
return { label: '..', uri: resources.addTrailingPathSeparator(parentFolder, this.separator), isFolder: true };
}
return null;
}
private async createItems(currentFolder: URI): Promise<FileQuickPickItem[]> {
const result: FileQuickPickItem[] = [];
const backDir = this.createBackItem(currentFolder);
try {
const folder = await this.fileService.resolve(currentFolder);
const fileNames = folder.children ? folder.children.map(child => child.name) : [];
const items = await Promise.all(fileNames.map(fileName => this.createItem(fileName, currentFolder)));
for (let item of items) {
if (item) {
result.push(item);
}
}
} catch (e) {
// ignore
console.log(e);
}
const sorted = result.sort((i1, i2) => {
if (i1.isFolder !== i2.isFolder) {
return i1.isFolder ? -1 : 1;
}
const trimmed1 = this.endsWithSlash(i1.label) ? i1.label.substr(0, i1.label.length - 1) : i1.label;
const trimmed2 = this.endsWithSlash(i2.label) ? i2.label.substr(0, i2.label.length - 1) : i2.label;
return trimmed1.localeCompare(trimmed2);
});
if (backDir) {
sorted.unshift(backDir);
}
return sorted;
}
private filterFile(file: URI): boolean {
if (this.options.filters) {
const ext = resources.extname(file);
for (let i = 0; i < this.options.filters.length; i++) {
for (let j = 0; j < this.options.filters[i].extensions.length; j++) {
if (ext === ('.' + this.options.filters[i].extensions[j])) {
return true;
}
}
}
return false;
}
return true;
}
private async createItem(filename: string, parent: URI): Promise<FileQuickPickItem | undefined> {
let fullPath = resources.joinPath(parent, filename);
try {
const stat = await this.fileService.resolve(fullPath);
if (stat.isDirectory) {
filename = this.basenameWithTrailingSlash(fullPath);
fullPath = resources.addTrailingPathSeparator(fullPath, this.separator);
return { label: filename, uri: fullPath, isFolder: true, iconClasses: getIconClasses(this.modelService, this.modeService, fullPath || undefined, FileKind.FOLDER) };
} else if (!stat.isDirectory && this.allowFileSelection && this.filterFile(fullPath)) {
return { label: filename, uri: fullPath, isFolder: false, iconClasses: getIconClasses(this.modelService, this.modeService, fullPath || undefined) };
}
return undefined;
} catch (e) {
return undefined;
}
}
} | src/vs/workbench/services/dialogs/browser/remoteFileDialog.ts | 1 | https://github.com/microsoft/vscode/commit/985de26b3446636f86e2bb2b14dbeb9ec1e33207 | [
0.9990614056587219,
0.024310899898409843,
0.00016029142716433853,
0.00017192855011671782,
0.15310174226760864
] |
{
"id": 2,
"code_window": [
"\t) {\n",
"\t\tsuper(id, label);\n",
"\t}\n",
"\n",
"\trun(event?: any, data?: ITelemetryData): Promise<any> {\n",
"\t\treturn this.dialogService.pickFileToSave({ availableFileSystems: [Schemas.file] });\n",
"\t}\n",
"}\n",
"\n",
"export class OpenFolderAction extends Action {\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\tasync run(event?: any, data?: ITelemetryData): Promise<any> {\n",
"\t\tlet resource: URI | undefined = toResource(this.editorService.activeEditor);\n",
"\t\tconst options: ISaveOptions = { force: true, availableFileSystems: [Schemas.file] };\n",
"\t\tif (resource) {\n",
"\t\t\treturn this.textFileService.saveAs(resource, undefined, options);\n",
"\t\t}\n"
],
"file_path": "src/vs/workbench/browser/actions/workspaceActions.ts",
"type": "replace",
"edit_start_line_idx": 69
} | [
{
"c": "#",
"t": "source.cpp source.cpp meta.preprocessor.cpp keyword.control.directive.conditional.cpp punctuation.definition.directive.cpp",
"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": "ifndef",
"t": "source.cpp source.cpp meta.preprocessor.cpp keyword.control.directive.conditional.cpp",
"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.cpp source.cpp meta.preprocessor.cpp",
"r": {
"dark_plus": "meta.preprocessor: #569CD6",
"light_plus": "meta.preprocessor: #0000FF",
"dark_vs": "meta.preprocessor: #569CD6",
"light_vs": "meta.preprocessor: #0000FF",
"hc_black": "meta.preprocessor: #569CD6"
}
},
{
"c": "_UCRT",
"t": "source.cpp source.cpp meta.preprocessor.cpp entity.name.function.preprocessor.cpp",
"r": {
"dark_plus": "entity.name.function: #DCDCAA",
"light_plus": "entity.name.function: #795E26",
"dark_vs": "meta.preprocessor: #569CD6",
"light_vs": "meta.preprocessor: #0000FF",
"hc_black": "entity.name.function: #DCDCAA"
}
},
{
"c": "#",
"t": "source.cpp source.cpp meta.preprocessor.macro.cpp keyword.control.directive.define.cpp punctuation.definition.directive.cpp",
"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": "define",
"t": "source.cpp source.cpp meta.preprocessor.macro.cpp keyword.control.directive.define.cpp",
"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.cpp source.cpp meta.preprocessor.macro.cpp",
"r": {
"dark_plus": "meta.preprocessor: #569CD6",
"light_plus": "meta.preprocessor: #0000FF",
"dark_vs": "meta.preprocessor: #569CD6",
"light_vs": "meta.preprocessor: #0000FF",
"hc_black": "meta.preprocessor: #569CD6"
}
},
{
"c": "_UCRT",
"t": "source.cpp source.cpp meta.preprocessor.macro.cpp entity.name.function.preprocessor.cpp",
"r": {
"dark_plus": "entity.name.function: #DCDCAA",
"light_plus": "entity.name.function: #795E26",
"dark_vs": "meta.preprocessor: #569CD6",
"light_vs": "meta.preprocessor: #0000FF",
"hc_black": "entity.name.function: #DCDCAA"
}
},
{
"c": "#",
"t": "source.cpp source.cpp meta.preprocessor.cpp keyword.control.directive.conditional.cpp punctuation.definition.directive.cpp",
"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": "endif",
"t": "source.cpp source.cpp meta.preprocessor.cpp keyword.control.directive.conditional.cpp",
"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"
}
}
] | extensions/cpp/test/colorize-results/test-23850_cpp.json | 0 | https://github.com/microsoft/vscode/commit/985de26b3446636f86e2bb2b14dbeb9ec1e33207 | [
0.00017607062181923538,
0.00017488503362983465,
0.00017302713240496814,
0.0001753214601194486,
0.0000011058328936996986
] |
{
"id": 2,
"code_window": [
"\t) {\n",
"\t\tsuper(id, label);\n",
"\t}\n",
"\n",
"\trun(event?: any, data?: ITelemetryData): Promise<any> {\n",
"\t\treturn this.dialogService.pickFileToSave({ availableFileSystems: [Schemas.file] });\n",
"\t}\n",
"}\n",
"\n",
"export class OpenFolderAction extends Action {\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\tasync run(event?: any, data?: ITelemetryData): Promise<any> {\n",
"\t\tlet resource: URI | undefined = toResource(this.editorService.activeEditor);\n",
"\t\tconst options: ISaveOptions = { force: true, availableFileSystems: [Schemas.file] };\n",
"\t\tif (resource) {\n",
"\t\t\treturn this.textFileService.saveAs(resource, undefined, options);\n",
"\t\t}\n"
],
"file_path": "src/vs/workbench/browser/actions/workspaceActions.ts",
"type": "replace",
"edit_start_line_idx": 69
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import * as DOM from 'vs/base/browser/dom';
import { dispose, IDisposable, combinedDisposable, toDisposable } from 'vs/base/common/lifecycle';
import { IAction } from 'vs/base/common/actions';
import { Separator } from 'vs/base/browser/ui/actionbar/actionbar';
import { firstIndex } from 'vs/base/common/arrays';
import { IExtensionService } from 'vs/workbench/services/extensions/common/extensions';
import { IContextMenuService } from 'vs/platform/contextview/browser/contextView';
import { IViewDescriptor, IViewsViewlet, IViewContainersRegistry, Extensions as ViewContainerExtensions, IView } from 'vs/workbench/common/views';
import { ITelemetryService } from 'vs/platform/telemetry/common/telemetry';
import { IThemeService } from 'vs/platform/theme/common/themeService';
import { IInstantiationService } from 'vs/platform/instantiation/common/instantiation';
import { IStorageService, StorageScope } from 'vs/platform/storage/common/storage';
import { IWorkspaceContextService } from 'vs/platform/workspace/common/workspace';
import { IContextKeyService } from 'vs/platform/contextkey/common/contextkey';
import { StandardMouseEvent } from 'vs/base/browser/mouseEvent';
import { PanelViewlet, ViewletPanel, IViewletPanelOptions } from 'vs/workbench/browser/parts/views/panelViewlet';
import { DefaultPanelDndController } from 'vs/base/browser/ui/splitview/panelview';
import { WorkbenchTree, IListService } from 'vs/platform/list/browser/listService';
import { IWorkbenchThemeService, IFileIconTheme } from 'vs/workbench/services/themes/common/workbenchThemeService';
import { ITreeConfiguration, ITreeOptions } from 'vs/base/parts/tree/browser/tree';
import { Event } from 'vs/base/common/event';
import { IConfigurationService } from 'vs/platform/configuration/common/configuration';
import { IWorkbenchLayoutService } from 'vs/workbench/services/layout/browser/layoutService';
import { localize } from 'vs/nls';
import { IAddedViewDescriptorRef, IViewDescriptorRef, PersistentContributableViewsModel } from 'vs/workbench/browser/parts/views/views';
import { Registry } from 'vs/platform/registry/common/platform';
import { MementoObject } from 'vs/workbench/common/memento';
export interface IViewletViewOptions extends IViewletPanelOptions {
viewletState: MementoObject;
}
export abstract class ViewContainerViewlet extends PanelViewlet implements IViewsViewlet {
private readonly viewletState: MementoObject;
private didLayout = false;
private dimension: DOM.Dimension;
private areExtensionsReady: boolean = false;
private readonly visibleViewsCountFromCache: number;
private readonly visibleViewsStorageId: string;
protected readonly viewsModel: PersistentContributableViewsModel;
private viewDisposables: IDisposable[] = [];
constructor(
id: string,
viewletStateStorageId: string,
showHeaderInTitleWhenSingleView: boolean,
@IConfigurationService configurationService: IConfigurationService,
@IWorkbenchLayoutService layoutService: IWorkbenchLayoutService,
@ITelemetryService telemetryService: ITelemetryService,
@IStorageService protected storageService: IStorageService,
@IInstantiationService protected instantiationService: IInstantiationService,
@IThemeService themeService: IThemeService,
@IContextMenuService protected contextMenuService: IContextMenuService,
@IExtensionService protected extensionService: IExtensionService,
@IWorkspaceContextService protected contextService: IWorkspaceContextService
) {
super(id, { showHeaderInTitleWhenSingleView, dnd: new DefaultPanelDndController() }, configurationService, layoutService, contextMenuService, telemetryService, themeService, storageService);
const container = Registry.as<IViewContainersRegistry>(ViewContainerExtensions.ViewContainersRegistry).get(id);
this.viewsModel = this._register(this.instantiationService.createInstance(PersistentContributableViewsModel, container, viewletStateStorageId));
this.viewletState = this.getMemento(StorageScope.WORKSPACE);
this.visibleViewsStorageId = `${id}.numberOfVisibleViews`;
this.visibleViewsCountFromCache = this.storageService.getNumber(this.visibleViewsStorageId, StorageScope.WORKSPACE, 1);
this._register(toDisposable(() => this.viewDisposables = dispose(this.viewDisposables)));
}
create(parent: HTMLElement): void {
super.create(parent);
this._register(this.onDidSashChange(() => this.saveViewSizes()));
this.viewsModel.onDidAdd(added => this.onDidAddViews(added));
this.viewsModel.onDidRemove(removed => this.onDidRemoveViews(removed));
const addedViews: IAddedViewDescriptorRef[] = this.viewsModel.visibleViewDescriptors.map((viewDescriptor, index) => {
const size = this.viewsModel.getSize(viewDescriptor.id);
const collapsed = this.viewsModel.isCollapsed(viewDescriptor.id);
return ({ viewDescriptor, index, size, collapsed });
});
if (addedViews.length) {
this.onDidAddViews(addedViews);
}
// Update headers after and title contributed views after available, since we read from cache in the beginning to know if the viewlet has single view or not. Ref #29609
this.extensionService.whenInstalledExtensionsRegistered().then(() => {
this.areExtensionsReady = true;
if (this.panels.length) {
this.updateTitleArea();
this.updateViewHeaders();
}
});
this.focus();
}
getContextMenuActions(): IAction[] {
const result: IAction[] = [];
const viewToggleActions = this.viewsModel.viewDescriptors.map(viewDescriptor => (<IAction>{
id: `${viewDescriptor.id}.toggleVisibility`,
label: viewDescriptor.name,
checked: this.viewsModel.isVisible(viewDescriptor.id),
enabled: viewDescriptor.canToggleVisibility,
run: () => this.toggleViewVisibility(viewDescriptor.id)
}));
result.push(...viewToggleActions);
const parentActions = super.getContextMenuActions();
if (viewToggleActions.length && parentActions.length) {
result.push(new Separator());
}
result.push(...parentActions);
return result;
}
setVisible(visible: boolean): void {
super.setVisible(visible);
this.panels.filter(view => view.isVisible() !== visible)
.map((view) => view.setVisible(visible));
}
openView(id: string, focus?: boolean): IView {
if (focus) {
this.focus();
}
let view = this.getView(id);
if (!view) {
this.toggleViewVisibility(id);
}
view = this.getView(id);
view.setExpanded(true);
if (focus) {
view.focus();
}
return view;
}
movePanel(from: ViewletPanel, to: ViewletPanel): void {
const fromIndex = firstIndex(this.panels, panel => panel === from);
const toIndex = firstIndex(this.panels, panel => panel === to);
const fromViewDescriptor = this.viewsModel.visibleViewDescriptors[fromIndex];
const toViewDescriptor = this.viewsModel.visibleViewDescriptors[toIndex];
super.movePanel(from, to);
this.viewsModel.move(fromViewDescriptor.id, toViewDescriptor.id);
}
layout(dimension: DOM.Dimension): void {
super.layout(dimension);
this.dimension = dimension;
if (this.didLayout) {
this.saveViewSizes();
} else {
this.didLayout = true;
this.restoreViewSizes();
}
}
getOptimalWidth(): number {
const additionalMargin = 16;
const optimalWidth = Math.max(...this.panels.map(view => view.getOptimalWidth() || 0));
return optimalWidth + additionalMargin;
}
protected isSingleView(): boolean {
if (!super.isSingleView()) {
return false;
}
if (!this.areExtensionsReady) {
// Check in cache so that view do not jump. See #29609
return this.visibleViewsCountFromCache === 1;
}
return true;
}
protected createView(viewDescriptor: IViewDescriptor, options: IViewletViewOptions): ViewletPanel {
return (this.instantiationService as any).createInstance(viewDescriptor.ctorDescriptor.ctor, ...(viewDescriptor.ctorDescriptor.arguments || []), options) as ViewletPanel;
}
protected getView(id: string): ViewletPanel {
return this.panels.filter(view => view.id === id)[0];
}
protected onDidAddViews(added: IAddedViewDescriptorRef[]): ViewletPanel[] {
const panelsToAdd: { panel: ViewletPanel, size: number, index: number }[] = [];
for (const { viewDescriptor, collapsed, index, size } of added) {
const panel = this.createView(viewDescriptor,
{
id: viewDescriptor.id,
title: viewDescriptor.name,
actionRunner: this.getActionRunner(),
expanded: !collapsed,
viewletState: this.viewletState
});
panel.render();
const contextMenuDisposable = DOM.addDisposableListener(panel.draggableElement, 'contextmenu', e => {
e.stopPropagation();
e.preventDefault();
this.onContextMenu(new StandardMouseEvent(e), viewDescriptor);
});
const collapseDisposable = Event.latch(Event.map(panel.onDidChange, () => !panel.isExpanded()))(collapsed => {
this.viewsModel.setCollapsed(viewDescriptor.id, collapsed);
});
this.viewDisposables.splice(index, 0, combinedDisposable(contextMenuDisposable, collapseDisposable));
panelsToAdd.push({ panel, size: size || panel.minimumSize, index });
}
this.addPanels(panelsToAdd);
this.restoreViewSizes();
const panels: ViewletPanel[] = [];
for (const { panel } of panelsToAdd) {
panel.setVisible(this.isVisible());
panels.push(panel);
}
return panels;
}
private onDidRemoveViews(removed: IViewDescriptorRef[]): void {
removed = removed.sort((a, b) => b.index - a.index);
const panelsToRemove: ViewletPanel[] = [];
for (const { index } of removed) {
const [disposable] = this.viewDisposables.splice(index, 1);
disposable.dispose();
panelsToRemove.push(this.panels[index]);
}
this.removePanels(panelsToRemove);
dispose(panelsToRemove);
}
private onContextMenu(event: StandardMouseEvent, viewDescriptor: IViewDescriptor): void {
event.stopPropagation();
event.preventDefault();
const actions: IAction[] = [];
actions.push(<IAction>{
id: `${viewDescriptor.id}.removeView`,
label: localize('hideView', "Hide"),
enabled: viewDescriptor.canToggleVisibility,
run: () => this.toggleViewVisibility(viewDescriptor.id)
});
const otherActions = this.getContextMenuActions();
if (otherActions.length) {
actions.push(...[new Separator(), ...otherActions]);
}
let anchor: { x: number, y: number } = { x: event.posx, y: event.posy };
this.contextMenuService.showContextMenu({
getAnchor: () => anchor,
getActions: () => actions
});
}
private toggleViewVisibility(viewId: string): void {
const visible = !this.viewsModel.isVisible(viewId);
/* __GDPR__
"views.toggleVisibility" : {
"viewId" : { "classification": "SystemMetaData", "purpose": "FeatureInsight" },
"visible": { "classification": "SystemMetaData", "purpose": "FeatureInsight" }
}
*/
this.telemetryService.publicLog('views.toggledVisibility', { viewId, visible });
this.viewsModel.setVisible(viewId, visible);
}
private saveViewSizes(): void {
// Save size only when the layout has happened
if (this.didLayout) {
for (const view of this.panels) {
this.viewsModel.setSize(view.id, this.getPanelSize(view));
}
}
}
private restoreViewSizes(): void {
// Restore sizes only when the layout has happened
if (this.didLayout) {
let initialSizes;
for (let i = 0; i < this.viewsModel.visibleViewDescriptors.length; i++) {
const panel = this.panels[i];
const viewDescriptor = this.viewsModel.visibleViewDescriptors[i];
const size = this.viewsModel.getSize(viewDescriptor.id);
if (typeof size === 'number') {
this.resizePanel(panel, size);
} else {
initialSizes = initialSizes ? initialSizes : this.computeInitialSizes();
this.resizePanel(panel, initialSizes[panel.id] || 200);
}
}
}
}
private computeInitialSizes(): { [id: string]: number } {
let sizes = {};
if (this.dimension) {
const totalWeight = this.viewsModel.visibleViewDescriptors.reduce((totalWeight, { weight }) => totalWeight + (weight || 20), 0);
for (const viewDescriptor of this.viewsModel.visibleViewDescriptors) {
sizes[viewDescriptor.id] = this.dimension.height * (viewDescriptor.weight || 20) / totalWeight;
}
}
return sizes;
}
protected saveState(): void {
this.panels.forEach((view) => view.saveState());
this.storageService.store(this.visibleViewsStorageId, this.length, StorageScope.WORKSPACE);
super.saveState();
}
}
export class FileIconThemableWorkbenchTree extends WorkbenchTree {
constructor(
container: HTMLElement,
configuration: ITreeConfiguration,
options: ITreeOptions,
@IContextKeyService contextKeyService: IContextKeyService,
@IListService listService: IListService,
@IThemeService themeService: IWorkbenchThemeService,
@IConfigurationService configurationService: IConfigurationService,
@IInstantiationService instantiationService: IInstantiationService
) {
super(container, configuration, { ...options, ...{ showTwistie: false, twistiePixels: 12 } }, contextKeyService, listService, themeService, instantiationService, configurationService);
DOM.addClass(container, 'file-icon-themable-tree');
DOM.addClass(container, 'show-file-icons');
const onFileIconThemeChange = (fileIconTheme: IFileIconTheme) => {
DOM.toggleClass(container, 'align-icons-and-twisties', fileIconTheme.hasFileIcons && !fileIconTheme.hasFolderIcons);
DOM.toggleClass(container, 'hide-arrows', fileIconTheme.hidesExplorerArrows === true);
};
this.disposables.push(themeService.onDidFileIconThemeChange(onFileIconThemeChange));
onFileIconThemeChange(themeService.getFileIconTheme());
}
}
| src/vs/workbench/browser/parts/views/viewsViewlet.ts | 0 | https://github.com/microsoft/vscode/commit/985de26b3446636f86e2bb2b14dbeb9ec1e33207 | [
0.00020174089877400547,
0.00017130348714999855,
0.00015941227320581675,
0.00017151478095911443,
0.000006817662324465346
] |
{
"id": 2,
"code_window": [
"\t) {\n",
"\t\tsuper(id, label);\n",
"\t}\n",
"\n",
"\trun(event?: any, data?: ITelemetryData): Promise<any> {\n",
"\t\treturn this.dialogService.pickFileToSave({ availableFileSystems: [Schemas.file] });\n",
"\t}\n",
"}\n",
"\n",
"export class OpenFolderAction extends Action {\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\tasync run(event?: any, data?: ITelemetryData): Promise<any> {\n",
"\t\tlet resource: URI | undefined = toResource(this.editorService.activeEditor);\n",
"\t\tconst options: ISaveOptions = { force: true, availableFileSystems: [Schemas.file] };\n",
"\t\tif (resource) {\n",
"\t\t\treturn this.textFileService.saveAs(resource, undefined, options);\n",
"\t\t}\n"
],
"file_path": "src/vs/workbench/browser/actions/workspaceActions.ts",
"type": "replace",
"edit_start_line_idx": 69
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import { Application, Quality } from '../../application';
export function setup() {
describe('Extensions', () => {
it(`install and activate vscode-smoketest-check extension`, async function () {
const app = this.app as Application;
if (app.quality === Quality.Dev) {
this.skip();
return;
}
await app.workbench.extensions.openExtensionsViewlet();
await app.workbench.extensions.installExtension('michelkaporin.vscode-smoketest-check', 'vscode-smoketest-check');
await app.workbench.extensions.waitForExtensionsViewlet();
if (app.remote) {
await app.reload();
}
await app.workbench.quickopen.runCommand('Smoke Test Check');
await app.workbench.statusbar.waitForStatusbarText('smoke test', 'VS Code Smoke Test Check');
});
});
} | test/smoke/src/areas/extensions/extensions.test.ts | 0 | https://github.com/microsoft/vscode/commit/985de26b3446636f86e2bb2b14dbeb9ec1e33207 | [
0.0001751525269355625,
0.0001712454977678135,
0.00016293249791488051,
0.00017344849766232073,
0.000004853785867453553
] |
{
"id": 3,
"code_window": [
"\t\treturn this.filePickBox.busy;\n",
"\t}\n",
"\n",
"\tpublic async showOpenDialog(options: IOpenDialogOptions = {}): Promise<URI | undefined> {\n",
"\t\tthis.scheme = this.getScheme(options.defaultUri, options.availableFileSystems);\n",
"\t\tthis.userHome = await this.getUserHome();\n",
"\t\tconst newOptions = await this.getOptions(options);\n",
"\t\tif (!newOptions) {\n",
"\t\t\treturn Promise.resolve(undefined);\n",
"\t\t}\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\tthis.scheme = this.getScheme(options.availableFileSystems);\n"
],
"file_path": "src/vs/workbench/services/dialogs/browser/remoteFileDialog.ts",
"type": "replace",
"edit_start_line_idx": 100
} | /*---------------------------------------------------------------------------------------------
* 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 resources from 'vs/base/common/resources';
import * as objects from 'vs/base/common/objects';
import { IFileService, IFileStat, FileKind } from 'vs/platform/files/common/files';
import { IQuickInputService, IQuickPickItem, IQuickPick } from 'vs/platform/quickinput/common/quickInput';
import { URI } from 'vs/base/common/uri';
import { isWindows, OperatingSystem } from 'vs/base/common/platform';
import { ISaveDialogOptions, IOpenDialogOptions, IFileDialogService } from 'vs/platform/dialogs/common/dialogs';
import { REMOTE_HOST_SCHEME } from 'vs/platform/remote/common/remoteHosts';
import { ILabelService } from 'vs/platform/label/common/label';
import { IWorkspaceContextService } from 'vs/platform/workspace/common/workspace';
import { INotificationService } from 'vs/platform/notification/common/notification';
import { IModelService } from 'vs/editor/common/services/modelService';
import { IModeService } from 'vs/editor/common/services/modeService';
import { getIconClasses } from 'vs/editor/common/services/getIconClasses';
import { Schemas } from 'vs/base/common/network';
import { IWorkbenchEnvironmentService } from 'vs/workbench/services/environment/common/environmentService';
import { IRemoteAgentService } from 'vs/workbench/services/remote/common/remoteAgentService';
import { IContextKeyService, IContextKey } from 'vs/platform/contextkey/common/contextkey';
import { equalsIgnoreCase, format, startsWithIgnoreCase } from 'vs/base/common/strings';
import { OpenLocalFileAction, OpenLocalFileFolderAction, OpenLocalFolderAction, SaveLocalFileAction } from 'vs/workbench/browser/actions/workspaceActions';
import { IKeybindingService } from 'vs/platform/keybinding/common/keybinding';
import { IRemoteAgentEnvironment } from 'vs/platform/remote/common/remoteAgentEnvironment';
import { isValidBasename } from 'vs/base/common/extpath';
import { RemoteFileDialogContext } from 'vs/workbench/browser/contextkeys';
import { Emitter } from 'vs/base/common/event';
import { IDisposable, dispose } from 'vs/base/common/lifecycle';
interface FileQuickPickItem extends IQuickPickItem {
uri: URI;
isFolder: boolean;
}
enum UpdateResult {
Updated,
Updating,
NotUpdated,
InvalidPath
}
export class RemoteFileDialog {
private options: IOpenDialogOptions;
private currentFolder: URI;
private filePickBox: IQuickPick<FileQuickPickItem>;
private hidden: boolean;
private allowFileSelection: boolean;
private allowFolderSelection: boolean;
private remoteAuthority: string | undefined;
private requiresTrailing: boolean;
private trailing: string | undefined;
private scheme: string = REMOTE_HOST_SCHEME;
private contextKey: IContextKey<boolean>;
private userEnteredPathSegment: string;
private autoCompletePathSegment: string;
private activeItem: FileQuickPickItem;
private userHome: URI;
private badPath: string | undefined;
private remoteAgentEnvironment: IRemoteAgentEnvironment | null;
private separator: string;
private onBusyChangeEmitter = new Emitter<boolean>();
protected disposables: IDisposable[] = [
this.onBusyChangeEmitter
];
constructor(
@IFileService private readonly fileService: IFileService,
@IQuickInputService private readonly quickInputService: IQuickInputService,
@ILabelService private readonly labelService: ILabelService,
@IWorkspaceContextService private readonly workspaceContextService: IWorkspaceContextService,
@INotificationService private readonly notificationService: INotificationService,
@IFileDialogService private readonly fileDialogService: IFileDialogService,
@IModelService private readonly modelService: IModelService,
@IModeService private readonly modeService: IModeService,
@IWorkbenchEnvironmentService private readonly environmentService: IWorkbenchEnvironmentService,
@IRemoteAgentService private readonly remoteAgentService: IRemoteAgentService,
@IKeybindingService private readonly keybindingService: IKeybindingService,
@IContextKeyService contextKeyService: IContextKeyService,
) {
this.remoteAuthority = this.environmentService.configuration.remoteAuthority;
this.contextKey = RemoteFileDialogContext.bindTo(contextKeyService);
}
set busy(busy: boolean) {
if (this.filePickBox.busy !== busy) {
this.filePickBox.busy = busy;
this.onBusyChangeEmitter.fire(busy);
}
}
get busy(): boolean {
return this.filePickBox.busy;
}
public async showOpenDialog(options: IOpenDialogOptions = {}): Promise<URI | undefined> {
this.scheme = this.getScheme(options.defaultUri, options.availableFileSystems);
this.userHome = await this.getUserHome();
const newOptions = await this.getOptions(options);
if (!newOptions) {
return Promise.resolve(undefined);
}
this.options = newOptions;
return this.pickResource();
}
public async showSaveDialog(options: ISaveDialogOptions): Promise<URI | undefined> {
this.scheme = this.getScheme(options.defaultUri, options.availableFileSystems);
this.userHome = await this.getUserHome();
this.requiresTrailing = true;
const newOptions = await this.getOptions(options, true);
if (!newOptions) {
return Promise.resolve(undefined);
}
this.options = newOptions;
this.options.canSelectFolders = true;
this.options.canSelectFiles = true;
return new Promise<URI | undefined>((resolve) => {
this.pickResource(true).then(folderUri => {
resolve(folderUri);
});
});
}
private getOptions(options: ISaveDialogOptions | IOpenDialogOptions, isSave: boolean = false): IOpenDialogOptions | undefined {
let defaultUri = options.defaultUri;
const filename = (defaultUri && isSave && (resources.dirname(defaultUri).path === '/')) ? resources.basename(defaultUri) : undefined;
if (!defaultUri || filename) {
defaultUri = this.userHome;
if (filename) {
defaultUri = resources.joinPath(defaultUri, filename);
}
}
if ((this.scheme !== Schemas.file) && !this.fileService.canHandleResource(defaultUri)) {
this.notificationService.info(nls.localize('remoteFileDialog.notConnectedToRemote', 'File system provider for {0} is not available.', defaultUri.toString()));
return undefined;
}
const newOptions: IOpenDialogOptions = objects.deepClone(options);
newOptions.defaultUri = defaultUri;
return newOptions;
}
private remoteUriFrom(path: string): URI {
path = path.replace(/\\/g, '/');
return resources.toLocalResource(URI.from({ scheme: this.scheme, path }), this.scheme === Schemas.file ? undefined : this.remoteAuthority);
}
private getScheme(defaultUri: URI | undefined, available: string[] | undefined): string {
return defaultUri ? defaultUri.scheme : (available ? available[0] : Schemas.file);
}
private async getRemoteAgentEnvironment(): Promise<IRemoteAgentEnvironment | null> {
if (this.remoteAgentEnvironment === undefined) {
this.remoteAgentEnvironment = await this.remoteAgentService.getEnvironment();
}
return this.remoteAgentEnvironment;
}
private async getUserHome(): Promise<URI> {
if (this.scheme !== Schemas.file) {
const env = await this.getRemoteAgentEnvironment();
if (env) {
return env.userHome;
}
}
return URI.from({ scheme: this.scheme, path: this.environmentService.userHome });
}
private async pickResource(isSave: boolean = false): Promise<URI | undefined> {
this.allowFolderSelection = !!this.options.canSelectFolders;
this.allowFileSelection = !!this.options.canSelectFiles;
this.separator = this.labelService.getSeparator(this.scheme, this.remoteAuthority);
this.hidden = false;
let homedir: URI = this.options.defaultUri ? this.options.defaultUri : this.workspaceContextService.getWorkspace().folders[0].uri;
let stat: IFileStat | undefined;
let ext: string = resources.extname(homedir);
if (this.options.defaultUri) {
try {
stat = await this.fileService.resolve(this.options.defaultUri);
} catch (e) {
// The file or folder doesn't exist
}
if (!stat || !stat.isDirectory) {
homedir = resources.dirname(this.options.defaultUri);
this.trailing = resources.basename(this.options.defaultUri);
}
// append extension
if (isSave && !ext && this.options.filters) {
for (let i = 0; i < this.options.filters.length; i++) {
if (this.options.filters[i].extensions[0] !== '*') {
ext = '.' + this.options.filters[i].extensions[0];
this.trailing = this.trailing ? this.trailing + ext : ext;
break;
}
}
}
}
return new Promise<URI | undefined>(async (resolve) => {
this.filePickBox = this.quickInputService.createQuickPick<FileQuickPickItem>();
this.busy = true;
this.filePickBox.matchOnLabel = false;
this.filePickBox.autoFocusOnList = false;
this.filePickBox.ignoreFocusOut = true;
this.filePickBox.ok = true;
if (this.options && this.options.availableFileSystems && (this.options.availableFileSystems.length > 1)) {
this.filePickBox.customButton = true;
this.filePickBox.customLabel = nls.localize('remoteFileDialog.local', 'Show Local');
let action;
if (isSave) {
action = SaveLocalFileAction;
} else {
action = this.allowFileSelection ? (this.allowFolderSelection ? OpenLocalFileFolderAction : OpenLocalFileAction) : OpenLocalFolderAction;
}
const keybinding = this.keybindingService.lookupKeybinding(action.ID);
if (keybinding) {
const label = keybinding.getLabel();
if (label) {
this.filePickBox.customHover = format('{0} ({1})', action.LABEL, label);
}
}
}
let isResolving: number = 0;
let isAcceptHandled = false;
this.currentFolder = homedir;
this.userEnteredPathSegment = '';
this.autoCompletePathSegment = '';
this.filePickBox.title = this.options.title;
this.filePickBox.value = this.pathFromUri(this.currentFolder, true);
this.filePickBox.valueSelection = [this.filePickBox.value.length, this.filePickBox.value.length];
this.filePickBox.items = [];
function doResolve(dialog: RemoteFileDialog, uri: URI | undefined) {
resolve(uri);
dialog.contextKey.set(false);
dialog.filePickBox.dispose();
dispose(dialog.disposables);
}
this.filePickBox.onDidCustom(() => {
if (isAcceptHandled || this.busy) {
return;
}
isAcceptHandled = true;
isResolving++;
if (this.options.availableFileSystems && (this.options.availableFileSystems.length > 1)) {
this.options.availableFileSystems.shift();
}
this.options.defaultUri = undefined;
this.filePickBox.hide();
if (isSave) {
// Remove defaultUri and filters to get a consistant experience with the keybinding.
this.options.defaultUri = undefined;
this.options.filters = undefined;
return this.fileDialogService.showSaveDialog(this.options).then(result => {
doResolve(this, result);
});
} else {
return this.fileDialogService.showOpenDialog(this.options).then(result => {
doResolve(this, result ? result[0] : undefined);
});
}
});
function handleAccept(dialog: RemoteFileDialog) {
if (dialog.busy) {
// Save the accept until the file picker is not busy.
dialog.onBusyChangeEmitter.event((busy: boolean) => {
if (!busy) {
handleAccept(dialog);
}
});
return;
} else if (isAcceptHandled) {
return;
}
isAcceptHandled = true;
isResolving++;
dialog.onDidAccept().then(resolveValue => {
if (resolveValue) {
dialog.filePickBox.hide();
doResolve(dialog, resolveValue);
} else if (dialog.hidden) {
doResolve(dialog, undefined);
} else {
isResolving--;
isAcceptHandled = false;
}
});
}
this.filePickBox.onDidAccept(_ => {
handleAccept(this);
});
this.filePickBox.onDidChangeActive(i => {
isAcceptHandled = false;
// update input box to match the first selected item
if ((i.length === 1) && this.isChangeFromUser()) {
this.filePickBox.validationMessage = undefined;
this.setAutoComplete(this.constructFullUserPath(), this.userEnteredPathSegment, i[0], true);
}
});
this.filePickBox.onDidChangeValue(async value => {
try {
// onDidChangeValue can also be triggered by the auto complete, so if it looks like the auto complete, don't do anything
if (this.isChangeFromUser()) {
// If the user has just entered more bad path, don't change anything
if (!equalsIgnoreCase(value, this.constructFullUserPath()) && !this.isBadSubpath(value)) {
this.filePickBox.validationMessage = undefined;
const filePickBoxUri = this.filePickBoxValue();
let updated: UpdateResult = UpdateResult.NotUpdated;
if (!resources.isEqual(this.currentFolder, filePickBoxUri, true)) {
updated = await this.tryUpdateItems(value, filePickBoxUri);
}
if (updated === UpdateResult.NotUpdated) {
this.setActiveItems(value);
}
} else {
this.filePickBox.activeItems = [];
}
}
} catch {
// Since any text can be entered in the input box, there is potential for error causing input. If this happens, do nothing.
}
});
this.filePickBox.onDidHide(() => {
this.hidden = true;
if (isResolving === 0) {
doResolve(this, undefined);
}
});
this.filePickBox.show();
this.contextKey.set(true);
await this.updateItems(homedir, true, this.trailing);
if (this.trailing) {
this.filePickBox.valueSelection = [this.filePickBox.value.length - this.trailing.length, this.filePickBox.value.length - ext.length];
} else {
this.filePickBox.valueSelection = [this.filePickBox.value.length, this.filePickBox.value.length];
}
this.busy = false;
});
}
private isBadSubpath(value: string) {
return this.badPath && (value.length > this.badPath.length) && equalsIgnoreCase(value.substring(0, this.badPath.length), this.badPath);
}
private isChangeFromUser(): boolean {
if (equalsIgnoreCase(this.filePickBox.value, this.pathAppend(this.currentFolder, this.userEnteredPathSegment + this.autoCompletePathSegment))
&& (this.activeItem === (this.filePickBox.activeItems ? this.filePickBox.activeItems[0] : undefined))) {
return false;
}
return true;
}
private constructFullUserPath(): string {
return this.pathAppend(this.currentFolder, this.userEnteredPathSegment);
}
private filePickBoxValue(): URI {
// The file pick box can't render everything, so we use the current folder to create the uri so that it is an existing path.
const directUri = this.remoteUriFrom(this.filePickBox.value);
const currentPath = this.pathFromUri(this.currentFolder);
if (equalsIgnoreCase(this.filePickBox.value, currentPath)) {
return this.currentFolder;
}
const currentDisplayUri = this.remoteUriFrom(currentPath);
const relativePath = resources.relativePath(currentDisplayUri, directUri);
const isSameRoot = (this.filePickBox.value.length > 1 && currentPath.length > 1) ? equalsIgnoreCase(this.filePickBox.value.substr(0, 2), currentPath.substr(0, 2)) : false;
if (relativePath && isSameRoot) {
const path = resources.joinPath(this.currentFolder, relativePath);
return resources.hasTrailingPathSeparator(directUri) ? resources.addTrailingPathSeparator(path) : path;
} else {
return directUri;
}
}
private async onDidAccept(): Promise<URI | undefined> {
this.busy = true;
if (this.filePickBox.activeItems.length === 1) {
const item = this.filePickBox.selectedItems[0];
if (item.isFolder) {
if (this.trailing) {
await this.updateItems(item.uri, true, this.trailing);
} else {
// When possible, cause the update to happen by modifying the input box.
// This allows all input box updates to happen first, and uses the same code path as the user typing.
const newPath = this.pathFromUri(item.uri);
if (startsWithIgnoreCase(newPath, this.filePickBox.value) && (equalsIgnoreCase(item.label, resources.basename(item.uri)))) {
this.filePickBox.valueSelection = [this.pathFromUri(this.currentFolder).length, this.filePickBox.value.length];
this.insertText(newPath, item.label);
} else if ((item.label === '..') && startsWithIgnoreCase(this.filePickBox.value, newPath)) {
this.filePickBox.valueSelection = [newPath.length, this.filePickBox.value.length];
this.insertText(newPath, '');
} else {
await this.updateItems(item.uri, true);
}
}
this.filePickBox.busy = false;
return;
}
} else {
// If the items have updated, don't try to resolve
if ((await this.tryUpdateItems(this.filePickBox.value, this.filePickBoxValue())) !== UpdateResult.NotUpdated) {
this.filePickBox.busy = false;
return;
}
}
let resolveValue: URI | undefined;
// Find resolve value
if (this.filePickBox.activeItems.length === 0) {
resolveValue = this.filePickBoxValue();
} else if (this.filePickBox.activeItems.length === 1) {
resolveValue = this.filePickBox.selectedItems[0].uri;
}
if (resolveValue) {
resolveValue = this.addPostfix(resolveValue);
}
if (await this.validate(resolveValue)) {
this.busy = false;
return resolveValue;
}
this.busy = false;
return undefined;
}
private async tryUpdateItems(value: string, valueUri: URI): Promise<UpdateResult> {
if ((value.length > 0) && ((value[value.length - 1] === '~') || (value[0] === '~'))) {
let newDir = this.userHome;
if ((value[0] === '~') && (value.length > 1)) {
newDir = resources.joinPath(newDir, value.substring(1));
}
await this.updateItems(newDir, true);
return UpdateResult.Updated;
} else if (!resources.isEqual(this.currentFolder, valueUri, true) && (this.endsWithSlash(value) || (!resources.isEqual(this.currentFolder, resources.dirname(valueUri), true) && resources.isEqualOrParent(this.currentFolder, resources.dirname(valueUri), true)))) {
let stat: IFileStat | undefined;
try {
stat = await this.fileService.resolve(valueUri);
} catch (e) {
// do nothing
}
if (stat && stat.isDirectory && (resources.basename(valueUri) !== '.') && this.endsWithSlash(value)) {
await this.updateItems(valueUri);
return UpdateResult.Updated;
} else if (this.endsWithSlash(value)) {
// The input box contains a path that doesn't exist on the system.
this.filePickBox.validationMessage = nls.localize('remoteFileDialog.badPath', 'The path does not exist.');
// Save this bad path. It can take too long to to a stat on every user entered character, but once a user enters a bad path they are likely
// to keep typing more bad path. We can compare against this bad path and see if the user entered path starts with it.
this.badPath = value;
return UpdateResult.InvalidPath;
} else {
const inputUriDirname = resources.dirname(valueUri);
if (!resources.isEqual(resources.removeTrailingPathSeparator(this.currentFolder), inputUriDirname, true)) {
let statWithoutTrailing: IFileStat | undefined;
try {
statWithoutTrailing = await this.fileService.resolve(inputUriDirname);
} catch (e) {
// do nothing
}
if (statWithoutTrailing && statWithoutTrailing.isDirectory && (resources.basename(valueUri) !== '.')) {
await this.updateItems(inputUriDirname, false, resources.basename(valueUri));
this.badPath = undefined;
return UpdateResult.Updated;
}
}
}
}
this.badPath = undefined;
return UpdateResult.NotUpdated;
}
private setActiveItems(value: string) {
const inputBasename = resources.basename(this.remoteUriFrom(value));
// Make sure that the folder whose children we are currently viewing matches the path in the input
const userPath = this.constructFullUserPath();
if (equalsIgnoreCase(userPath, value.substring(0, userPath.length))) {
let hasMatch = false;
for (let i = 0; i < this.filePickBox.items.length; i++) {
const item = <FileQuickPickItem>this.filePickBox.items[i];
if (this.setAutoComplete(value, inputBasename, item)) {
hasMatch = true;
break;
}
}
if (!hasMatch) {
this.userEnteredPathSegment = inputBasename;
this.autoCompletePathSegment = '';
this.filePickBox.activeItems = [];
}
} else {
if (!equalsIgnoreCase(inputBasename, resources.basename(this.currentFolder))) {
this.userEnteredPathSegment = inputBasename;
} else {
this.userEnteredPathSegment = '';
}
this.autoCompletePathSegment = '';
}
}
private setAutoComplete(startingValue: string, startingBasename: string, quickPickItem: FileQuickPickItem, force: boolean = false): boolean {
if (this.busy) {
// We're in the middle of something else. Doing an auto complete now can result jumbled or incorrect autocompletes.
this.userEnteredPathSegment = startingBasename;
this.autoCompletePathSegment = '';
return false;
}
const itemBasename = this.trimTrailingSlash(quickPickItem.label);
// Either force the autocomplete, or the old value should be one smaller than the new value and match the new value.
if (itemBasename === '..') {
// Don't match on the up directory item ever.
this.userEnteredPathSegment = startingValue;
this.autoCompletePathSegment = '';
this.activeItem = quickPickItem;
if (force) {
// clear any selected text
this.insertText(this.userEnteredPathSegment, '');
}
return false;
} else if (!force && (itemBasename.length >= startingBasename.length) && equalsIgnoreCase(itemBasename.substr(0, startingBasename.length), startingBasename)) {
this.userEnteredPathSegment = startingBasename;
this.activeItem = quickPickItem;
// Changing the active items will trigger the onDidActiveItemsChanged. Clear the autocomplete first, then set it after.
this.autoCompletePathSegment = '';
this.filePickBox.activeItems = [quickPickItem];
return true;
} else if (force && (!equalsIgnoreCase(quickPickItem.label, (this.userEnteredPathSegment + this.autoCompletePathSegment)))) {
this.userEnteredPathSegment = '';
this.autoCompletePathSegment = this.trimTrailingSlash(itemBasename);
this.activeItem = quickPickItem;
this.filePickBox.valueSelection = [this.pathFromUri(this.currentFolder, true).length, this.filePickBox.value.length];
// use insert text to preserve undo buffer
this.insertText(this.pathAppend(this.currentFolder, this.autoCompletePathSegment), this.autoCompletePathSegment);
this.filePickBox.valueSelection = [this.filePickBox.value.length - this.autoCompletePathSegment.length, this.filePickBox.value.length];
return true;
} else {
this.userEnteredPathSegment = startingBasename;
this.autoCompletePathSegment = '';
return false;
}
}
private insertText(wholeValue: string, insertText: string) {
if (this.filePickBox.inputHasFocus()) {
document.execCommand('insertText', false, insertText);
} else {
this.filePickBox.value = wholeValue;
}
}
private addPostfix(uri: URI): URI {
let result = uri;
if (this.requiresTrailing && this.options.filters && this.options.filters.length > 0) {
// Make sure that the suffix is added. If the user deleted it, we automatically add it here
let hasExt: boolean = false;
const currentExt = resources.extname(uri).substr(1);
for (let i = 0; i < this.options.filters.length; i++) {
for (let j = 0; j < this.options.filters[i].extensions.length; j++) {
if ((this.options.filters[i].extensions[j] === '*') || (this.options.filters[i].extensions[j] === currentExt)) {
hasExt = true;
break;
}
}
if (hasExt) {
break;
}
}
if (!hasExt) {
result = resources.joinPath(resources.dirname(uri), resources.basename(uri) + '.' + this.options.filters[0].extensions[0]);
}
}
return result;
}
private trimTrailingSlash(path: string): string {
return ((path.length > 1) && this.endsWithSlash(path)) ? path.substr(0, path.length - 1) : path;
}
private yesNoPrompt(uri: URI, message: string): Promise<boolean> {
interface YesNoItem extends IQuickPickItem {
value: boolean;
}
const prompt = this.quickInputService.createQuickPick<YesNoItem>();
prompt.title = message;
prompt.ignoreFocusOut = true;
prompt.ok = true;
prompt.customButton = true;
prompt.customLabel = nls.localize('remoteFileDialog.cancel', 'Cancel');
prompt.value = this.pathFromUri(uri);
let isResolving = false;
return new Promise<boolean>(resolve => {
prompt.onDidAccept(() => {
isResolving = true;
prompt.hide();
resolve(true);
});
prompt.onDidHide(() => {
if (!isResolving) {
resolve(false);
}
this.filePickBox.show();
this.hidden = false;
this.filePickBox.items = this.filePickBox.items;
prompt.dispose();
});
prompt.onDidChangeValue(() => {
prompt.hide();
});
prompt.onDidCustom(() => {
prompt.hide();
});
prompt.show();
});
}
private async validate(uri: URI | undefined): Promise<boolean> {
if (uri === undefined) {
this.filePickBox.validationMessage = nls.localize('remoteFileDialog.invalidPath', 'Please enter a valid path.');
return Promise.resolve(false);
}
let stat: IFileStat | undefined;
let statDirname: IFileStat | undefined;
try {
statDirname = await this.fileService.resolve(resources.dirname(uri));
stat = await this.fileService.resolve(uri);
} catch (e) {
// do nothing
}
if (this.requiresTrailing) { // save
if (stat && stat.isDirectory) {
// Can't do this
this.filePickBox.validationMessage = nls.localize('remoteFileDialog.validateFolder', 'The folder already exists. Please use a new file name.');
return Promise.resolve(false);
} else if (stat) {
// Replacing a file.
// Show a yes/no prompt
const message = nls.localize('remoteFileDialog.validateExisting', '{0} already exists. Are you sure you want to overwrite it?', resources.basename(uri));
return this.yesNoPrompt(uri, message);
} else if (!(isValidBasename(resources.basename(uri), await this.isWindowsOS()))) {
// Filename not allowed
this.filePickBox.validationMessage = nls.localize('remoteFileDialog.validateBadFilename', 'Please enter a valid file name.');
return Promise.resolve(false);
} else if (!statDirname || !statDirname.isDirectory) {
// Folder to save in doesn't exist
this.filePickBox.validationMessage = nls.localize('remoteFileDialog.validateNonexistentDir', 'Please enter a path that exists.');
return Promise.resolve(false);
}
} else { // open
if (!stat) {
// File or folder doesn't exist
this.filePickBox.validationMessage = nls.localize('remoteFileDialog.validateNonexistentDir', 'Please enter a path that exists.');
return Promise.resolve(false);
} else if (stat.isDirectory && !this.allowFolderSelection) {
// Folder selected when folder selection not permitted
this.filePickBox.validationMessage = nls.localize('remoteFileDialog.validateFileOnly', 'Please select a file.');
return Promise.resolve(false);
} else if (!stat.isDirectory && !this.allowFileSelection) {
// File selected when file selection not permitted
this.filePickBox.validationMessage = nls.localize('remoteFileDialog.validateFolderOnly', 'Please select a folder.');
return Promise.resolve(false);
}
}
return Promise.resolve(true);
}
private async updateItems(newFolder: URI, force: boolean = false, trailing?: string) {
this.busy = true;
this.userEnteredPathSegment = trailing ? trailing : '';
this.autoCompletePathSegment = '';
const newValue = trailing ? this.pathFromUri(resources.joinPath(newFolder, trailing)) : this.pathFromUri(newFolder, true);
this.currentFolder = resources.addTrailingPathSeparator(newFolder, this.separator);
return this.createItems(this.currentFolder).then(items => {
this.filePickBox.items = items;
if (this.allowFolderSelection) {
this.filePickBox.activeItems = [];
}
// the user might have continued typing while we were updating. Only update the input box if it doesn't match the directory.
if (!equalsIgnoreCase(this.filePickBox.value, newValue) && force) {
this.filePickBox.valueSelection = [0, this.filePickBox.value.length];
this.insertText(newValue, newValue);
}
if (force && trailing) {
// Keep the cursor position in front of the save as name.
this.filePickBox.valueSelection = [this.filePickBox.value.length - trailing.length, this.filePickBox.value.length - trailing.length];
} else if (!trailing) {
// If there is trailing, we don't move the cursor. If there is no trailing, cursor goes at the end.
this.filePickBox.valueSelection = [this.filePickBox.value.length, this.filePickBox.value.length];
}
this.busy = false;
});
}
private pathFromUri(uri: URI, endWithSeparator: boolean = false): string {
let result: string = uri.fsPath.replace(/\n/g, '');
if (this.separator === '/') {
result = result.replace(/\\/g, this.separator);
} else {
result = result.replace(/\//g, this.separator);
}
if (endWithSeparator && !this.endsWithSlash(result)) {
result = result + this.separator;
}
return result;
}
private pathAppend(uri: URI, additional: string): string {
if ((additional === '..') || (additional === '.')) {
const basePath = this.pathFromUri(uri);
return basePath + (this.endsWithSlash(basePath) ? '' : this.separator) + additional;
} else {
return this.pathFromUri(resources.joinPath(uri, additional));
}
}
private async isWindowsOS(): Promise<boolean> {
let isWindowsOS = isWindows;
const env = await this.getRemoteAgentEnvironment();
if (env) {
isWindowsOS = env.os === OperatingSystem.Windows;
}
return isWindowsOS;
}
private endsWithSlash(s: string) {
return /[\/\\]$/.test(s);
}
private basenameWithTrailingSlash(fullPath: URI): string {
const child = this.pathFromUri(fullPath, true);
const parent = this.pathFromUri(resources.dirname(fullPath), true);
return child.substring(parent.length);
}
private createBackItem(currFolder: URI): FileQuickPickItem | null {
const parentFolder = resources.dirname(currFolder)!;
if (!resources.isEqual(currFolder, parentFolder, true)) {
return { label: '..', uri: resources.addTrailingPathSeparator(parentFolder, this.separator), isFolder: true };
}
return null;
}
private async createItems(currentFolder: URI): Promise<FileQuickPickItem[]> {
const result: FileQuickPickItem[] = [];
const backDir = this.createBackItem(currentFolder);
try {
const folder = await this.fileService.resolve(currentFolder);
const fileNames = folder.children ? folder.children.map(child => child.name) : [];
const items = await Promise.all(fileNames.map(fileName => this.createItem(fileName, currentFolder)));
for (let item of items) {
if (item) {
result.push(item);
}
}
} catch (e) {
// ignore
console.log(e);
}
const sorted = result.sort((i1, i2) => {
if (i1.isFolder !== i2.isFolder) {
return i1.isFolder ? -1 : 1;
}
const trimmed1 = this.endsWithSlash(i1.label) ? i1.label.substr(0, i1.label.length - 1) : i1.label;
const trimmed2 = this.endsWithSlash(i2.label) ? i2.label.substr(0, i2.label.length - 1) : i2.label;
return trimmed1.localeCompare(trimmed2);
});
if (backDir) {
sorted.unshift(backDir);
}
return sorted;
}
private filterFile(file: URI): boolean {
if (this.options.filters) {
const ext = resources.extname(file);
for (let i = 0; i < this.options.filters.length; i++) {
for (let j = 0; j < this.options.filters[i].extensions.length; j++) {
if (ext === ('.' + this.options.filters[i].extensions[j])) {
return true;
}
}
}
return false;
}
return true;
}
private async createItem(filename: string, parent: URI): Promise<FileQuickPickItem | undefined> {
let fullPath = resources.joinPath(parent, filename);
try {
const stat = await this.fileService.resolve(fullPath);
if (stat.isDirectory) {
filename = this.basenameWithTrailingSlash(fullPath);
fullPath = resources.addTrailingPathSeparator(fullPath, this.separator);
return { label: filename, uri: fullPath, isFolder: true, iconClasses: getIconClasses(this.modelService, this.modeService, fullPath || undefined, FileKind.FOLDER) };
} else if (!stat.isDirectory && this.allowFileSelection && this.filterFile(fullPath)) {
return { label: filename, uri: fullPath, isFolder: false, iconClasses: getIconClasses(this.modelService, this.modeService, fullPath || undefined) };
}
return undefined;
} catch (e) {
return undefined;
}
}
} | src/vs/workbench/services/dialogs/browser/remoteFileDialog.ts | 1 | https://github.com/microsoft/vscode/commit/985de26b3446636f86e2bb2b14dbeb9ec1e33207 | [
0.9989948868751526,
0.05420941114425659,
0.00016524938109796494,
0.00044987277942709625,
0.2133430689573288
] |
{
"id": 3,
"code_window": [
"\t\treturn this.filePickBox.busy;\n",
"\t}\n",
"\n",
"\tpublic async showOpenDialog(options: IOpenDialogOptions = {}): Promise<URI | undefined> {\n",
"\t\tthis.scheme = this.getScheme(options.defaultUri, options.availableFileSystems);\n",
"\t\tthis.userHome = await this.getUserHome();\n",
"\t\tconst newOptions = await this.getOptions(options);\n",
"\t\tif (!newOptions) {\n",
"\t\t\treturn Promise.resolve(undefined);\n",
"\t\t}\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\tthis.scheme = this.getScheme(options.availableFileSystems);\n"
],
"file_path": "src/vs/workbench/services/dialogs/browser/remoteFileDialog.ts",
"type": "replace",
"edit_start_line_idx": 100
} | /*---------------------------------------------------------------------------------------------
* 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 { replaceWhitespace, renderExpressionValue, renderVariable } from 'vs/workbench/contrib/debug/browser/baseDebugView';
import * as dom from 'vs/base/browser/dom';
import { Expression, Variable, Scope, StackFrame, Thread } from 'vs/workbench/contrib/debug/common/debugModel';
import { MockSession } from 'vs/workbench/contrib/debug/test/common/mockDebug';
import { HighlightedLabel } from 'vs/base/browser/ui/highlightedlabel/highlightedLabel';
const $ = dom.$;
suite('Debug - Base Debug View', () => {
test('replace whitespace', () => {
assert.equal(replaceWhitespace('hey there'), 'hey there');
assert.equal(replaceWhitespace('hey there\n'), 'hey there\\n');
assert.equal(replaceWhitespace('hey \r there\n\t'), 'hey \\r there\\n\\t');
assert.equal(replaceWhitespace('hey \r\t\n\t\t\n there'), 'hey \\r\\t\\n\\t\\t\\n there');
});
test('render expression value', () => {
let container = $('.container');
renderExpressionValue('render \n me', container, { showHover: true, preserveWhitespace: true });
assert.equal(container.className, 'value');
assert.equal(container.title, 'render \n me');
assert.equal(container.textContent, 'render \n me');
const expression = new Expression('console');
expression.value = 'Object';
container = $('.container');
renderExpressionValue(expression, container, { colorize: true });
assert.equal(container.className, 'value unavailable error');
expression.available = true;
expression.value = '"string value"';
container = $('.container');
renderExpressionValue(expression, container, { colorize: true });
assert.equal(container.className, 'value string');
assert.equal(container.textContent, '"string value"');
expression.type = 'boolean';
container = $('.container');
renderExpressionValue(expression, container, { colorize: true });
assert.equal(container.className, 'value boolean');
assert.equal(container.textContent, expression.value);
expression.value = 'this is a long string';
container = $('.container');
renderExpressionValue(expression, container, { colorize: true, maxValueLength: 4 });
assert.equal(container.textContent, 'this...');
});
test('render variable', () => {
const session = new MockSession();
const thread = new Thread(session, 'mockthread', 1);
const stackFrame = new StackFrame(thread, 1, null!, 'app.js', 'normal', { startLineNumber: 1, startColumn: 1, endLineNumber: undefined!, endColumn: undefined! }, 0);
const scope = new Scope(stackFrame, 1, 'local', 1, false, 10, 10);
let variable = new Variable(session, scope, 2, 'foo', 'bar.foo', undefined!, 0, 0, {}, 'string');
let expression = $('.');
let name = $('.');
let value = $('.');
let label = new HighlightedLabel(name, false);
renderVariable(variable, { expression, name, value, label }, false, []);
assert.equal(label.element.textContent, 'foo');
assert.equal(value.textContent, '');
assert.equal(value.title, '');
variable.value = 'hey';
expression = $('.');
name = $('.');
value = $('.');
renderVariable(variable, { expression, name, value, label }, false, []);
assert.equal(value.textContent, 'hey');
assert.equal(label.element.textContent, 'foo:');
assert.equal(label.element.title, 'string');
variable = new Variable(session, scope, 2, 'console', 'console', '5', 0, 0, { kind: 'virtual' });
expression = $('.');
name = $('.');
value = $('.');
renderVariable(variable, { expression, name, value, label }, false, []);
assert.equal(name.className, 'virtual');
assert.equal(label.element.textContent, 'console:');
assert.equal(label.element.title, 'console');
assert.equal(value.className, 'value number');
});
});
| src/vs/workbench/contrib/debug/test/browser/baseDebugView.test.ts | 0 | https://github.com/microsoft/vscode/commit/985de26b3446636f86e2bb2b14dbeb9ec1e33207 | [
0.00017839150677900761,
0.0001758981088642031,
0.00017363847291562706,
0.00017609055794309825,
0.000001448292437089549
] |
{
"id": 3,
"code_window": [
"\t\treturn this.filePickBox.busy;\n",
"\t}\n",
"\n",
"\tpublic async showOpenDialog(options: IOpenDialogOptions = {}): Promise<URI | undefined> {\n",
"\t\tthis.scheme = this.getScheme(options.defaultUri, options.availableFileSystems);\n",
"\t\tthis.userHome = await this.getUserHome();\n",
"\t\tconst newOptions = await this.getOptions(options);\n",
"\t\tif (!newOptions) {\n",
"\t\t\treturn Promise.resolve(undefined);\n",
"\t\t}\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\tthis.scheme = this.getScheme(options.availableFileSystems);\n"
],
"file_path": "src/vs/workbench/services/dialogs/browser/remoteFileDialog.ts",
"type": "replace",
"edit_start_line_idx": 100
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
/*
Keeping name short for faster parsing.
cdr = core decorations rendering (div)
*/
.monaco-editor .lines-content .cdr {
position: absolute;
} | src/vs/editor/browser/viewParts/decorations/decorations.css | 0 | https://github.com/microsoft/vscode/commit/985de26b3446636f86e2bb2b14dbeb9ec1e33207 | [
0.00017594611563254148,
0.00017594595556147397,
0.00017594578093849123,
0.00017594595556147397,
1.6750512088492542e-10
] |
{
"id": 3,
"code_window": [
"\t\treturn this.filePickBox.busy;\n",
"\t}\n",
"\n",
"\tpublic async showOpenDialog(options: IOpenDialogOptions = {}): Promise<URI | undefined> {\n",
"\t\tthis.scheme = this.getScheme(options.defaultUri, options.availableFileSystems);\n",
"\t\tthis.userHome = await this.getUserHome();\n",
"\t\tconst newOptions = await this.getOptions(options);\n",
"\t\tif (!newOptions) {\n",
"\t\t\treturn Promise.resolve(undefined);\n",
"\t\t}\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\tthis.scheme = this.getScheme(options.availableFileSystems);\n"
],
"file_path": "src/vs/workbench/services/dialogs/browser/remoteFileDialog.ts",
"type": "replace",
"edit_start_line_idx": 100
} | /*---------------------------------------------------------------------------------------------
* 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 { regExpFlags } from 'vs/base/common/strings';
export function stringify(obj: any): string {
return JSON.stringify(obj, replacer);
}
export function parse(text: string): any {
let data = JSON.parse(text);
data = revive(data, 0);
return data;
}
export interface MarshalledObject {
$mid: number;
}
function replacer(key: string, value: any): any {
// URI is done via toJSON-member
if (value instanceof RegExp) {
return {
$mid: 2,
source: value.source,
flags: regExpFlags(value),
};
}
return value;
}
export function revive(obj: any, depth: number): any {
if (!obj || depth > 200) {
return obj;
}
if (typeof obj === 'object') {
switch ((<MarshalledObject>obj).$mid) {
case 1: return URI.revive(obj);
case 2: return new RegExp(obj.source, obj.flags);
}
// walk object (or array)
for (let key in obj) {
if (Object.hasOwnProperty.call(obj, key)) {
obj[key] = revive(obj[key], depth + 1);
}
}
}
return obj;
}
| src/vs/base/common/marshalling.ts | 0 | https://github.com/microsoft/vscode/commit/985de26b3446636f86e2bb2b14dbeb9ec1e33207 | [
0.0001740238512866199,
0.0001709748903522268,
0.00016748688358347863,
0.00017134816152974963,
0.0000022612039174418896
] |
{
"id": 4,
"code_window": [
"\t\treturn this.pickResource();\n",
"\t}\n",
"\n",
"\tpublic async showSaveDialog(options: ISaveDialogOptions): Promise<URI | undefined> {\n",
"\t\tthis.scheme = this.getScheme(options.defaultUri, options.availableFileSystems);\n",
"\t\tthis.userHome = await this.getUserHome();\n",
"\t\tthis.requiresTrailing = true;\n",
"\t\tconst newOptions = await this.getOptions(options, true);\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\tthis.scheme = this.getScheme(options.availableFileSystems);\n"
],
"file_path": "src/vs/workbench/services/dialogs/browser/remoteFileDialog.ts",
"type": "replace",
"edit_start_line_idx": 111
} | /*---------------------------------------------------------------------------------------------
* 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 resources from 'vs/base/common/resources';
import * as objects from 'vs/base/common/objects';
import { IFileService, IFileStat, FileKind } from 'vs/platform/files/common/files';
import { IQuickInputService, IQuickPickItem, IQuickPick } from 'vs/platform/quickinput/common/quickInput';
import { URI } from 'vs/base/common/uri';
import { isWindows, OperatingSystem } from 'vs/base/common/platform';
import { ISaveDialogOptions, IOpenDialogOptions, IFileDialogService } from 'vs/platform/dialogs/common/dialogs';
import { REMOTE_HOST_SCHEME } from 'vs/platform/remote/common/remoteHosts';
import { ILabelService } from 'vs/platform/label/common/label';
import { IWorkspaceContextService } from 'vs/platform/workspace/common/workspace';
import { INotificationService } from 'vs/platform/notification/common/notification';
import { IModelService } from 'vs/editor/common/services/modelService';
import { IModeService } from 'vs/editor/common/services/modeService';
import { getIconClasses } from 'vs/editor/common/services/getIconClasses';
import { Schemas } from 'vs/base/common/network';
import { IWorkbenchEnvironmentService } from 'vs/workbench/services/environment/common/environmentService';
import { IRemoteAgentService } from 'vs/workbench/services/remote/common/remoteAgentService';
import { IContextKeyService, IContextKey } from 'vs/platform/contextkey/common/contextkey';
import { equalsIgnoreCase, format, startsWithIgnoreCase } from 'vs/base/common/strings';
import { OpenLocalFileAction, OpenLocalFileFolderAction, OpenLocalFolderAction, SaveLocalFileAction } from 'vs/workbench/browser/actions/workspaceActions';
import { IKeybindingService } from 'vs/platform/keybinding/common/keybinding';
import { IRemoteAgentEnvironment } from 'vs/platform/remote/common/remoteAgentEnvironment';
import { isValidBasename } from 'vs/base/common/extpath';
import { RemoteFileDialogContext } from 'vs/workbench/browser/contextkeys';
import { Emitter } from 'vs/base/common/event';
import { IDisposable, dispose } from 'vs/base/common/lifecycle';
interface FileQuickPickItem extends IQuickPickItem {
uri: URI;
isFolder: boolean;
}
enum UpdateResult {
Updated,
Updating,
NotUpdated,
InvalidPath
}
export class RemoteFileDialog {
private options: IOpenDialogOptions;
private currentFolder: URI;
private filePickBox: IQuickPick<FileQuickPickItem>;
private hidden: boolean;
private allowFileSelection: boolean;
private allowFolderSelection: boolean;
private remoteAuthority: string | undefined;
private requiresTrailing: boolean;
private trailing: string | undefined;
private scheme: string = REMOTE_HOST_SCHEME;
private contextKey: IContextKey<boolean>;
private userEnteredPathSegment: string;
private autoCompletePathSegment: string;
private activeItem: FileQuickPickItem;
private userHome: URI;
private badPath: string | undefined;
private remoteAgentEnvironment: IRemoteAgentEnvironment | null;
private separator: string;
private onBusyChangeEmitter = new Emitter<boolean>();
protected disposables: IDisposable[] = [
this.onBusyChangeEmitter
];
constructor(
@IFileService private readonly fileService: IFileService,
@IQuickInputService private readonly quickInputService: IQuickInputService,
@ILabelService private readonly labelService: ILabelService,
@IWorkspaceContextService private readonly workspaceContextService: IWorkspaceContextService,
@INotificationService private readonly notificationService: INotificationService,
@IFileDialogService private readonly fileDialogService: IFileDialogService,
@IModelService private readonly modelService: IModelService,
@IModeService private readonly modeService: IModeService,
@IWorkbenchEnvironmentService private readonly environmentService: IWorkbenchEnvironmentService,
@IRemoteAgentService private readonly remoteAgentService: IRemoteAgentService,
@IKeybindingService private readonly keybindingService: IKeybindingService,
@IContextKeyService contextKeyService: IContextKeyService,
) {
this.remoteAuthority = this.environmentService.configuration.remoteAuthority;
this.contextKey = RemoteFileDialogContext.bindTo(contextKeyService);
}
set busy(busy: boolean) {
if (this.filePickBox.busy !== busy) {
this.filePickBox.busy = busy;
this.onBusyChangeEmitter.fire(busy);
}
}
get busy(): boolean {
return this.filePickBox.busy;
}
public async showOpenDialog(options: IOpenDialogOptions = {}): Promise<URI | undefined> {
this.scheme = this.getScheme(options.defaultUri, options.availableFileSystems);
this.userHome = await this.getUserHome();
const newOptions = await this.getOptions(options);
if (!newOptions) {
return Promise.resolve(undefined);
}
this.options = newOptions;
return this.pickResource();
}
public async showSaveDialog(options: ISaveDialogOptions): Promise<URI | undefined> {
this.scheme = this.getScheme(options.defaultUri, options.availableFileSystems);
this.userHome = await this.getUserHome();
this.requiresTrailing = true;
const newOptions = await this.getOptions(options, true);
if (!newOptions) {
return Promise.resolve(undefined);
}
this.options = newOptions;
this.options.canSelectFolders = true;
this.options.canSelectFiles = true;
return new Promise<URI | undefined>((resolve) => {
this.pickResource(true).then(folderUri => {
resolve(folderUri);
});
});
}
private getOptions(options: ISaveDialogOptions | IOpenDialogOptions, isSave: boolean = false): IOpenDialogOptions | undefined {
let defaultUri = options.defaultUri;
const filename = (defaultUri && isSave && (resources.dirname(defaultUri).path === '/')) ? resources.basename(defaultUri) : undefined;
if (!defaultUri || filename) {
defaultUri = this.userHome;
if (filename) {
defaultUri = resources.joinPath(defaultUri, filename);
}
}
if ((this.scheme !== Schemas.file) && !this.fileService.canHandleResource(defaultUri)) {
this.notificationService.info(nls.localize('remoteFileDialog.notConnectedToRemote', 'File system provider for {0} is not available.', defaultUri.toString()));
return undefined;
}
const newOptions: IOpenDialogOptions = objects.deepClone(options);
newOptions.defaultUri = defaultUri;
return newOptions;
}
private remoteUriFrom(path: string): URI {
path = path.replace(/\\/g, '/');
return resources.toLocalResource(URI.from({ scheme: this.scheme, path }), this.scheme === Schemas.file ? undefined : this.remoteAuthority);
}
private getScheme(defaultUri: URI | undefined, available: string[] | undefined): string {
return defaultUri ? defaultUri.scheme : (available ? available[0] : Schemas.file);
}
private async getRemoteAgentEnvironment(): Promise<IRemoteAgentEnvironment | null> {
if (this.remoteAgentEnvironment === undefined) {
this.remoteAgentEnvironment = await this.remoteAgentService.getEnvironment();
}
return this.remoteAgentEnvironment;
}
private async getUserHome(): Promise<URI> {
if (this.scheme !== Schemas.file) {
const env = await this.getRemoteAgentEnvironment();
if (env) {
return env.userHome;
}
}
return URI.from({ scheme: this.scheme, path: this.environmentService.userHome });
}
private async pickResource(isSave: boolean = false): Promise<URI | undefined> {
this.allowFolderSelection = !!this.options.canSelectFolders;
this.allowFileSelection = !!this.options.canSelectFiles;
this.separator = this.labelService.getSeparator(this.scheme, this.remoteAuthority);
this.hidden = false;
let homedir: URI = this.options.defaultUri ? this.options.defaultUri : this.workspaceContextService.getWorkspace().folders[0].uri;
let stat: IFileStat | undefined;
let ext: string = resources.extname(homedir);
if (this.options.defaultUri) {
try {
stat = await this.fileService.resolve(this.options.defaultUri);
} catch (e) {
// The file or folder doesn't exist
}
if (!stat || !stat.isDirectory) {
homedir = resources.dirname(this.options.defaultUri);
this.trailing = resources.basename(this.options.defaultUri);
}
// append extension
if (isSave && !ext && this.options.filters) {
for (let i = 0; i < this.options.filters.length; i++) {
if (this.options.filters[i].extensions[0] !== '*') {
ext = '.' + this.options.filters[i].extensions[0];
this.trailing = this.trailing ? this.trailing + ext : ext;
break;
}
}
}
}
return new Promise<URI | undefined>(async (resolve) => {
this.filePickBox = this.quickInputService.createQuickPick<FileQuickPickItem>();
this.busy = true;
this.filePickBox.matchOnLabel = false;
this.filePickBox.autoFocusOnList = false;
this.filePickBox.ignoreFocusOut = true;
this.filePickBox.ok = true;
if (this.options && this.options.availableFileSystems && (this.options.availableFileSystems.length > 1)) {
this.filePickBox.customButton = true;
this.filePickBox.customLabel = nls.localize('remoteFileDialog.local', 'Show Local');
let action;
if (isSave) {
action = SaveLocalFileAction;
} else {
action = this.allowFileSelection ? (this.allowFolderSelection ? OpenLocalFileFolderAction : OpenLocalFileAction) : OpenLocalFolderAction;
}
const keybinding = this.keybindingService.lookupKeybinding(action.ID);
if (keybinding) {
const label = keybinding.getLabel();
if (label) {
this.filePickBox.customHover = format('{0} ({1})', action.LABEL, label);
}
}
}
let isResolving: number = 0;
let isAcceptHandled = false;
this.currentFolder = homedir;
this.userEnteredPathSegment = '';
this.autoCompletePathSegment = '';
this.filePickBox.title = this.options.title;
this.filePickBox.value = this.pathFromUri(this.currentFolder, true);
this.filePickBox.valueSelection = [this.filePickBox.value.length, this.filePickBox.value.length];
this.filePickBox.items = [];
function doResolve(dialog: RemoteFileDialog, uri: URI | undefined) {
resolve(uri);
dialog.contextKey.set(false);
dialog.filePickBox.dispose();
dispose(dialog.disposables);
}
this.filePickBox.onDidCustom(() => {
if (isAcceptHandled || this.busy) {
return;
}
isAcceptHandled = true;
isResolving++;
if (this.options.availableFileSystems && (this.options.availableFileSystems.length > 1)) {
this.options.availableFileSystems.shift();
}
this.options.defaultUri = undefined;
this.filePickBox.hide();
if (isSave) {
// Remove defaultUri and filters to get a consistant experience with the keybinding.
this.options.defaultUri = undefined;
this.options.filters = undefined;
return this.fileDialogService.showSaveDialog(this.options).then(result => {
doResolve(this, result);
});
} else {
return this.fileDialogService.showOpenDialog(this.options).then(result => {
doResolve(this, result ? result[0] : undefined);
});
}
});
function handleAccept(dialog: RemoteFileDialog) {
if (dialog.busy) {
// Save the accept until the file picker is not busy.
dialog.onBusyChangeEmitter.event((busy: boolean) => {
if (!busy) {
handleAccept(dialog);
}
});
return;
} else if (isAcceptHandled) {
return;
}
isAcceptHandled = true;
isResolving++;
dialog.onDidAccept().then(resolveValue => {
if (resolveValue) {
dialog.filePickBox.hide();
doResolve(dialog, resolveValue);
} else if (dialog.hidden) {
doResolve(dialog, undefined);
} else {
isResolving--;
isAcceptHandled = false;
}
});
}
this.filePickBox.onDidAccept(_ => {
handleAccept(this);
});
this.filePickBox.onDidChangeActive(i => {
isAcceptHandled = false;
// update input box to match the first selected item
if ((i.length === 1) && this.isChangeFromUser()) {
this.filePickBox.validationMessage = undefined;
this.setAutoComplete(this.constructFullUserPath(), this.userEnteredPathSegment, i[0], true);
}
});
this.filePickBox.onDidChangeValue(async value => {
try {
// onDidChangeValue can also be triggered by the auto complete, so if it looks like the auto complete, don't do anything
if (this.isChangeFromUser()) {
// If the user has just entered more bad path, don't change anything
if (!equalsIgnoreCase(value, this.constructFullUserPath()) && !this.isBadSubpath(value)) {
this.filePickBox.validationMessage = undefined;
const filePickBoxUri = this.filePickBoxValue();
let updated: UpdateResult = UpdateResult.NotUpdated;
if (!resources.isEqual(this.currentFolder, filePickBoxUri, true)) {
updated = await this.tryUpdateItems(value, filePickBoxUri);
}
if (updated === UpdateResult.NotUpdated) {
this.setActiveItems(value);
}
} else {
this.filePickBox.activeItems = [];
}
}
} catch {
// Since any text can be entered in the input box, there is potential for error causing input. If this happens, do nothing.
}
});
this.filePickBox.onDidHide(() => {
this.hidden = true;
if (isResolving === 0) {
doResolve(this, undefined);
}
});
this.filePickBox.show();
this.contextKey.set(true);
await this.updateItems(homedir, true, this.trailing);
if (this.trailing) {
this.filePickBox.valueSelection = [this.filePickBox.value.length - this.trailing.length, this.filePickBox.value.length - ext.length];
} else {
this.filePickBox.valueSelection = [this.filePickBox.value.length, this.filePickBox.value.length];
}
this.busy = false;
});
}
private isBadSubpath(value: string) {
return this.badPath && (value.length > this.badPath.length) && equalsIgnoreCase(value.substring(0, this.badPath.length), this.badPath);
}
private isChangeFromUser(): boolean {
if (equalsIgnoreCase(this.filePickBox.value, this.pathAppend(this.currentFolder, this.userEnteredPathSegment + this.autoCompletePathSegment))
&& (this.activeItem === (this.filePickBox.activeItems ? this.filePickBox.activeItems[0] : undefined))) {
return false;
}
return true;
}
private constructFullUserPath(): string {
return this.pathAppend(this.currentFolder, this.userEnteredPathSegment);
}
private filePickBoxValue(): URI {
// The file pick box can't render everything, so we use the current folder to create the uri so that it is an existing path.
const directUri = this.remoteUriFrom(this.filePickBox.value);
const currentPath = this.pathFromUri(this.currentFolder);
if (equalsIgnoreCase(this.filePickBox.value, currentPath)) {
return this.currentFolder;
}
const currentDisplayUri = this.remoteUriFrom(currentPath);
const relativePath = resources.relativePath(currentDisplayUri, directUri);
const isSameRoot = (this.filePickBox.value.length > 1 && currentPath.length > 1) ? equalsIgnoreCase(this.filePickBox.value.substr(0, 2), currentPath.substr(0, 2)) : false;
if (relativePath && isSameRoot) {
const path = resources.joinPath(this.currentFolder, relativePath);
return resources.hasTrailingPathSeparator(directUri) ? resources.addTrailingPathSeparator(path) : path;
} else {
return directUri;
}
}
private async onDidAccept(): Promise<URI | undefined> {
this.busy = true;
if (this.filePickBox.activeItems.length === 1) {
const item = this.filePickBox.selectedItems[0];
if (item.isFolder) {
if (this.trailing) {
await this.updateItems(item.uri, true, this.trailing);
} else {
// When possible, cause the update to happen by modifying the input box.
// This allows all input box updates to happen first, and uses the same code path as the user typing.
const newPath = this.pathFromUri(item.uri);
if (startsWithIgnoreCase(newPath, this.filePickBox.value) && (equalsIgnoreCase(item.label, resources.basename(item.uri)))) {
this.filePickBox.valueSelection = [this.pathFromUri(this.currentFolder).length, this.filePickBox.value.length];
this.insertText(newPath, item.label);
} else if ((item.label === '..') && startsWithIgnoreCase(this.filePickBox.value, newPath)) {
this.filePickBox.valueSelection = [newPath.length, this.filePickBox.value.length];
this.insertText(newPath, '');
} else {
await this.updateItems(item.uri, true);
}
}
this.filePickBox.busy = false;
return;
}
} else {
// If the items have updated, don't try to resolve
if ((await this.tryUpdateItems(this.filePickBox.value, this.filePickBoxValue())) !== UpdateResult.NotUpdated) {
this.filePickBox.busy = false;
return;
}
}
let resolveValue: URI | undefined;
// Find resolve value
if (this.filePickBox.activeItems.length === 0) {
resolveValue = this.filePickBoxValue();
} else if (this.filePickBox.activeItems.length === 1) {
resolveValue = this.filePickBox.selectedItems[0].uri;
}
if (resolveValue) {
resolveValue = this.addPostfix(resolveValue);
}
if (await this.validate(resolveValue)) {
this.busy = false;
return resolveValue;
}
this.busy = false;
return undefined;
}
private async tryUpdateItems(value: string, valueUri: URI): Promise<UpdateResult> {
if ((value.length > 0) && ((value[value.length - 1] === '~') || (value[0] === '~'))) {
let newDir = this.userHome;
if ((value[0] === '~') && (value.length > 1)) {
newDir = resources.joinPath(newDir, value.substring(1));
}
await this.updateItems(newDir, true);
return UpdateResult.Updated;
} else if (!resources.isEqual(this.currentFolder, valueUri, true) && (this.endsWithSlash(value) || (!resources.isEqual(this.currentFolder, resources.dirname(valueUri), true) && resources.isEqualOrParent(this.currentFolder, resources.dirname(valueUri), true)))) {
let stat: IFileStat | undefined;
try {
stat = await this.fileService.resolve(valueUri);
} catch (e) {
// do nothing
}
if (stat && stat.isDirectory && (resources.basename(valueUri) !== '.') && this.endsWithSlash(value)) {
await this.updateItems(valueUri);
return UpdateResult.Updated;
} else if (this.endsWithSlash(value)) {
// The input box contains a path that doesn't exist on the system.
this.filePickBox.validationMessage = nls.localize('remoteFileDialog.badPath', 'The path does not exist.');
// Save this bad path. It can take too long to to a stat on every user entered character, but once a user enters a bad path they are likely
// to keep typing more bad path. We can compare against this bad path and see if the user entered path starts with it.
this.badPath = value;
return UpdateResult.InvalidPath;
} else {
const inputUriDirname = resources.dirname(valueUri);
if (!resources.isEqual(resources.removeTrailingPathSeparator(this.currentFolder), inputUriDirname, true)) {
let statWithoutTrailing: IFileStat | undefined;
try {
statWithoutTrailing = await this.fileService.resolve(inputUriDirname);
} catch (e) {
// do nothing
}
if (statWithoutTrailing && statWithoutTrailing.isDirectory && (resources.basename(valueUri) !== '.')) {
await this.updateItems(inputUriDirname, false, resources.basename(valueUri));
this.badPath = undefined;
return UpdateResult.Updated;
}
}
}
}
this.badPath = undefined;
return UpdateResult.NotUpdated;
}
private setActiveItems(value: string) {
const inputBasename = resources.basename(this.remoteUriFrom(value));
// Make sure that the folder whose children we are currently viewing matches the path in the input
const userPath = this.constructFullUserPath();
if (equalsIgnoreCase(userPath, value.substring(0, userPath.length))) {
let hasMatch = false;
for (let i = 0; i < this.filePickBox.items.length; i++) {
const item = <FileQuickPickItem>this.filePickBox.items[i];
if (this.setAutoComplete(value, inputBasename, item)) {
hasMatch = true;
break;
}
}
if (!hasMatch) {
this.userEnteredPathSegment = inputBasename;
this.autoCompletePathSegment = '';
this.filePickBox.activeItems = [];
}
} else {
if (!equalsIgnoreCase(inputBasename, resources.basename(this.currentFolder))) {
this.userEnteredPathSegment = inputBasename;
} else {
this.userEnteredPathSegment = '';
}
this.autoCompletePathSegment = '';
}
}
private setAutoComplete(startingValue: string, startingBasename: string, quickPickItem: FileQuickPickItem, force: boolean = false): boolean {
if (this.busy) {
// We're in the middle of something else. Doing an auto complete now can result jumbled or incorrect autocompletes.
this.userEnteredPathSegment = startingBasename;
this.autoCompletePathSegment = '';
return false;
}
const itemBasename = this.trimTrailingSlash(quickPickItem.label);
// Either force the autocomplete, or the old value should be one smaller than the new value and match the new value.
if (itemBasename === '..') {
// Don't match on the up directory item ever.
this.userEnteredPathSegment = startingValue;
this.autoCompletePathSegment = '';
this.activeItem = quickPickItem;
if (force) {
// clear any selected text
this.insertText(this.userEnteredPathSegment, '');
}
return false;
} else if (!force && (itemBasename.length >= startingBasename.length) && equalsIgnoreCase(itemBasename.substr(0, startingBasename.length), startingBasename)) {
this.userEnteredPathSegment = startingBasename;
this.activeItem = quickPickItem;
// Changing the active items will trigger the onDidActiveItemsChanged. Clear the autocomplete first, then set it after.
this.autoCompletePathSegment = '';
this.filePickBox.activeItems = [quickPickItem];
return true;
} else if (force && (!equalsIgnoreCase(quickPickItem.label, (this.userEnteredPathSegment + this.autoCompletePathSegment)))) {
this.userEnteredPathSegment = '';
this.autoCompletePathSegment = this.trimTrailingSlash(itemBasename);
this.activeItem = quickPickItem;
this.filePickBox.valueSelection = [this.pathFromUri(this.currentFolder, true).length, this.filePickBox.value.length];
// use insert text to preserve undo buffer
this.insertText(this.pathAppend(this.currentFolder, this.autoCompletePathSegment), this.autoCompletePathSegment);
this.filePickBox.valueSelection = [this.filePickBox.value.length - this.autoCompletePathSegment.length, this.filePickBox.value.length];
return true;
} else {
this.userEnteredPathSegment = startingBasename;
this.autoCompletePathSegment = '';
return false;
}
}
private insertText(wholeValue: string, insertText: string) {
if (this.filePickBox.inputHasFocus()) {
document.execCommand('insertText', false, insertText);
} else {
this.filePickBox.value = wholeValue;
}
}
private addPostfix(uri: URI): URI {
let result = uri;
if (this.requiresTrailing && this.options.filters && this.options.filters.length > 0) {
// Make sure that the suffix is added. If the user deleted it, we automatically add it here
let hasExt: boolean = false;
const currentExt = resources.extname(uri).substr(1);
for (let i = 0; i < this.options.filters.length; i++) {
for (let j = 0; j < this.options.filters[i].extensions.length; j++) {
if ((this.options.filters[i].extensions[j] === '*') || (this.options.filters[i].extensions[j] === currentExt)) {
hasExt = true;
break;
}
}
if (hasExt) {
break;
}
}
if (!hasExt) {
result = resources.joinPath(resources.dirname(uri), resources.basename(uri) + '.' + this.options.filters[0].extensions[0]);
}
}
return result;
}
private trimTrailingSlash(path: string): string {
return ((path.length > 1) && this.endsWithSlash(path)) ? path.substr(0, path.length - 1) : path;
}
private yesNoPrompt(uri: URI, message: string): Promise<boolean> {
interface YesNoItem extends IQuickPickItem {
value: boolean;
}
const prompt = this.quickInputService.createQuickPick<YesNoItem>();
prompt.title = message;
prompt.ignoreFocusOut = true;
prompt.ok = true;
prompt.customButton = true;
prompt.customLabel = nls.localize('remoteFileDialog.cancel', 'Cancel');
prompt.value = this.pathFromUri(uri);
let isResolving = false;
return new Promise<boolean>(resolve => {
prompt.onDidAccept(() => {
isResolving = true;
prompt.hide();
resolve(true);
});
prompt.onDidHide(() => {
if (!isResolving) {
resolve(false);
}
this.filePickBox.show();
this.hidden = false;
this.filePickBox.items = this.filePickBox.items;
prompt.dispose();
});
prompt.onDidChangeValue(() => {
prompt.hide();
});
prompt.onDidCustom(() => {
prompt.hide();
});
prompt.show();
});
}
private async validate(uri: URI | undefined): Promise<boolean> {
if (uri === undefined) {
this.filePickBox.validationMessage = nls.localize('remoteFileDialog.invalidPath', 'Please enter a valid path.');
return Promise.resolve(false);
}
let stat: IFileStat | undefined;
let statDirname: IFileStat | undefined;
try {
statDirname = await this.fileService.resolve(resources.dirname(uri));
stat = await this.fileService.resolve(uri);
} catch (e) {
// do nothing
}
if (this.requiresTrailing) { // save
if (stat && stat.isDirectory) {
// Can't do this
this.filePickBox.validationMessage = nls.localize('remoteFileDialog.validateFolder', 'The folder already exists. Please use a new file name.');
return Promise.resolve(false);
} else if (stat) {
// Replacing a file.
// Show a yes/no prompt
const message = nls.localize('remoteFileDialog.validateExisting', '{0} already exists. Are you sure you want to overwrite it?', resources.basename(uri));
return this.yesNoPrompt(uri, message);
} else if (!(isValidBasename(resources.basename(uri), await this.isWindowsOS()))) {
// Filename not allowed
this.filePickBox.validationMessage = nls.localize('remoteFileDialog.validateBadFilename', 'Please enter a valid file name.');
return Promise.resolve(false);
} else if (!statDirname || !statDirname.isDirectory) {
// Folder to save in doesn't exist
this.filePickBox.validationMessage = nls.localize('remoteFileDialog.validateNonexistentDir', 'Please enter a path that exists.');
return Promise.resolve(false);
}
} else { // open
if (!stat) {
// File or folder doesn't exist
this.filePickBox.validationMessage = nls.localize('remoteFileDialog.validateNonexistentDir', 'Please enter a path that exists.');
return Promise.resolve(false);
} else if (stat.isDirectory && !this.allowFolderSelection) {
// Folder selected when folder selection not permitted
this.filePickBox.validationMessage = nls.localize('remoteFileDialog.validateFileOnly', 'Please select a file.');
return Promise.resolve(false);
} else if (!stat.isDirectory && !this.allowFileSelection) {
// File selected when file selection not permitted
this.filePickBox.validationMessage = nls.localize('remoteFileDialog.validateFolderOnly', 'Please select a folder.');
return Promise.resolve(false);
}
}
return Promise.resolve(true);
}
private async updateItems(newFolder: URI, force: boolean = false, trailing?: string) {
this.busy = true;
this.userEnteredPathSegment = trailing ? trailing : '';
this.autoCompletePathSegment = '';
const newValue = trailing ? this.pathFromUri(resources.joinPath(newFolder, trailing)) : this.pathFromUri(newFolder, true);
this.currentFolder = resources.addTrailingPathSeparator(newFolder, this.separator);
return this.createItems(this.currentFolder).then(items => {
this.filePickBox.items = items;
if (this.allowFolderSelection) {
this.filePickBox.activeItems = [];
}
// the user might have continued typing while we were updating. Only update the input box if it doesn't match the directory.
if (!equalsIgnoreCase(this.filePickBox.value, newValue) && force) {
this.filePickBox.valueSelection = [0, this.filePickBox.value.length];
this.insertText(newValue, newValue);
}
if (force && trailing) {
// Keep the cursor position in front of the save as name.
this.filePickBox.valueSelection = [this.filePickBox.value.length - trailing.length, this.filePickBox.value.length - trailing.length];
} else if (!trailing) {
// If there is trailing, we don't move the cursor. If there is no trailing, cursor goes at the end.
this.filePickBox.valueSelection = [this.filePickBox.value.length, this.filePickBox.value.length];
}
this.busy = false;
});
}
private pathFromUri(uri: URI, endWithSeparator: boolean = false): string {
let result: string = uri.fsPath.replace(/\n/g, '');
if (this.separator === '/') {
result = result.replace(/\\/g, this.separator);
} else {
result = result.replace(/\//g, this.separator);
}
if (endWithSeparator && !this.endsWithSlash(result)) {
result = result + this.separator;
}
return result;
}
private pathAppend(uri: URI, additional: string): string {
if ((additional === '..') || (additional === '.')) {
const basePath = this.pathFromUri(uri);
return basePath + (this.endsWithSlash(basePath) ? '' : this.separator) + additional;
} else {
return this.pathFromUri(resources.joinPath(uri, additional));
}
}
private async isWindowsOS(): Promise<boolean> {
let isWindowsOS = isWindows;
const env = await this.getRemoteAgentEnvironment();
if (env) {
isWindowsOS = env.os === OperatingSystem.Windows;
}
return isWindowsOS;
}
private endsWithSlash(s: string) {
return /[\/\\]$/.test(s);
}
private basenameWithTrailingSlash(fullPath: URI): string {
const child = this.pathFromUri(fullPath, true);
const parent = this.pathFromUri(resources.dirname(fullPath), true);
return child.substring(parent.length);
}
private createBackItem(currFolder: URI): FileQuickPickItem | null {
const parentFolder = resources.dirname(currFolder)!;
if (!resources.isEqual(currFolder, parentFolder, true)) {
return { label: '..', uri: resources.addTrailingPathSeparator(parentFolder, this.separator), isFolder: true };
}
return null;
}
private async createItems(currentFolder: URI): Promise<FileQuickPickItem[]> {
const result: FileQuickPickItem[] = [];
const backDir = this.createBackItem(currentFolder);
try {
const folder = await this.fileService.resolve(currentFolder);
const fileNames = folder.children ? folder.children.map(child => child.name) : [];
const items = await Promise.all(fileNames.map(fileName => this.createItem(fileName, currentFolder)));
for (let item of items) {
if (item) {
result.push(item);
}
}
} catch (e) {
// ignore
console.log(e);
}
const sorted = result.sort((i1, i2) => {
if (i1.isFolder !== i2.isFolder) {
return i1.isFolder ? -1 : 1;
}
const trimmed1 = this.endsWithSlash(i1.label) ? i1.label.substr(0, i1.label.length - 1) : i1.label;
const trimmed2 = this.endsWithSlash(i2.label) ? i2.label.substr(0, i2.label.length - 1) : i2.label;
return trimmed1.localeCompare(trimmed2);
});
if (backDir) {
sorted.unshift(backDir);
}
return sorted;
}
private filterFile(file: URI): boolean {
if (this.options.filters) {
const ext = resources.extname(file);
for (let i = 0; i < this.options.filters.length; i++) {
for (let j = 0; j < this.options.filters[i].extensions.length; j++) {
if (ext === ('.' + this.options.filters[i].extensions[j])) {
return true;
}
}
}
return false;
}
return true;
}
private async createItem(filename: string, parent: URI): Promise<FileQuickPickItem | undefined> {
let fullPath = resources.joinPath(parent, filename);
try {
const stat = await this.fileService.resolve(fullPath);
if (stat.isDirectory) {
filename = this.basenameWithTrailingSlash(fullPath);
fullPath = resources.addTrailingPathSeparator(fullPath, this.separator);
return { label: filename, uri: fullPath, isFolder: true, iconClasses: getIconClasses(this.modelService, this.modeService, fullPath || undefined, FileKind.FOLDER) };
} else if (!stat.isDirectory && this.allowFileSelection && this.filterFile(fullPath)) {
return { label: filename, uri: fullPath, isFolder: false, iconClasses: getIconClasses(this.modelService, this.modeService, fullPath || undefined) };
}
return undefined;
} catch (e) {
return undefined;
}
}
} | src/vs/workbench/services/dialogs/browser/remoteFileDialog.ts | 1 | https://github.com/microsoft/vscode/commit/985de26b3446636f86e2bb2b14dbeb9ec1e33207 | [
0.9990900754928589,
0.06055369973182678,
0.00015940451703500003,
0.00017360752099193633,
0.23255445063114166
] |
{
"id": 4,
"code_window": [
"\t\treturn this.pickResource();\n",
"\t}\n",
"\n",
"\tpublic async showSaveDialog(options: ISaveDialogOptions): Promise<URI | undefined> {\n",
"\t\tthis.scheme = this.getScheme(options.defaultUri, options.availableFileSystems);\n",
"\t\tthis.userHome = await this.getUserHome();\n",
"\t\tthis.requiresTrailing = true;\n",
"\t\tconst newOptions = await this.getOptions(options, true);\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\tthis.scheme = this.getScheme(options.availableFileSystems);\n"
],
"file_path": "src/vs/workbench/services/dialogs/browser/remoteFileDialog.ts",
"type": "replace",
"edit_start_line_idx": 111
} | {
"extends": "./tsconfig.base.json",
"compilerOptions": {
"noEmit": true,
"types": [],
"paths": {},
"module": "amd",
"moduleResolution": "classic",
"removeComments": false,
"preserveConstEnums": true,
"target": "es5",
"sourceMap": false,
"declaration": true
},
"include": [
"typings/require.d.ts",
"./typings/require-monaco.d.ts",
"typings/thenable.d.ts",
"typings/es6-promise.d.ts",
"typings/lib.es2018.promise.d.ts",
"typings/lib.array-ext.d.ts",
"typings/lib.ie11_safe_es6.d.ts",
"vs/css.d.ts",
"vs/monaco.d.ts",
"vs/nls.d.ts",
"vs/editor/*",
"vs/base/common/*",
"vs/base/browser/*",
"vs/base/parts/tree/*",
"vs/base/parts/quickopen/*",
"vs/platform/*/common/*",
"vs/platform/*/browser/*"
],
"exclude": [
"node_modules/*"
]
}
| src/tsconfig.monaco.json | 0 | https://github.com/microsoft/vscode/commit/985de26b3446636f86e2bb2b14dbeb9ec1e33207 | [
0.0001760019949870184,
0.00017415592446923256,
0.00017266703071072698,
0.00017397734336555004,
0.0000014908821412973339
] |
{
"id": 4,
"code_window": [
"\t\treturn this.pickResource();\n",
"\t}\n",
"\n",
"\tpublic async showSaveDialog(options: ISaveDialogOptions): Promise<URI | undefined> {\n",
"\t\tthis.scheme = this.getScheme(options.defaultUri, options.availableFileSystems);\n",
"\t\tthis.userHome = await this.getUserHome();\n",
"\t\tthis.requiresTrailing = true;\n",
"\t\tconst newOptions = await this.getOptions(options, true);\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\tthis.scheme = this.getScheme(options.availableFileSystems);\n"
],
"file_path": "src/vs/workbench/services/dialogs/browser/remoteFileDialog.ts",
"type": "replace",
"edit_start_line_idx": 111
} | steps:
- task: NodeTool@0
inputs:
versionSpec: "10.15.1"
- task: geeklearningio.gl-vsts-tasks-yarn.yarn-installer-task.YarnInstaller@2
inputs:
versionSpec: "1.10.1"
- task: AzureKeyVault@1
displayName: 'Azure Key Vault: Get Secrets'
inputs:
azureSubscription: 'vscode-builds-subscription'
KeyVaultName: vscode
- script: |
set -e
export npm_config_arch="$(VSCODE_ARCH)"
cat << EOF > ~/.netrc
machine monacotools.visualstudio.com
password $(devops-pat)
machine github.com
login vscode
password $(github-distro-mixin-password)
EOF
git config user.email "[email protected]"
git config user.name "VSCode"
git remote add distro "https://github.com/$(VSCODE_MIXIN_REPO).git"
git fetch distro
git merge $(node -p "require('./package.json').distro")
CHILD_CONCURRENCY=1 yarn
yarn gulp mixin
yarn gulp hygiene
yarn monaco-compile-check
node build/azure-pipelines/common/installDistroDependencies.js
node build/azure-pipelines/common/installDistroDependencies.js remote
node build/lib/builtInExtensions.js
displayName: Prepare build
- script: |
set -e
VSCODE_MIXIN_PASSWORD="$(github-distro-mixin-password)" \
./build/azure-pipelines/linux/build.sh
displayName: Build
- script: |
set -e
yarn gulp "electron-$(VSCODE_ARCH)"
# xvfb seems to be crashing often, let's make sure it's always up
service xvfb start
DISPLAY=:10 ./scripts/test.sh --build --tfs "Unit Tests"
# yarn smoketest -- --build "$(agent.builddirectory)/VSCode-linux-$(VSCODE_ARCH)"
displayName: Run unit tests
- script: |
set -e
AZURE_DOCUMENTDB_MASTERKEY="$(builds-docdb-key-readwrite)" \
AZURE_STORAGE_ACCESS_KEY_2="$(vscode-storage-key)" \
VSCODE_MIXIN_PASSWORD="$(github-distro-mixin-password)" \
VSCODE_HOCKEYAPP_TOKEN="$(vscode-hockeyapp-token)" \
./build/azure-pipelines/linux/publish.sh
displayName: Publish
- task: ms.vss-governance-buildtask.governance-build-task-component-detection.ComponentGovernanceComponentDetection@0
displayName: 'Component Detection'
continueOnError: true
- task: PublishPipelineArtifact@0
displayName: 'Publish Pipeline Artifact'
inputs:
artifactName: snap-$(VSCODE_ARCH)
targetPath: .build/linux/snap-tarball
| build/azure-pipelines/linux/product-build-linux.yml | 0 | https://github.com/microsoft/vscode/commit/985de26b3446636f86e2bb2b14dbeb9ec1e33207 | [
0.0001779345329850912,
0.00017577224934939295,
0.00017345264495816082,
0.00017549790209159255,
0.0000012887198863609228
] |
{
"id": 4,
"code_window": [
"\t\treturn this.pickResource();\n",
"\t}\n",
"\n",
"\tpublic async showSaveDialog(options: ISaveDialogOptions): Promise<URI | undefined> {\n",
"\t\tthis.scheme = this.getScheme(options.defaultUri, options.availableFileSystems);\n",
"\t\tthis.userHome = await this.getUserHome();\n",
"\t\tthis.requiresTrailing = true;\n",
"\t\tconst newOptions = await this.getOptions(options, true);\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\tthis.scheme = this.getScheme(options.availableFileSystems);\n"
],
"file_path": "src/vs/workbench/services/dialogs/browser/remoteFileDialog.ts",
"type": "replace",
"edit_start_line_idx": 111
} | {
// Use IntelliSense to learn about possible Node.js debug attributes.
// Hover to view descriptions of existing attributes.
// For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
"version": "0.2.0",
"configurations": [
{
"type": "extensionHost",
"request": "launch",
"name": "Launch Extension",
"runtimeExecutable": "${execPath}",
"args": [
"--extensionDevelopmentPath=${workspaceFolder}"
],
"sourceMaps": true,
"outFiles": [
"${workspaceFolder}/out/**/*.js"
]
}
]
} | extensions/emmet/.vscode/launch.json | 0 | https://github.com/microsoft/vscode/commit/985de26b3446636f86e2bb2b14dbeb9ec1e33207 | [
0.00017764975200407207,
0.00017586121975909919,
0.0001733076642267406,
0.0001766261993907392,
0.000001853347157521057
] |
{
"id": 5,
"code_window": [
"\t}\n",
"\n",
"\tprivate getOptions(options: ISaveDialogOptions | IOpenDialogOptions, isSave: boolean = false): IOpenDialogOptions | undefined {\n",
"\t\tlet defaultUri = options.defaultUri;\n",
"\t\tconst filename = (defaultUri && isSave && (resources.dirname(defaultUri).path === '/')) ? resources.basename(defaultUri) : undefined;\n",
"\t\tif (!defaultUri || filename) {\n",
"\t\t\tdefaultUri = this.userHome;\n",
"\t\t\tif (filename) {\n",
"\t\t\t\tdefaultUri = resources.joinPath(defaultUri, filename);\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\tlet defaultUri: URI | undefined = undefined;\n",
"\t\tlet filename: string | undefined = undefined;\n",
"\t\tif (options.defaultUri) {\n",
"\t\t\tdefaultUri = (this.scheme === options.defaultUri.scheme) ? options.defaultUri : undefined;\n",
"\t\t\tfilename = isSave ? resources.basename(options.defaultUri) : undefined;\n",
"\t\t}\n",
"\t\tif (!defaultUri) {\n"
],
"file_path": "src/vs/workbench/services/dialogs/browser/remoteFileDialog.ts",
"type": "replace",
"edit_start_line_idx": 130
} | /*---------------------------------------------------------------------------------------------
* 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 { URI } from 'vs/base/common/uri';
import * as errors from 'vs/base/common/errors';
import * as objects from 'vs/base/common/objects';
import { Event, Emitter } from 'vs/base/common/event';
import * as platform from 'vs/base/common/platform';
import { IWindowsService } from 'vs/platform/windows/common/windows';
import { IBackupFileService } from 'vs/workbench/services/backup/common/backup';
import { IResult, ITextFileOperationResult, ITextFileService, ITextFileStreamContent, IAutoSaveConfiguration, AutoSaveMode, SaveReason, ITextFileEditorModelManager, ITextFileEditorModel, ModelState, ISaveOptions, AutoSaveContext, IWillMoveEvent, ITextFileContent, IResourceEncodings, IReadTextFileOptions, IWriteTextFileOptions, toBufferOrReadable, TextFileOperationError, TextFileOperationResult } from 'vs/workbench/services/textfile/common/textfiles';
import { ConfirmResult, IRevertOptions } from 'vs/workbench/common/editor';
import { ILifecycleService, ShutdownReason, LifecyclePhase } from 'vs/platform/lifecycle/common/lifecycle';
import { IWorkspaceContextService, WorkbenchState } from 'vs/platform/workspace/common/workspace';
import { IFileService, IFilesConfiguration, FileOperationError, FileOperationResult, AutoSaveConfiguration, HotExitConfiguration, IFileStatWithMetadata, ICreateFileOptions } from 'vs/platform/files/common/files';
import { IConfigurationService } from 'vs/platform/configuration/common/configuration';
import { Disposable } from 'vs/base/common/lifecycle';
import { IWorkbenchEnvironmentService } from 'vs/workbench/services/environment/common/environmentService';
import { IUntitledEditorService } from 'vs/workbench/services/untitled/common/untitledEditorService';
import { UntitledEditorModel } from 'vs/workbench/common/editor/untitledEditorModel';
import { TextFileEditorModelManager } from 'vs/workbench/services/textfile/common/textFileEditorModelManager';
import { IInstantiationService, ServiceIdentifier } from 'vs/platform/instantiation/common/instantiation';
import { ResourceMap } from 'vs/base/common/map';
import { Schemas } from 'vs/base/common/network';
import { IHistoryService } from 'vs/workbench/services/history/common/history';
import { IContextKey, IContextKeyService } from 'vs/platform/contextkey/common/contextkey';
import { createTextBufferFactoryFromSnapshot, createTextBufferFactoryFromStream } from 'vs/editor/common/model/textModel';
import { IModelService } from 'vs/editor/common/services/modelService';
import { INotificationService, Severity } from 'vs/platform/notification/common/notification';
import { isEqualOrParent, isEqual, joinPath, dirname, extname, basename, toLocalResource } from 'vs/base/common/resources';
import { posix } from 'vs/base/common/path';
import { getConfirmMessage, IDialogService, IFileDialogService, ISaveDialogOptions, IConfirmation } from 'vs/platform/dialogs/common/dialogs';
import { IModeService } from 'vs/editor/common/services/modeService';
import { IEditorService } from 'vs/workbench/services/editor/common/editorService';
import { coalesce } from 'vs/base/common/arrays';
import { trim } from 'vs/base/common/strings';
import { VSBuffer } from 'vs/base/common/buffer';
import { ITextSnapshot } from 'vs/editor/common/model';
import { ITextResourceConfigurationService } from 'vs/editor/common/services/resourceConfiguration';
import { PLAINTEXT_MODE_ID } from 'vs/editor/common/modes/modesRegistry';
/**
* The workbench file service implementation implements the raw file service spec and adds additional methods on top.
*/
export abstract class TextFileService extends Disposable implements ITextFileService {
_serviceBrand: ServiceIdentifier<any>;
private readonly _onAutoSaveConfigurationChange: Emitter<IAutoSaveConfiguration> = this._register(new Emitter<IAutoSaveConfiguration>());
get onAutoSaveConfigurationChange(): Event<IAutoSaveConfiguration> { return this._onAutoSaveConfigurationChange.event; }
private readonly _onFilesAssociationChange: Emitter<void> = this._register(new Emitter<void>());
get onFilesAssociationChange(): Event<void> { return this._onFilesAssociationChange.event; }
private readonly _onWillMove = this._register(new Emitter<IWillMoveEvent>());
get onWillMove(): Event<IWillMoveEvent> { return this._onWillMove.event; }
private _models: TextFileEditorModelManager;
get models(): ITextFileEditorModelManager { return this._models; }
abstract get encoding(): IResourceEncodings;
private currentFilesAssociationConfig: { [key: string]: string; };
private configuredAutoSaveDelay?: number;
private configuredAutoSaveOnFocusChange: boolean;
private configuredAutoSaveOnWindowChange: boolean;
private configuredHotExit: string;
private autoSaveContext: IContextKey<string>;
constructor(
@IWorkspaceContextService private readonly contextService: IWorkspaceContextService,
@IFileService protected readonly fileService: IFileService,
@IUntitledEditorService private readonly untitledEditorService: IUntitledEditorService,
@ILifecycleService private readonly lifecycleService: ILifecycleService,
@IInstantiationService protected instantiationService: IInstantiationService,
@IConfigurationService private readonly configurationService: IConfigurationService,
@IModeService private readonly modeService: IModeService,
@IModelService private readonly modelService: IModelService,
@IWorkbenchEnvironmentService protected readonly environmentService: IWorkbenchEnvironmentService,
@INotificationService private readonly notificationService: INotificationService,
@IBackupFileService private readonly backupFileService: IBackupFileService,
@IWindowsService private readonly windowsService: IWindowsService,
@IHistoryService private readonly historyService: IHistoryService,
@IContextKeyService contextKeyService: IContextKeyService,
@IDialogService private readonly dialogService: IDialogService,
@IFileDialogService private readonly fileDialogService: IFileDialogService,
@IEditorService private readonly editorService: IEditorService,
@ITextResourceConfigurationService protected readonly textResourceConfigurationService: ITextResourceConfigurationService
) {
super();
this._models = this._register(instantiationService.createInstance(TextFileEditorModelManager));
this.autoSaveContext = AutoSaveContext.bindTo(contextKeyService);
const configuration = configurationService.getValue<IFilesConfiguration>();
this.currentFilesAssociationConfig = configuration && configuration.files && configuration.files.associations;
this.onFilesConfigurationChange(configuration);
this.registerListeners();
}
//#region event handling
private registerListeners(): void {
// Lifecycle
this.lifecycleService.onBeforeShutdown(event => event.veto(this.beforeShutdown(event.reason)));
this.lifecycleService.onShutdown(this.dispose, this);
// Files configuration changes
this._register(this.configurationService.onDidChangeConfiguration(e => {
if (e.affectsConfiguration('files')) {
this.onFilesConfigurationChange(this.configurationService.getValue<IFilesConfiguration>());
}
}));
}
private beforeShutdown(reason: ShutdownReason): boolean | Promise<boolean> {
// Dirty files need treatment on shutdown
const dirty = this.getDirty();
if (dirty.length) {
// If auto save is enabled, save all files and then check again for dirty files
// We DO NOT run any save participant if we are in the shutdown phase for performance reasons
if (this.getAutoSaveMode() !== AutoSaveMode.OFF) {
return this.saveAll(false /* files only */, { skipSaveParticipants: true }).then(() => {
// If we still have dirty files, we either have untitled ones or files that cannot be saved
const remainingDirty = this.getDirty();
if (remainingDirty.length) {
return this.handleDirtyBeforeShutdown(remainingDirty, reason);
}
return false;
});
}
// Auto save is not enabled
return this.handleDirtyBeforeShutdown(dirty, reason);
}
// No dirty files: no veto
return this.noVeto({ cleanUpBackups: true });
}
private handleDirtyBeforeShutdown(dirty: URI[], reason: ShutdownReason): boolean | Promise<boolean> {
// If hot exit is enabled, backup dirty files and allow to exit without confirmation
if (this.isHotExitEnabled) {
return this.backupBeforeShutdown(dirty, this.models, reason).then(didBackup => {
if (didBackup) {
return this.noVeto({ cleanUpBackups: false }); // no veto and no backup cleanup (since backup was successful)
}
// since a backup did not happen, we have to confirm for the dirty files now
return this.confirmBeforeShutdown();
}, errors => {
const firstError = errors[0];
this.notificationService.error(nls.localize('files.backup.failSave', "Files that are dirty could not be written to the backup location (Error: {0}). Try saving your files first and then exit.", firstError.message));
return true; // veto, the backups failed
});
}
// Otherwise just confirm from the user what to do with the dirty files
return this.confirmBeforeShutdown();
}
private async backupBeforeShutdown(dirtyToBackup: URI[], textFileEditorModelManager: ITextFileEditorModelManager, reason: ShutdownReason): Promise<boolean> {
const windowCount = await this.windowsService.getWindowCount();
// When quit is requested skip the confirm callback and attempt to backup all workspaces.
// When quit is not requested the confirm callback should be shown when the window being
// closed is the only VS Code window open, except for on Mac where hot exit is only
// ever activated when quit is requested.
let doBackup: boolean | undefined;
switch (reason) {
case ShutdownReason.CLOSE:
if (this.contextService.getWorkbenchState() !== WorkbenchState.EMPTY && this.configuredHotExit === HotExitConfiguration.ON_EXIT_AND_WINDOW_CLOSE) {
doBackup = true; // backup if a folder is open and onExitAndWindowClose is configured
} else if (windowCount > 1 || platform.isMacintosh) {
doBackup = false; // do not backup if a window is closed that does not cause quitting of the application
} else {
doBackup = true; // backup if last window is closed on win/linux where the application quits right after
}
break;
case ShutdownReason.QUIT:
doBackup = true; // backup because next start we restore all backups
break;
case ShutdownReason.RELOAD:
doBackup = true; // backup because after window reload, backups restore
break;
case ShutdownReason.LOAD:
if (this.contextService.getWorkbenchState() !== WorkbenchState.EMPTY && this.configuredHotExit === HotExitConfiguration.ON_EXIT_AND_WINDOW_CLOSE) {
doBackup = true; // backup if a folder is open and onExitAndWindowClose is configured
} else {
doBackup = false; // do not backup because we are switching contexts
}
break;
}
if (!doBackup) {
return false;
}
await this.backupAll(dirtyToBackup, textFileEditorModelManager);
return true;
}
private backupAll(dirtyToBackup: URI[], textFileEditorModelManager: ITextFileEditorModelManager): Promise<void> {
// split up between files and untitled
const filesToBackup: ITextFileEditorModel[] = [];
const untitledToBackup: URI[] = [];
dirtyToBackup.forEach(s => {
if (this.fileService.canHandleResource(s)) {
const model = textFileEditorModelManager.get(s);
if (model) {
filesToBackup.push(model);
}
} else if (s.scheme === Schemas.untitled) {
untitledToBackup.push(s);
}
});
return this.doBackupAll(filesToBackup, untitledToBackup);
}
private async doBackupAll(dirtyFileModels: ITextFileEditorModel[], untitledResources: URI[]): Promise<void> {
// Handle file resources first
await Promise.all(dirtyFileModels.map(model => model.backup()));
// Handle untitled resources
await Promise.all(untitledResources
.filter(untitled => this.untitledEditorService.exists(untitled))
.map(async untitled => (await this.untitledEditorService.loadOrCreate({ resource: untitled })).backup()));
}
private async confirmBeforeShutdown(): Promise<boolean> {
const confirm = await this.confirmSave();
// Save
if (confirm === ConfirmResult.SAVE) {
const result = await this.saveAll(true /* includeUntitled */, { skipSaveParticipants: true });
if (result.results.some(r => !r.success)) {
return true; // veto if some saves failed
}
return this.noVeto({ cleanUpBackups: true });
}
// Don't Save
else if (confirm === ConfirmResult.DONT_SAVE) {
// Make sure to revert untitled so that they do not restore
// see https://github.com/Microsoft/vscode/issues/29572
this.untitledEditorService.revertAll();
return this.noVeto({ cleanUpBackups: true });
}
// Cancel
else if (confirm === ConfirmResult.CANCEL) {
return true; // veto
}
return false;
}
private noVeto(options: { cleanUpBackups: boolean }): boolean | Promise<boolean> {
if (!options.cleanUpBackups) {
return false;
}
if (this.lifecycleService.phase < LifecyclePhase.Restored) {
return false; // if editors have not restored, we are not up to speed with backups and thus should not clean them
}
return this.cleanupBackupsBeforeShutdown().then(() => false, () => false);
}
protected async cleanupBackupsBeforeShutdown(): Promise<void> {
if (this.environmentService.isExtensionDevelopment) {
return;
}
await this.backupFileService.discardAllWorkspaceBackups();
}
protected onFilesConfigurationChange(configuration: IFilesConfiguration): void {
const wasAutoSaveEnabled = (this.getAutoSaveMode() !== AutoSaveMode.OFF);
const autoSaveMode = (configuration && configuration.files && configuration.files.autoSave) || AutoSaveConfiguration.OFF;
this.autoSaveContext.set(autoSaveMode);
switch (autoSaveMode) {
case AutoSaveConfiguration.AFTER_DELAY:
this.configuredAutoSaveDelay = configuration && configuration.files && configuration.files.autoSaveDelay;
this.configuredAutoSaveOnFocusChange = false;
this.configuredAutoSaveOnWindowChange = false;
break;
case AutoSaveConfiguration.ON_FOCUS_CHANGE:
this.configuredAutoSaveDelay = undefined;
this.configuredAutoSaveOnFocusChange = true;
this.configuredAutoSaveOnWindowChange = false;
break;
case AutoSaveConfiguration.ON_WINDOW_CHANGE:
this.configuredAutoSaveDelay = undefined;
this.configuredAutoSaveOnFocusChange = false;
this.configuredAutoSaveOnWindowChange = true;
break;
default:
this.configuredAutoSaveDelay = undefined;
this.configuredAutoSaveOnFocusChange = false;
this.configuredAutoSaveOnWindowChange = false;
break;
}
// Emit as event
this._onAutoSaveConfigurationChange.fire(this.getAutoSaveConfiguration());
// save all dirty when enabling auto save
if (!wasAutoSaveEnabled && this.getAutoSaveMode() !== AutoSaveMode.OFF) {
this.saveAll();
}
// Check for change in files associations
const filesAssociation = configuration && configuration.files && configuration.files.associations;
if (!objects.equals(this.currentFilesAssociationConfig, filesAssociation)) {
this.currentFilesAssociationConfig = filesAssociation;
this._onFilesAssociationChange.fire();
}
// Hot exit
const hotExitMode = configuration && configuration.files && configuration.files.hotExit;
if (hotExitMode === HotExitConfiguration.OFF || hotExitMode === HotExitConfiguration.ON_EXIT_AND_WINDOW_CLOSE) {
this.configuredHotExit = hotExitMode;
} else {
this.configuredHotExit = HotExitConfiguration.ON_EXIT;
}
}
//#endregion
//#region primitives (read, create, move, delete, update)
async read(resource: URI, options?: IReadTextFileOptions): Promise<ITextFileContent> {
const content = await this.fileService.readFile(resource, options);
// in case of acceptTextOnly: true, we check the first
// chunk for possibly being binary by looking for 0-bytes
// we limit this check to the first 512 bytes
this.validateBinary(content.value, options);
return {
...content,
encoding: 'utf8',
value: content.value.toString()
};
}
async readStream(resource: URI, options?: IReadTextFileOptions): Promise<ITextFileStreamContent> {
const stream = await this.fileService.readFileStream(resource, options);
// in case of acceptTextOnly: true, we check the first
// chunk for possibly being binary by looking for 0-bytes
// we limit this check to the first 512 bytes
let checkedForBinary = false;
const throwOnBinary = (data: VSBuffer): Error | undefined => {
if (!checkedForBinary) {
checkedForBinary = true;
this.validateBinary(data, options);
}
return undefined;
};
return {
...stream,
encoding: 'utf8',
value: await createTextBufferFactoryFromStream(stream.value, undefined, options && options.acceptTextOnly ? throwOnBinary : undefined)
};
}
private validateBinary(buffer: VSBuffer, options?: IReadTextFileOptions): void {
if (!options || !options.acceptTextOnly) {
return; // no validation needed
}
// in case of acceptTextOnly: true, we check the first
// chunk for possibly being binary by looking for 0-bytes
// we limit this check to the first 512 bytes
for (let i = 0; i < buffer.byteLength && i < 512; i++) {
if (buffer.readUInt8(i) === 0) {
throw new TextFileOperationError(nls.localize('fileBinaryError', "File seems to be binary and cannot be opened as text"), TextFileOperationResult.FILE_IS_BINARY, options);
}
}
}
async create(resource: URI, value?: string | ITextSnapshot, options?: ICreateFileOptions): Promise<IFileStatWithMetadata> {
const stat = await this.doCreate(resource, value, options);
// If we had an existing model for the given resource, load
// it again to make sure it is up to date with the contents
// we just wrote into the underlying resource by calling
// revert()
const existingModel = this.models.get(resource);
if (existingModel && !existingModel.isDisposed()) {
await existingModel.revert();
}
return stat;
}
protected doCreate(resource: URI, value?: string | ITextSnapshot, options?: ICreateFileOptions): Promise<IFileStatWithMetadata> {
return this.fileService.createFile(resource, toBufferOrReadable(value), options);
}
async write(resource: URI, value: string | ITextSnapshot, options?: IWriteTextFileOptions): Promise<IFileStatWithMetadata> {
return this.fileService.writeFile(resource, toBufferOrReadable(value), options);
}
async delete(resource: URI, options?: { useTrash?: boolean, recursive?: boolean }): Promise<void> {
const dirtyFiles = this.getDirty().filter(dirty => isEqualOrParent(dirty, resource, !platform.isLinux /* ignorecase */));
await this.revertAll(dirtyFiles, { soft: true });
return this.fileService.del(resource, options);
}
async move(source: URI, target: URI, overwrite?: boolean): Promise<IFileStatWithMetadata> {
const waitForPromises: Promise<unknown>[] = [];
// Event
this._onWillMove.fire({
oldResource: source,
newResource: target,
waitUntil(promise: Promise<unknown>) {
waitForPromises.push(promise.then(undefined, errors.onUnexpectedError));
}
});
// prevent async waitUntil-calls
Object.freeze(waitForPromises);
await Promise.all(waitForPromises);
// Handle target models if existing (if target URI is a folder, this can be multiple)
const dirtyTargetModels = this.getDirtyFileModels().filter(model => isEqualOrParent(model.getResource(), target, false /* do not ignorecase, see https://github.com/Microsoft/vscode/issues/56384 */));
if (dirtyTargetModels.length) {
await this.revertAll(dirtyTargetModels.map(targetModel => targetModel.getResource()), { soft: true });
}
// Handle dirty source models if existing (if source URI is a folder, this can be multiple)
const dirtySourceModels = this.getDirtyFileModels().filter(model => isEqualOrParent(model.getResource(), source, !platform.isLinux /* ignorecase */));
const dirtyTargetModelUris: URI[] = [];
if (dirtySourceModels.length) {
await Promise.all(dirtySourceModels.map(async sourceModel => {
const sourceModelResource = sourceModel.getResource();
let targetModelResource: URI;
// If the source is the actual model, just use target as new resource
if (isEqual(sourceModelResource, source, !platform.isLinux /* ignorecase */)) {
targetModelResource = target;
}
// Otherwise a parent folder of the source is being moved, so we need
// to compute the target resource based on that
else {
targetModelResource = sourceModelResource.with({ path: joinPath(target, sourceModelResource.path.substr(source.path.length + 1)).path });
}
// Remember as dirty target model to load after the operation
dirtyTargetModelUris.push(targetModelResource);
// Backup dirty source model to the target resource it will become later
await sourceModel.backup(targetModelResource);
}));
}
// Soft revert the dirty source files if any
await this.revertAll(dirtySourceModels.map(dirtySourceModel => dirtySourceModel.getResource()), { soft: true });
// Rename to target
try {
const stat = await this.fileService.move(source, target, overwrite);
// Load models that were dirty before
await Promise.all(dirtyTargetModelUris.map(dirtyTargetModel => this.models.loadOrCreate(dirtyTargetModel)));
return stat;
} catch (error) {
// In case of an error, discard any dirty target backups that were made
await Promise.all(dirtyTargetModelUris.map(dirtyTargetModel => this.backupFileService.discardResourceBackup(dirtyTargetModel)));
throw error;
}
}
//#endregion
//#region save/revert
async save(resource: URI, options?: ISaveOptions): Promise<boolean> {
// Run a forced save if we detect the file is not dirty so that save participants can still run
if (options && options.force && this.fileService.canHandleResource(resource) && !this.isDirty(resource)) {
const model = this._models.get(resource);
if (model) {
options.reason = SaveReason.EXPLICIT;
await model.save(options);
return !model.isDirty();
}
}
const result = await this.saveAll([resource], options);
return result.results.length === 1 && !!result.results[0].success;
}
async confirmSave(resources?: URI[]): Promise<ConfirmResult> {
if (this.environmentService.isExtensionDevelopment) {
return ConfirmResult.DONT_SAVE; // no veto when we are in extension dev mode because we cannot assum we run interactive (e.g. tests)
}
const resourcesToConfirm = this.getDirty(resources);
if (resourcesToConfirm.length === 0) {
return ConfirmResult.DONT_SAVE;
}
const message = resourcesToConfirm.length === 1 ? nls.localize('saveChangesMessage', "Do you want to save the changes you made to {0}?", basename(resourcesToConfirm[0]))
: getConfirmMessage(nls.localize('saveChangesMessages', "Do you want to save the changes to the following {0} files?", resourcesToConfirm.length), resourcesToConfirm);
const buttons: string[] = [
resourcesToConfirm.length > 1 ? nls.localize({ key: 'saveAll', comment: ['&& denotes a mnemonic'] }, "&&Save All") : nls.localize({ key: 'save', comment: ['&& denotes a mnemonic'] }, "&&Save"),
nls.localize({ key: 'dontSave', comment: ['&& denotes a mnemonic'] }, "Do&&n't Save"),
nls.localize('cancel', "Cancel")
];
const index = await this.dialogService.show(Severity.Warning, message, buttons, {
cancelId: 2,
detail: nls.localize('saveChangesDetail', "Your changes will be lost if you don't save them.")
});
switch (index) {
case 0: return ConfirmResult.SAVE;
case 1: return ConfirmResult.DONT_SAVE;
default: return ConfirmResult.CANCEL;
}
}
async confirmOverwrite(resource: URI): Promise<boolean> {
const confirm: IConfirmation = {
message: nls.localize('confirmOverwrite', "'{0}' already exists. Do you want to replace it?", basename(resource)),
detail: nls.localize('irreversible', "A file or folder with the same name already exists in the folder {0}. Replacing it will overwrite its current contents.", basename(dirname(resource))),
primaryButton: nls.localize({ key: 'replaceButtonLabel', comment: ['&& denotes a mnemonic'] }, "&&Replace"),
type: 'warning'
};
return (await this.dialogService.confirm(confirm)).confirmed;
}
saveAll(includeUntitled?: boolean, options?: ISaveOptions): Promise<ITextFileOperationResult>;
saveAll(resources: URI[], options?: ISaveOptions): Promise<ITextFileOperationResult>;
saveAll(arg1?: boolean | URI[], options?: ISaveOptions): Promise<ITextFileOperationResult> {
// get all dirty
let toSave: URI[] = [];
if (Array.isArray(arg1)) {
toSave = this.getDirty(arg1);
} else {
toSave = this.getDirty();
}
// split up between files and untitled
const filesToSave: URI[] = [];
const untitledToSave: URI[] = [];
toSave.forEach(s => {
if ((Array.isArray(arg1) || arg1 === true /* includeUntitled */) && s.scheme === Schemas.untitled) {
untitledToSave.push(s);
} else {
filesToSave.push(s);
}
});
return this.doSaveAll(filesToSave, untitledToSave, options);
}
private async doSaveAll(fileResources: URI[], untitledResources: URI[], options?: ISaveOptions): Promise<ITextFileOperationResult> {
// Handle files first that can just be saved
const result = await this.doSaveAllFiles(fileResources, options);
// Preflight for untitled to handle cancellation from the dialog
const targetsForUntitled: URI[] = [];
for (const untitled of untitledResources) {
if (this.untitledEditorService.exists(untitled)) {
let targetUri: URI;
// Untitled with associated file path don't need to prompt
if (this.untitledEditorService.hasAssociatedFilePath(untitled)) {
targetUri = toLocalResource(untitled, this.environmentService.configuration.remoteAuthority);
}
// Otherwise ask user
else {
const targetPath = await this.promptForPath(untitled, this.suggestFileName(untitled));
if (!targetPath) {
return { results: [...fileResources, ...untitledResources].map(r => ({ source: r })) };
}
targetUri = targetPath;
}
targetsForUntitled.push(targetUri);
}
}
// Handle untitled
await Promise.all(targetsForUntitled.map(async (target, index) => {
const uri = await this.saveAs(untitledResources[index], target);
result.results.push({
source: untitledResources[index],
target: uri,
success: !!uri
});
}));
return result;
}
protected async promptForPath(resource: URI, defaultUri: URI): Promise<URI | undefined> {
// Help user to find a name for the file by opening it first
await this.editorService.openEditor({ resource, options: { revealIfOpened: true, preserveFocus: true, } });
return this.fileDialogService.pickFileToSave(this.getSaveDialogOptions(defaultUri));
}
private getSaveDialogOptions(defaultUri: URI): ISaveDialogOptions {
const options: ISaveDialogOptions = {
defaultUri,
title: nls.localize('saveAsTitle', "Save As")
};
// Filters are only enabled on Windows where they work properly
if (!platform.isWindows) {
return options;
}
interface IFilter { name: string; extensions: string[]; }
// Build the file filter by using our known languages
const ext: string | undefined = defaultUri ? extname(defaultUri) : undefined;
let matchingFilter: IFilter | undefined;
const filters: IFilter[] = coalesce(this.modeService.getRegisteredLanguageNames().map(languageName => {
const extensions = this.modeService.getExtensions(languageName);
if (!extensions || !extensions.length) {
return null;
}
const filter: IFilter = { name: languageName, extensions: extensions.slice(0, 10).map(e => trim(e, '.')) };
if (ext && extensions.indexOf(ext) >= 0) {
matchingFilter = filter;
return null; // matching filter will be added last to the top
}
return filter;
}));
// Filters are a bit weird on Windows, based on having a match or not:
// Match: we put the matching filter first so that it shows up selected and the all files last
// No match: we put the all files filter first
const allFilesFilter = { name: nls.localize('allFiles', "All Files"), extensions: ['*'] };
if (matchingFilter) {
filters.unshift(matchingFilter);
filters.unshift(allFilesFilter);
} else {
filters.unshift(allFilesFilter);
}
// Allow to save file without extension
filters.push({ name: nls.localize('noExt', "No Extension"), extensions: [''] });
options.filters = filters;
return options;
}
private async doSaveAllFiles(resources?: URI[], options: ISaveOptions = Object.create(null)): Promise<ITextFileOperationResult> {
const dirtyFileModels = this.getDirtyFileModels(Array.isArray(resources) ? resources : undefined /* Save All */)
.filter(model => {
if ((model.hasState(ModelState.CONFLICT) || model.hasState(ModelState.ERROR)) && (options.reason === SaveReason.AUTO || options.reason === SaveReason.FOCUS_CHANGE || options.reason === SaveReason.WINDOW_CHANGE)) {
return false; // if model is in save conflict or error, do not save unless save reason is explicit or not provided at all
}
return true;
});
const mapResourceToResult = new ResourceMap<IResult>();
dirtyFileModels.forEach(m => {
mapResourceToResult.set(m.getResource(), {
source: m.getResource()
});
});
await Promise.all(dirtyFileModels.map(async model => {
await model.save(options);
if (!model.isDirty()) {
const result = mapResourceToResult.get(model.getResource());
if (result) {
result.success = true;
}
}
}));
return { results: mapResourceToResult.values() };
}
private getFileModels(arg1?: URI | URI[]): ITextFileEditorModel[] {
if (Array.isArray(arg1)) {
const models: ITextFileEditorModel[] = [];
arg1.forEach(resource => {
models.push(...this.getFileModels(resource));
});
return models;
}
return this._models.getAll(arg1);
}
private getDirtyFileModels(resources?: URI | URI[]): ITextFileEditorModel[] {
return this.getFileModels(resources).filter(model => model.isDirty());
}
async saveAs(resource: URI, targetResource?: URI, options?: ISaveOptions): Promise<URI | undefined> {
// Get to target resource
if (!targetResource) {
let dialogPath = resource;
if (resource.scheme === Schemas.untitled) {
dialogPath = this.suggestFileName(resource);
}
targetResource = await this.promptForPath(resource, dialogPath);
}
if (!targetResource) {
return; // user canceled
}
// Just save if target is same as models own resource
if (resource.toString() === targetResource.toString()) {
await this.save(resource, options);
return resource;
}
// Do it
return this.doSaveAs(resource, targetResource, options);
}
private async doSaveAs(resource: URI, target: URI, options?: ISaveOptions): Promise<URI> {
// Retrieve text model from provided resource if any
let model: ITextFileEditorModel | UntitledEditorModel | undefined;
if (this.fileService.canHandleResource(resource)) {
model = this._models.get(resource);
} else if (resource.scheme === Schemas.untitled && this.untitledEditorService.exists(resource)) {
model = await this.untitledEditorService.loadOrCreate({ resource });
}
// We have a model: Use it (can be null e.g. if this file is binary and not a text file or was never opened before)
let result: boolean;
if (model) {
result = await this.doSaveTextFileAs(model, resource, target, options);
}
// Otherwise we can only copy
else {
await this.fileService.copy(resource, target);
result = true;
}
// Return early if the operation was not running
if (!result) {
return target;
}
// Revert the source
await this.revert(resource);
return target;
}
private async doSaveTextFileAs(sourceModel: ITextFileEditorModel | UntitledEditorModel, resource: URI, target: URI, options?: ISaveOptions): Promise<boolean> {
// Prefer an existing model if it is already loaded for the given target resource
let targetExists: boolean = false;
let targetModel = this.models.get(target);
if (targetModel && targetModel.isResolved()) {
targetExists = true;
}
// Otherwise create the target file empty if it does not exist already and resolve it from there
else {
targetExists = await this.fileService.exists(target);
// create target model adhoc if file does not exist yet
if (!targetExists) {
await this.create(target, '');
}
targetModel = await this.models.loadOrCreate(target);
}
try {
// Confirm to overwrite if we have an untitled file with associated file where
// the file actually exists on disk and we are instructed to save to that file
// path. This can happen if the file was created after the untitled file was opened.
// See https://github.com/Microsoft/vscode/issues/67946
let write: boolean;
if (sourceModel instanceof UntitledEditorModel && sourceModel.hasAssociatedFilePath && targetExists && isEqual(target, toLocalResource(sourceModel.getResource(), this.environmentService.configuration.remoteAuthority))) {
write = await this.confirmOverwrite(target);
} else {
write = true;
}
if (!write) {
return false;
}
// take over encoding, mode and model value from source model
targetModel.updatePreferredEncoding(sourceModel.getEncoding());
if (sourceModel.isResolved() && targetModel.isResolved()) {
this.modelService.updateModel(targetModel.textEditorModel, createTextBufferFactoryFromSnapshot(sourceModel.createSnapshot()));
const mode = sourceModel.textEditorModel.getLanguageIdentifier();
if (mode.language !== PLAINTEXT_MODE_ID) {
targetModel.textEditorModel.setMode(mode); // only use if more specific than plain/text
}
}
// save model
await targetModel.save(options);
return true;
} catch (error) {
// binary model: delete the file and run the operation again
if (
(<TextFileOperationError>error).textFileOperationResult === TextFileOperationResult.FILE_IS_BINARY ||
(<FileOperationError>error).fileOperationResult === FileOperationResult.FILE_TOO_LARGE
) {
await this.fileService.del(target);
return this.doSaveTextFileAs(sourceModel, resource, target, options);
}
throw error;
}
}
private suggestFileName(untitledResource: URI): URI {
const untitledFileName = this.untitledEditorService.suggestFileName(untitledResource);
const remoteAuthority = this.environmentService.configuration.remoteAuthority;
const schemeFilter = remoteAuthority ? Schemas.vscodeRemote : Schemas.file;
const lastActiveFile = this.historyService.getLastActiveFile(schemeFilter);
if (lastActiveFile) {
const lastDir = dirname(lastActiveFile);
return joinPath(lastDir, untitledFileName);
}
const lastActiveFolder = this.historyService.getLastActiveWorkspaceRoot(schemeFilter);
if (lastActiveFolder) {
return joinPath(lastActiveFolder, untitledFileName);
}
return schemeFilter === Schemas.file ? URI.file(untitledFileName) : URI.from({ scheme: schemeFilter, authority: remoteAuthority, path: posix.sep + untitledFileName });
}
async revert(resource: URI, options?: IRevertOptions): Promise<boolean> {
const result = await this.revertAll([resource], options);
return result.results.length === 1 && !!result.results[0].success;
}
async revertAll(resources?: URI[], options?: IRevertOptions): Promise<ITextFileOperationResult> {
// Revert files first
const revertOperationResult = await this.doRevertAllFiles(resources, options);
// Revert untitled
const untitledReverted = this.untitledEditorService.revertAll(resources);
untitledReverted.forEach(untitled => revertOperationResult.results.push({ source: untitled, success: true }));
return revertOperationResult;
}
private async doRevertAllFiles(resources?: URI[], options?: IRevertOptions): Promise<ITextFileOperationResult> {
const fileModels = options && options.force ? this.getFileModels(resources) : this.getDirtyFileModels(resources);
const mapResourceToResult = new ResourceMap<IResult>();
fileModels.forEach(m => {
mapResourceToResult.set(m.getResource(), {
source: m.getResource()
});
});
await Promise.all(fileModels.map(async model => {
try {
await model.revert(options && options.soft);
if (!model.isDirty()) {
const result = mapResourceToResult.get(model.getResource());
if (result) {
result.success = true;
}
}
} catch (error) {
// FileNotFound means the file got deleted meanwhile, so still record as successful revert
if ((<FileOperationError>error).fileOperationResult === FileOperationResult.FILE_NOT_FOUND) {
const result = mapResourceToResult.get(model.getResource());
if (result) {
result.success = true;
}
}
// Otherwise bubble up the error
else {
throw error;
}
}
}));
return { results: mapResourceToResult.values() };
}
getDirty(resources?: URI[]): URI[] {
// Collect files
const dirty = this.getDirtyFileModels(resources).map(m => m.getResource());
// Add untitled ones
dirty.push(...this.untitledEditorService.getDirty(resources));
return dirty;
}
isDirty(resource?: URI): boolean {
// Check for dirty file
if (this._models.getAll(resource).some(model => model.isDirty())) {
return true;
}
// Check for dirty untitled
return this.untitledEditorService.getDirty().some(dirty => !resource || dirty.toString() === resource.toString());
}
//#endregion
//#region config
getAutoSaveMode(): AutoSaveMode {
if (this.configuredAutoSaveOnFocusChange) {
return AutoSaveMode.ON_FOCUS_CHANGE;
}
if (this.configuredAutoSaveOnWindowChange) {
return AutoSaveMode.ON_WINDOW_CHANGE;
}
if (this.configuredAutoSaveDelay && this.configuredAutoSaveDelay > 0) {
return this.configuredAutoSaveDelay <= 1000 ? AutoSaveMode.AFTER_SHORT_DELAY : AutoSaveMode.AFTER_LONG_DELAY;
}
return AutoSaveMode.OFF;
}
getAutoSaveConfiguration(): IAutoSaveConfiguration {
return {
autoSaveDelay: this.configuredAutoSaveDelay && this.configuredAutoSaveDelay > 0 ? this.configuredAutoSaveDelay : undefined,
autoSaveFocusChange: this.configuredAutoSaveOnFocusChange,
autoSaveApplicationChange: this.configuredAutoSaveOnWindowChange
};
}
get isHotExitEnabled(): boolean {
return !this.environmentService.isExtensionDevelopment && this.configuredHotExit !== HotExitConfiguration.OFF;
}
//#endregion
dispose(): void {
// Clear all caches
this._models.clear();
super.dispose();
}
} | src/vs/workbench/services/textfile/common/textFileService.ts | 1 | https://github.com/microsoft/vscode/commit/985de26b3446636f86e2bb2b14dbeb9ec1e33207 | [
0.9979538917541504,
0.027291985228657722,
0.00016322422015946358,
0.00017184839816763997,
0.15726067125797272
] |
{
"id": 5,
"code_window": [
"\t}\n",
"\n",
"\tprivate getOptions(options: ISaveDialogOptions | IOpenDialogOptions, isSave: boolean = false): IOpenDialogOptions | undefined {\n",
"\t\tlet defaultUri = options.defaultUri;\n",
"\t\tconst filename = (defaultUri && isSave && (resources.dirname(defaultUri).path === '/')) ? resources.basename(defaultUri) : undefined;\n",
"\t\tif (!defaultUri || filename) {\n",
"\t\t\tdefaultUri = this.userHome;\n",
"\t\t\tif (filename) {\n",
"\t\t\t\tdefaultUri = resources.joinPath(defaultUri, filename);\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\tlet defaultUri: URI | undefined = undefined;\n",
"\t\tlet filename: string | undefined = undefined;\n",
"\t\tif (options.defaultUri) {\n",
"\t\t\tdefaultUri = (this.scheme === options.defaultUri.scheme) ? options.defaultUri : undefined;\n",
"\t\t\tfilename = isSave ? resources.basename(options.defaultUri) : undefined;\n",
"\t\t}\n",
"\t\tif (!defaultUri) {\n"
],
"file_path": "src/vs/workbench/services/dialogs/browser/remoteFileDialog.ts",
"type": "replace",
"edit_start_line_idx": 130
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
export function memoize(_target: any, key: string, descriptor: any) {
let fnKey: string | undefined;
let fn: Function | undefined;
if (typeof descriptor.value === 'function') {
fnKey = 'value';
fn = descriptor.value;
} else if (typeof descriptor.get === 'function') {
fnKey = 'get';
fn = descriptor.get;
} else {
throw new Error('not supported');
}
const memoizeKey = `$memoize$${key}`;
descriptor[fnKey] = function (...args: any[]) {
if (!this.hasOwnProperty(memoizeKey)) {
Object.defineProperty(this, memoizeKey, {
configurable: false,
enumerable: false,
writable: false,
value: fn!.apply(this, args)
});
}
return this[memoizeKey];
};
}
| extensions/typescript-language-features/src/utils/memoize.ts | 0 | https://github.com/microsoft/vscode/commit/985de26b3446636f86e2bb2b14dbeb9ec1e33207 | [
0.0001768661750247702,
0.00017503694107290357,
0.00017373618902638555,
0.00017477269284427166,
0.0000011471556717879139
] |
{
"id": 5,
"code_window": [
"\t}\n",
"\n",
"\tprivate getOptions(options: ISaveDialogOptions | IOpenDialogOptions, isSave: boolean = false): IOpenDialogOptions | undefined {\n",
"\t\tlet defaultUri = options.defaultUri;\n",
"\t\tconst filename = (defaultUri && isSave && (resources.dirname(defaultUri).path === '/')) ? resources.basename(defaultUri) : undefined;\n",
"\t\tif (!defaultUri || filename) {\n",
"\t\t\tdefaultUri = this.userHome;\n",
"\t\t\tif (filename) {\n",
"\t\t\t\tdefaultUri = resources.joinPath(defaultUri, filename);\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\tlet defaultUri: URI | undefined = undefined;\n",
"\t\tlet filename: string | undefined = undefined;\n",
"\t\tif (options.defaultUri) {\n",
"\t\t\tdefaultUri = (this.scheme === options.defaultUri.scheme) ? options.defaultUri : undefined;\n",
"\t\t\tfilename = isSave ? resources.basename(options.defaultUri) : undefined;\n",
"\t\t}\n",
"\t\tif (!defaultUri) {\n"
],
"file_path": "src/vs/workbench/services/dialogs/browser/remoteFileDialog.ts",
"type": "replace",
"edit_start_line_idx": 130
} | /*---------------------------------------------------------------------------------------------
* 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!./media/notificationsToasts';
import { INotificationsModel, NotificationChangeType, INotificationChangeEvent, INotificationViewItem, NotificationViewItemLabelKind } from 'vs/workbench/common/notifications';
import { IDisposable, dispose, toDisposable, DisposableStore } from 'vs/base/common/lifecycle';
import { addClass, removeClass, isAncestor, addDisposableListener, EventType, Dimension } from 'vs/base/browser/dom';
import { IInstantiationService } from 'vs/platform/instantiation/common/instantiation';
import { NotificationsList } from 'vs/workbench/browser/parts/notifications/notificationsList';
import { Event } from 'vs/base/common/event';
import { IWorkbenchLayoutService, Parts } from 'vs/workbench/services/layout/browser/layoutService';
import { Themable, NOTIFICATIONS_TOAST_BORDER } from 'vs/workbench/common/theme';
import { IThemeService } from 'vs/platform/theme/common/themeService';
import { widgetShadow } from 'vs/platform/theme/common/colorRegistry';
import { IEditorGroupsService } from 'vs/workbench/services/editor/common/editorGroupsService';
import { NotificationsToastsVisibleContext } from 'vs/workbench/browser/parts/notifications/notificationsCommands';
import { IContextKeyService, IContextKey } from 'vs/platform/contextkey/common/contextkey';
import { localize } from 'vs/nls';
import { Severity } from 'vs/platform/notification/common/notification';
import { ScrollbarVisibility } from 'vs/base/common/scrollable';
import { ILifecycleService, LifecyclePhase } from 'vs/platform/lifecycle/common/lifecycle';
import { IWindowService } from 'vs/platform/windows/common/windows';
import { timeout } from 'vs/base/common/async';
interface INotificationToast {
item: INotificationViewItem;
list: NotificationsList;
container: HTMLElement;
toast: HTMLElement;
toDispose: DisposableStore;
}
enum ToastVisibility {
HIDDEN_OR_VISIBLE,
HIDDEN,
VISIBLE
}
export class NotificationsToasts extends Themable {
private static MAX_WIDTH = 450;
private static MAX_NOTIFICATIONS = 3;
private static PURGE_TIMEOUT: { [severity: number]: number } = (() => {
const intervals = Object.create(null);
intervals[Severity.Info] = 15000;
intervals[Severity.Warning] = 18000;
intervals[Severity.Error] = 20000;
return intervals;
})();
private notificationsToastsContainer: HTMLElement;
private workbenchDimensions: Dimension;
private isNotificationsCenterVisible: boolean;
private mapNotificationToToast: Map<INotificationViewItem, INotificationToast>;
private notificationsToastsVisibleContextKey: IContextKey<boolean>;
constructor(
private container: HTMLElement,
private model: INotificationsModel,
@IInstantiationService private readonly instantiationService: IInstantiationService,
@IWorkbenchLayoutService private readonly layoutService: IWorkbenchLayoutService,
@IThemeService themeService: IThemeService,
@IEditorGroupsService private readonly editorGroupService: IEditorGroupsService,
@IContextKeyService contextKeyService: IContextKeyService,
@ILifecycleService private readonly lifecycleService: ILifecycleService,
@IWindowService private readonly windowService: IWindowService
) {
super(themeService);
this.mapNotificationToToast = new Map<INotificationViewItem, INotificationToast>();
this.notificationsToastsVisibleContextKey = NotificationsToastsVisibleContext.bindTo(contextKeyService);
this.registerListeners();
}
private registerListeners(): void {
// Layout
this._register(this.layoutService.onLayout(dimension => this.layout(dimension)));
// Delay some tasks until after we can show notifications
this.onCanShowNotifications().then(() => {
// Show toast for initial notifications if any
this.model.notifications.forEach(notification => this.addToast(notification));
// Update toasts on notification changes
this._register(this.model.onDidNotificationChange(e => this.onDidNotificationChange(e)));
});
}
private async onCanShowNotifications(): Promise<void> {
// Wait for the running phase to ensure we can draw notifications properly
await this.lifecycleService.when(LifecyclePhase.Ready);
// Push notificiations out until either workbench is restored
// or some time has ellapsed to reduce pressure on the startup
return Promise.race([
this.lifecycleService.when(LifecyclePhase.Restored),
timeout(2000)
]);
}
private onDidNotificationChange(e: INotificationChangeEvent): void {
switch (e.kind) {
case NotificationChangeType.ADD:
return this.addToast(e.item);
case NotificationChangeType.REMOVE:
return this.removeToast(e.item);
}
}
private addToast(item: INotificationViewItem): void {
if (this.isNotificationsCenterVisible) {
return; // do not show toasts while notification center is visibles
}
if (item.silent) {
return; // do not show toats for silenced notifications
}
// Lazily create toasts containers
if (!this.notificationsToastsContainer) {
this.notificationsToastsContainer = document.createElement('div');
addClass(this.notificationsToastsContainer, 'notifications-toasts');
this.container.appendChild(this.notificationsToastsContainer);
}
// Make Visible
addClass(this.notificationsToastsContainer, 'visible');
const itemDisposeables = new DisposableStore();
// Container
const notificationToastContainer = document.createElement('div');
addClass(notificationToastContainer, 'notification-toast-container');
const firstToast = this.notificationsToastsContainer.firstChild;
if (firstToast) {
this.notificationsToastsContainer.insertBefore(notificationToastContainer, firstToast); // always first
} else {
this.notificationsToastsContainer.appendChild(notificationToastContainer);
}
// Toast
const notificationToast = document.createElement('div');
addClass(notificationToast, 'notification-toast');
notificationToastContainer.appendChild(notificationToast);
// Create toast with item and show
const notificationList = this.instantiationService.createInstance(NotificationsList, notificationToast, {
ariaLabel: localize('notificationsToast', "Notification Toast"),
verticalScrollMode: ScrollbarVisibility.Hidden
});
itemDisposeables.add(notificationList);
const toast: INotificationToast = { item, list: notificationList, container: notificationToastContainer, toast: notificationToast, toDispose: itemDisposeables };
this.mapNotificationToToast.set(item, toast);
itemDisposeables.add(toDisposable(() => {
if (this.isVisible(toast)) {
this.notificationsToastsContainer.removeChild(toast.container);
}
}));
// Make visible
notificationList.show();
// Layout lists
const maxDimensions = this.computeMaxDimensions();
this.layoutLists(maxDimensions.width);
// Show notification
notificationList.updateNotificationsList(0, 0, [item]);
// Layout container: only after we show the notification to ensure that
// the height computation takes the content of it into account!
this.layoutContainer(maxDimensions.height);
// Update when item height changes due to expansion
itemDisposeables.add(item.onDidExpansionChange(() => {
notificationList.updateNotificationsList(0, 1, [item]);
}));
// Update when item height potentially changes due to label changes
itemDisposeables.add(item.onDidLabelChange(e => {
if (!item.expanded) {
return; // dynamic height only applies to expanded notifications
}
if (e.kind === NotificationViewItemLabelKind.ACTIONS || e.kind === NotificationViewItemLabelKind.MESSAGE) {
notificationList.updateNotificationsList(0, 1, [item]);
}
}));
// Remove when item gets closed
Event.once(item.onDidClose)(() => {
this.removeToast(item);
});
// Automatically purge non-sticky notifications
this.purgeNotification(item, notificationToastContainer, notificationList, itemDisposeables);
// Theming
this.updateStyles();
// Context Key
this.notificationsToastsVisibleContextKey.set(true);
// Animate in
addClass(notificationToast, 'notification-fade-in');
itemDisposeables.add(addDisposableListener(notificationToast, 'transitionend', () => {
removeClass(notificationToast, 'notification-fade-in');
addClass(notificationToast, 'notification-fade-in-done');
}));
}
private purgeNotification(item: INotificationViewItem, notificationToastContainer: HTMLElement, notificationList: NotificationsList, disposables: DisposableStore): void {
// Track mouse over item
let isMouseOverToast = false;
disposables.add(addDisposableListener(notificationToastContainer, EventType.MOUSE_OVER, () => isMouseOverToast = true));
disposables.add(addDisposableListener(notificationToastContainer, EventType.MOUSE_OUT, () => isMouseOverToast = false));
// Install Timers to Purge Notification
let purgeTimeoutHandle: any;
let listener: IDisposable;
const hideAfterTimeout = () => {
purgeTimeoutHandle = setTimeout(() => {
// If the notification is sticky or prompting and the window does not have
// focus, we wait for the window to gain focus again before triggering
// the timeout again. This prevents an issue where focussing the window
// could immediately hide the notification because the timeout was triggered
// again.
if ((item.sticky || item.hasPrompt()) && !this.windowService.hasFocus) {
if (!listener) {
listener = this.windowService.onDidChangeFocus(focus => {
if (focus) {
hideAfterTimeout();
}
});
disposables.add(listener);
}
}
// Otherwise...
else if (
item.sticky || // never hide sticky notifications
notificationList.hasFocus() || // never hide notifications with focus
isMouseOverToast // never hide notifications under mouse
) {
hideAfterTimeout();
} else {
this.removeToast(item);
}
}, NotificationsToasts.PURGE_TIMEOUT[item.severity]);
};
hideAfterTimeout();
disposables.add(toDisposable(() => clearTimeout(purgeTimeoutHandle)));
}
private removeToast(item: INotificationViewItem): void {
const notificationToast = this.mapNotificationToToast.get(item);
let focusGroup = false;
if (notificationToast) {
const toastHasDOMFocus = isAncestor(document.activeElement, notificationToast.container);
if (toastHasDOMFocus) {
focusGroup = !(this.focusNext() || this.focusPrevious()); // focus next if any, otherwise focus editor
}
// Listeners
dispose(notificationToast.toDispose);
// Remove from Map
this.mapNotificationToToast.delete(item);
}
// Layout if we still have toasts
if (this.mapNotificationToToast.size > 0) {
this.layout(this.workbenchDimensions);
}
// Otherwise hide if no more toasts to show
else {
this.doHide();
// Move focus back to editor group as needed
if (focusGroup) {
this.editorGroupService.activeGroup.focus();
}
}
}
private removeToasts(): void {
this.mapNotificationToToast.forEach(toast => dispose(toast.toDispose));
this.mapNotificationToToast.clear();
this.doHide();
}
private doHide(): void {
if (this.notificationsToastsContainer) {
removeClass(this.notificationsToastsContainer, 'visible');
}
// Context Key
this.notificationsToastsVisibleContextKey.set(false);
}
hide(): void {
const focusGroup = isAncestor(document.activeElement, this.notificationsToastsContainer);
this.removeToasts();
if (focusGroup) {
this.editorGroupService.activeGroup.focus();
}
}
focus(): boolean {
const toasts = this.getToasts(ToastVisibility.VISIBLE);
if (toasts.length > 0) {
toasts[0].list.focusFirst();
return true;
}
return false;
}
focusNext(): boolean {
const toasts = this.getToasts(ToastVisibility.VISIBLE);
for (let i = 0; i < toasts.length; i++) {
const toast = toasts[i];
if (toast.list.hasFocus()) {
const nextToast = toasts[i + 1];
if (nextToast) {
nextToast.list.focusFirst();
return true;
}
break;
}
}
return false;
}
focusPrevious(): boolean {
const toasts = this.getToasts(ToastVisibility.VISIBLE);
for (let i = 0; i < toasts.length; i++) {
const toast = toasts[i];
if (toast.list.hasFocus()) {
const previousToast = toasts[i - 1];
if (previousToast) {
previousToast.list.focusFirst();
return true;
}
break;
}
}
return false;
}
focusFirst(): boolean {
const toast = this.getToasts(ToastVisibility.VISIBLE)[0];
if (toast) {
toast.list.focusFirst();
return true;
}
return false;
}
focusLast(): boolean {
const toasts = this.getToasts(ToastVisibility.VISIBLE);
if (toasts.length > 0) {
toasts[toasts.length - 1].list.focusFirst();
return true;
}
return false;
}
update(isCenterVisible: boolean): void {
if (this.isNotificationsCenterVisible !== isCenterVisible) {
this.isNotificationsCenterVisible = isCenterVisible;
// Hide all toasts when the notificationcenter gets visible
if (this.isNotificationsCenterVisible) {
this.removeToasts();
}
}
}
protected updateStyles(): void {
this.mapNotificationToToast.forEach(t => {
const widgetShadowColor = this.getColor(widgetShadow);
t.toast.style.boxShadow = widgetShadowColor ? `0 0px 8px ${widgetShadowColor}` : null;
const borderColor = this.getColor(NOTIFICATIONS_TOAST_BORDER);
t.toast.style.border = borderColor ? `1px solid ${borderColor}` : null;
});
}
private getToasts(state: ToastVisibility): INotificationToast[] {
const notificationToasts: INotificationToast[] = [];
this.mapNotificationToToast.forEach(toast => {
switch (state) {
case ToastVisibility.HIDDEN_OR_VISIBLE:
notificationToasts.push(toast);
break;
case ToastVisibility.HIDDEN:
if (!this.isVisible(toast)) {
notificationToasts.push(toast);
}
break;
case ToastVisibility.VISIBLE:
if (this.isVisible(toast)) {
notificationToasts.push(toast);
}
break;
}
});
return notificationToasts.reverse(); // from newest to oldest
}
layout(dimension: Dimension): void {
this.workbenchDimensions = dimension;
const maxDimensions = this.computeMaxDimensions();
// Hide toasts that exceed height
if (maxDimensions.height) {
this.layoutContainer(maxDimensions.height);
}
// Layout all lists of toasts
this.layoutLists(maxDimensions.width);
}
private computeMaxDimensions(): Dimension {
let maxWidth = NotificationsToasts.MAX_WIDTH;
let availableWidth = maxWidth;
let availableHeight: number | undefined;
if (this.workbenchDimensions) {
// Make sure notifications are not exceding available width
availableWidth = this.workbenchDimensions.width;
availableWidth -= (2 * 8); // adjust for paddings left and right
// Make sure notifications are not exceeding available height
availableHeight = this.workbenchDimensions.height;
if (this.layoutService.isVisible(Parts.STATUSBAR_PART)) {
availableHeight -= 22; // adjust for status bar
}
if (this.layoutService.isVisible(Parts.TITLEBAR_PART)) {
availableHeight -= 22; // adjust for title bar
}
availableHeight -= (2 * 12); // adjust for paddings top and bottom
}
availableHeight = typeof availableHeight === 'number'
? Math.round(availableHeight * 0.618) // try to not cover the full height for stacked toasts
: 0;
return new Dimension(Math.min(maxWidth, availableWidth), availableHeight);
}
private layoutLists(width: number): void {
this.mapNotificationToToast.forEach(toast => toast.list.layout(width));
}
private layoutContainer(heightToGive: number): void {
let visibleToasts = 0;
this.getToasts(ToastVisibility.HIDDEN_OR_VISIBLE).forEach(toast => {
// In order to measure the client height, the element cannot have display: none
toast.container.style.opacity = '0';
this.setVisibility(toast, true);
heightToGive -= toast.container.offsetHeight;
let makeVisible = false;
if (visibleToasts === NotificationsToasts.MAX_NOTIFICATIONS) {
makeVisible = false; // never show more than MAX_NOTIFICATIONS
} else if (heightToGive >= 0) {
makeVisible = true; // hide toast if available height is too little
}
// Hide or show toast based on context
this.setVisibility(toast, makeVisible);
toast.container.style.opacity = null;
if (makeVisible) {
visibleToasts++;
}
});
}
private setVisibility(toast: INotificationToast, visible: boolean): void {
if (this.isVisible(toast) === visible) {
return;
}
if (visible) {
this.notificationsToastsContainer.appendChild(toast.container);
} else {
this.notificationsToastsContainer.removeChild(toast.container);
}
}
private isVisible(toast: INotificationToast): boolean {
return !!toast.container.parentElement;
}
}
| src/vs/workbench/browser/parts/notifications/notificationsToasts.ts | 0 | https://github.com/microsoft/vscode/commit/985de26b3446636f86e2bb2b14dbeb9ec1e33207 | [
0.00017592932272236794,
0.00017290006508119404,
0.0001670188212301582,
0.0001734075922286138,
0.000002007713192142546
] |
{
"id": 5,
"code_window": [
"\t}\n",
"\n",
"\tprivate getOptions(options: ISaveDialogOptions | IOpenDialogOptions, isSave: boolean = false): IOpenDialogOptions | undefined {\n",
"\t\tlet defaultUri = options.defaultUri;\n",
"\t\tconst filename = (defaultUri && isSave && (resources.dirname(defaultUri).path === '/')) ? resources.basename(defaultUri) : undefined;\n",
"\t\tif (!defaultUri || filename) {\n",
"\t\t\tdefaultUri = this.userHome;\n",
"\t\t\tif (filename) {\n",
"\t\t\t\tdefaultUri = resources.joinPath(defaultUri, filename);\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\tlet defaultUri: URI | undefined = undefined;\n",
"\t\tlet filename: string | undefined = undefined;\n",
"\t\tif (options.defaultUri) {\n",
"\t\t\tdefaultUri = (this.scheme === options.defaultUri.scheme) ? options.defaultUri : undefined;\n",
"\t\t\tfilename = isSave ? resources.basename(options.defaultUri) : undefined;\n",
"\t\t}\n",
"\t\tif (!defaultUri) {\n"
],
"file_path": "src/vs/workbench/services/dialogs/browser/remoteFileDialog.ts",
"type": "replace",
"edit_start_line_idx": 130
} | /*---------------------------------------------------------------------------------------------
* 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/search/browser/search.contribution'; // load contributions
import * as assert from 'assert';
import * as fs from 'fs';
import { IWorkspaceContextService } from 'vs/platform/workspace/common/workspace';
import { createSyncDescriptor } from 'vs/platform/instantiation/common/descriptors';
import { IEditorGroupsService } from 'vs/workbench/services/editor/common/editorGroupsService';
import { ISearchService } from 'vs/workbench/services/search/common/search';
import { ITelemetryService, ITelemetryInfo } from 'vs/platform/telemetry/common/telemetry';
import { IUntitledEditorService, UntitledEditorService } from 'vs/workbench/services/untitled/common/untitledEditorService';
import { IEditorService } from 'vs/workbench/services/editor/common/editorService';
import * as minimist from 'minimist';
import * as path from 'vs/base/common/path';
import { LocalSearchService } from 'vs/workbench/services/search/node/searchService';
import { ServiceCollection } from 'vs/platform/instantiation/common/serviceCollection';
import { TestEnvironmentService, TestContextService, TestEditorService, TestEditorGroupsService, TestTextResourcePropertiesService } from 'vs/workbench/test/workbenchTestServices';
import { IEnvironmentService } from 'vs/platform/environment/common/environment';
import { URI } from 'vs/base/common/uri';
import { InstantiationService } from 'vs/platform/instantiation/common/instantiationService';
import { TestConfigurationService } from 'vs/platform/configuration/test/common/testConfigurationService';
import { IConfigurationService } from 'vs/platform/configuration/common/configuration';
import { ModelServiceImpl } from 'vs/editor/common/services/modelServiceImpl';
import { IModelService } from 'vs/editor/common/services/modelService';
import { SearchModel } from 'vs/workbench/contrib/search/common/searchModel';
import { QueryBuilder, ITextQueryBuilderOptions } from 'vs/workbench/contrib/search/common/queryBuilder';
import { Event, Emitter } from 'vs/base/common/event';
import { testWorkspace } from 'vs/platform/workspace/test/common/testWorkspace';
import { NullLogService, ILogService } from 'vs/platform/log/common/log';
import { ITextResourcePropertiesService } from 'vs/editor/common/services/resourceConfiguration';
declare var __dirname: string;
// Checkout sources to run against:
// git clone --separate-git-dir=testGit --no-checkout --single-branch https://chromium.googlesource.com/chromium/src testWorkspace
// cd testWorkspace; git checkout 39a7f93d67f7
// Run from repository root folder with (test.bat on Windows): ./scripts/test-int-mocha.sh --grep TextSearch.performance --timeout 500000 --testWorkspace <path>
suite.skip('TextSearch performance (integration)', () => {
test('Measure', () => {
if (process.env['VSCODE_PID']) {
return undefined; // TODO@Rob find out why test fails when run from within VS Code
}
const n = 3;
const argv = minimist(process.argv);
const testWorkspaceArg = argv['testWorkspace'];
const testWorkspacePath = testWorkspaceArg ? path.resolve(testWorkspaceArg) : __dirname;
if (!fs.existsSync(testWorkspacePath)) {
throw new Error(`--testWorkspace doesn't exist`);
}
const telemetryService = new TestTelemetryService();
const configurationService = new TestConfigurationService();
const textResourcePropertiesService = new TestTextResourcePropertiesService(configurationService);
const instantiationService = new InstantiationService(new ServiceCollection(
[ITelemetryService, telemetryService],
[IConfigurationService, configurationService],
[ITextResourcePropertiesService, textResourcePropertiesService],
[IModelService, new ModelServiceImpl(configurationService, textResourcePropertiesService)],
[IWorkspaceContextService, new TestContextService(testWorkspace(URI.file(testWorkspacePath)))],
[IEditorService, new TestEditorService()],
[IEditorGroupsService, new TestEditorGroupsService()],
[IEnvironmentService, TestEnvironmentService],
[IUntitledEditorService, createSyncDescriptor(UntitledEditorService)],
[ISearchService, createSyncDescriptor(LocalSearchService)],
[ILogService, new NullLogService()]
));
const queryOptions: ITextQueryBuilderOptions = {
maxResults: 2048
};
const searchModel: SearchModel = instantiationService.createInstance(SearchModel);
function runSearch(): Promise<any> {
const queryBuilder: QueryBuilder = instantiationService.createInstance(QueryBuilder);
const query = queryBuilder.text({ pattern: 'static_library(' }, [URI.file(testWorkspacePath)], queryOptions);
// Wait for the 'searchResultsFinished' event, which is fired after the search() promise is resolved
const onSearchResultsFinished = Event.filter(telemetryService.eventLogged, e => e.name === 'searchResultsFinished');
Event.once(onSearchResultsFinished)(onComplete);
function onComplete(): void {
try {
const allEvents = telemetryService.events.map(e => JSON.stringify(e)).join('\n');
assert.equal(telemetryService.events.length, 3, 'Expected 3 telemetry events, got:\n' + allEvents);
const [firstRenderEvent, resultsShownEvent, resultsFinishedEvent] = telemetryService.events;
assert.equal(firstRenderEvent.name, 'searchResultsFirstRender');
assert.equal(resultsShownEvent.name, 'searchResultsShown');
assert.equal(resultsFinishedEvent.name, 'searchResultsFinished');
telemetryService.events = [];
resolve!(resultsFinishedEvent);
} catch (e) {
// Fail the runSearch() promise
error!(e);
}
}
let resolve: (result: any) => void;
let error: (error: Error) => void;
return new Promise((_resolve, _error) => {
resolve = _resolve;
error = _error;
// Don't wait on this promise, we're waiting on the event fired above
searchModel.search(query).then(
null,
_error);
});
}
const finishedEvents: any[] = [];
return runSearch() // Warm-up first
.then(() => {
if (testWorkspaceArg) { // Don't measure by default
let i = n;
return (function iterate(): Promise<undefined> | undefined {
if (!i--) {
return;
}
return runSearch()
.then((resultsFinishedEvent: any) => {
console.log(`Iteration ${n - i}: ${resultsFinishedEvent.data.duration / 1000}s`);
finishedEvents.push(resultsFinishedEvent);
return iterate();
});
})()!.then(() => {
const totalTime = finishedEvents.reduce((sum, e) => sum + e.data.duration, 0);
console.log(`Avg duration: ${totalTime / n / 1000}s`);
});
}
return undefined;
});
});
});
class TestTelemetryService implements ITelemetryService {
public _serviceBrand: any;
public isOptedIn = true;
public events: any[] = [];
private emitter = new Emitter<any>();
public get eventLogged(): Event<any> {
return this.emitter.event;
}
public setEnabled(value: boolean): void {
}
public publicLog(eventName: string, data?: any): Promise<void> {
const event = { name: eventName, data: data };
this.events.push(event);
this.emitter.fire(event);
return Promise.resolve();
}
public getTelemetryInfo(): Promise<ITelemetryInfo> {
return Promise.resolve({
instanceId: 'someValue.instanceId',
sessionId: 'someValue.sessionId',
machineId: 'someValue.machineId'
});
}
}
| src/vs/workbench/test/electron-browser/textsearch.perf.integrationTest.ts | 0 | https://github.com/microsoft/vscode/commit/985de26b3446636f86e2bb2b14dbeb9ec1e33207 | [
0.0001841964985942468,
0.00017310588737018406,
0.00016812820103950799,
0.00017294065037276596,
0.0000034753713862301083
] |
{
"id": 6,
"code_window": [
"\t\tpath = path.replace(/\\\\/g, '/');\n",
"\t\treturn resources.toLocalResource(URI.from({ scheme: this.scheme, path }), this.scheme === Schemas.file ? undefined : this.remoteAuthority);\n",
"\t}\n",
"\n",
"\tprivate getScheme(defaultUri: URI | undefined, available: string[] | undefined): string {\n",
"\t\treturn defaultUri ? defaultUri.scheme : (available ? available[0] : Schemas.file);\n",
"\t}\n",
"\n",
"\tprivate async getRemoteAgentEnvironment(): Promise<IRemoteAgentEnvironment | null> {\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
"\tprivate getScheme(available: string[] | undefined): string {\n",
"\t\treturn available ? available[0] : Schemas.file;\n"
],
"file_path": "src/vs/workbench/services/dialogs/browser/remoteFileDialog.ts",
"type": "replace",
"edit_start_line_idx": 152
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import { Action } from 'vs/base/common/actions';
import * as nls from 'vs/nls';
import { IWindowService } from 'vs/platform/windows/common/windows';
import { ITelemetryData } from 'vs/platform/telemetry/common/telemetry';
import { IWorkspaceContextService, WorkbenchState, IWorkspaceFolder } from 'vs/platform/workspace/common/workspace';
import { IWorkspaceEditingService } from 'vs/workbench/services/workspace/common/workspaceEditing';
import { IWorkspacesService } from 'vs/platform/workspaces/common/workspaces';
import { IEditorService } from 'vs/workbench/services/editor/common/editorService';
import { ICommandService } from 'vs/platform/commands/common/commands';
import { ADD_ROOT_FOLDER_COMMAND_ID, ADD_ROOT_FOLDER_LABEL, PICK_WORKSPACE_FOLDER_COMMAND_ID } from 'vs/workbench/browser/actions/workspaceCommands';
import { IFileDialogService } from 'vs/platform/dialogs/common/dialogs';
import { INotificationService } from 'vs/platform/notification/common/notification';
import { Schemas } from 'vs/base/common/network';
import { IWorkbenchEnvironmentService } from 'vs/workbench/services/environment/common/environmentService';
export class OpenFileAction extends Action {
static readonly ID = 'workbench.action.files.openFile';
static LABEL = nls.localize('openFile', "Open File...");
constructor(
id: string,
label: string,
@IFileDialogService private readonly dialogService: IFileDialogService
) {
super(id, label);
}
run(event?: any, data?: ITelemetryData): Promise<any> {
return this.dialogService.pickFileAndOpen({ forceNewWindow: false, telemetryExtraData: data });
}
}
export class OpenLocalFileAction extends Action {
static readonly ID = 'workbench.action.files.openLocalFile';
static LABEL = nls.localize('openLocalFile', "Open Local File...");
constructor(
id: string,
label: string,
@IFileDialogService private readonly dialogService: IFileDialogService
) {
super(id, label);
}
run(event?: any, data?: ITelemetryData): Promise<any> {
return this.dialogService.pickFileAndOpen({ forceNewWindow: false, telemetryExtraData: data, availableFileSystems: [Schemas.file] });
}
}
export class SaveLocalFileAction extends Action {
static readonly ID = 'workbench.action.files.saveLocalFile';
static LABEL = nls.localize('saveLocalFile', "Save Local File...");
constructor(
id: string,
label: string,
@IFileDialogService private readonly dialogService: IFileDialogService
) {
super(id, label);
}
run(event?: any, data?: ITelemetryData): Promise<any> {
return this.dialogService.pickFileToSave({ availableFileSystems: [Schemas.file] });
}
}
export class OpenFolderAction extends Action {
static readonly ID = 'workbench.action.files.openFolder';
static LABEL = nls.localize('openFolder', "Open Folder...");
constructor(
id: string,
label: string,
@IFileDialogService private readonly dialogService: IFileDialogService
) {
super(id, label);
}
run(event?: any, data?: ITelemetryData): Promise<any> {
return this.dialogService.pickFolderAndOpen({ forceNewWindow: false, telemetryExtraData: data });
}
}
export class OpenLocalFolderAction extends Action {
static readonly ID = 'workbench.action.files.openLocalFolder';
static LABEL = nls.localize('openLocalFolder', "Open Local Folder...");
constructor(
id: string,
label: string,
@IFileDialogService private readonly dialogService: IFileDialogService
) {
super(id, label);
}
run(event?: any, data?: ITelemetryData): Promise<any> {
return this.dialogService.pickFolderAndOpen({ forceNewWindow: false, telemetryExtraData: data, availableFileSystems: [Schemas.file] });
}
}
export class OpenFileFolderAction extends Action {
static readonly ID = 'workbench.action.files.openFileFolder';
static LABEL = nls.localize('openFileFolder', "Open...");
constructor(
id: string,
label: string,
@IFileDialogService private readonly dialogService: IFileDialogService
) {
super(id, label);
}
run(event?: any, data?: ITelemetryData): Promise<any> {
return this.dialogService.pickFileFolderAndOpen({ forceNewWindow: false, telemetryExtraData: data });
}
}
export class OpenLocalFileFolderAction extends Action {
static readonly ID = 'workbench.action.files.openLocalFileFolder';
static LABEL = nls.localize('openLocalFileFolder', "Open Local...");
constructor(
id: string,
label: string,
@IFileDialogService private readonly dialogService: IFileDialogService
) {
super(id, label);
}
run(event?: any, data?: ITelemetryData): Promise<any> {
return this.dialogService.pickFileFolderAndOpen({ forceNewWindow: false, telemetryExtraData: data, availableFileSystems: [Schemas.file] });
}
}
export class AddRootFolderAction extends Action {
static readonly ID = 'workbench.action.addRootFolder';
static LABEL = ADD_ROOT_FOLDER_LABEL;
constructor(
id: string,
label: string,
@ICommandService private readonly commandService: ICommandService
) {
super(id, label);
}
run(): Promise<any> {
return this.commandService.executeCommand(ADD_ROOT_FOLDER_COMMAND_ID);
}
}
export class GlobalRemoveRootFolderAction extends Action {
static readonly ID = 'workbench.action.removeRootFolder';
static LABEL = nls.localize('globalRemoveFolderFromWorkspace', "Remove Folder from Workspace...");
constructor(
id: string,
label: string,
@IWorkspaceEditingService private readonly workspaceEditingService: IWorkspaceEditingService,
@IWorkspaceContextService private readonly contextService: IWorkspaceContextService,
@ICommandService private readonly commandService: ICommandService
) {
super(id, label);
}
async run(): Promise<any> {
const state = this.contextService.getWorkbenchState();
// Workspace / Folder
if (state === WorkbenchState.WORKSPACE || state === WorkbenchState.FOLDER) {
const folder = await this.commandService.executeCommand<IWorkspaceFolder>(PICK_WORKSPACE_FOLDER_COMMAND_ID);
if (folder) {
await this.workspaceEditingService.removeFolders([folder.uri]);
}
}
return true;
}
}
export class SaveWorkspaceAsAction extends Action {
static readonly ID = 'workbench.action.saveWorkspaceAs';
static LABEL = nls.localize('saveWorkspaceAsAction', "Save Workspace As...");
constructor(
id: string,
label: string,
@IWorkspaceContextService private readonly contextService: IWorkspaceContextService,
@IWorkspaceEditingService private readonly workspaceEditingService: IWorkspaceEditingService
) {
super(id, label);
}
async run(): Promise<any> {
const configPathUri = await this.workspaceEditingService.pickNewWorkspacePath();
if (configPathUri) {
switch (this.contextService.getWorkbenchState()) {
case WorkbenchState.EMPTY:
case WorkbenchState.FOLDER:
const folders = this.contextService.getWorkspace().folders.map(folder => ({ uri: folder.uri }));
return this.workspaceEditingService.createAndEnterWorkspace(folders, configPathUri);
case WorkbenchState.WORKSPACE:
return this.workspaceEditingService.saveAndEnterWorkspace(configPathUri);
}
}
}
}
export class OpenWorkspaceAction extends Action {
static readonly ID = 'workbench.action.openWorkspace';
static LABEL = nls.localize('openWorkspaceAction', "Open Workspace...");
constructor(
id: string,
label: string,
@IFileDialogService private readonly dialogService: IFileDialogService
) {
super(id, label);
}
run(event?: any, data?: ITelemetryData): Promise<any> {
return this.dialogService.pickWorkspaceAndOpen({ telemetryExtraData: data });
}
}
export class CloseWorkspaceAction extends Action {
static readonly ID = 'workbench.action.closeFolder';
static LABEL = nls.localize('closeWorkspace', "Close Workspace");
constructor(
id: string,
label: string,
@IWorkspaceContextService private readonly contextService: IWorkspaceContextService,
@INotificationService private readonly notificationService: INotificationService,
@IWindowService private readonly windowService: IWindowService
) {
super(id, label);
}
run(): Promise<void> {
if (this.contextService.getWorkbenchState() === WorkbenchState.EMPTY) {
this.notificationService.info(nls.localize('noWorkspaceOpened', "There is currently no workspace opened in this instance to close."));
return Promise.resolve(undefined);
}
return this.windowService.closeWorkspace();
}
}
export class OpenWorkspaceConfigFileAction extends Action {
static readonly ID = 'workbench.action.openWorkspaceConfigFile';
static readonly LABEL = nls.localize('openWorkspaceConfigFile', "Open Workspace Configuration File");
constructor(
id: string,
label: string,
@IWorkspaceContextService private readonly workspaceContextService: IWorkspaceContextService,
@IEditorService private readonly editorService: IEditorService
) {
super(id, label);
this.enabled = !!this.workspaceContextService.getWorkspace().configuration;
}
run(): Promise<any> {
const configuration = this.workspaceContextService.getWorkspace().configuration;
if (configuration) {
return this.editorService.openEditor({ resource: configuration });
}
return Promise.resolve();
}
}
export class DuplicateWorkspaceInNewWindowAction extends Action {
static readonly ID = 'workbench.action.duplicateWorkspaceInNewWindow';
static readonly LABEL = nls.localize('duplicateWorkspaceInNewWindow', "Duplicate Workspace in New Window");
constructor(
id: string,
label: string,
@IWorkspaceContextService private readonly workspaceContextService: IWorkspaceContextService,
@IWorkspaceEditingService private readonly workspaceEditingService: IWorkspaceEditingService,
@IWindowService private readonly windowService: IWindowService,
@IWorkspacesService private readonly workspacesService: IWorkspacesService,
@IWorkbenchEnvironmentService private readonly environmentService: IWorkbenchEnvironmentService
) {
super(id, label);
}
async run(): Promise<any> {
const folders = this.workspaceContextService.getWorkspace().folders;
const remoteAuthority = this.environmentService.configuration.remoteAuthority;
const newWorkspace = await this.workspacesService.createUntitledWorkspace(folders, remoteAuthority);
await this.workspaceEditingService.copyWorkspaceSettings(newWorkspace);
return this.windowService.openWindow([{ workspaceUri: newWorkspace.configPath }], { forceNewWindow: true });
}
}
| src/vs/workbench/browser/actions/workspaceActions.ts | 1 | https://github.com/microsoft/vscode/commit/985de26b3446636f86e2bb2b14dbeb9ec1e33207 | [
0.0018045934848487377,
0.00022214013733901083,
0.0001625882723601535,
0.00017161374853458256,
0.00027987410430796444
] |
{
"id": 6,
"code_window": [
"\t\tpath = path.replace(/\\\\/g, '/');\n",
"\t\treturn resources.toLocalResource(URI.from({ scheme: this.scheme, path }), this.scheme === Schemas.file ? undefined : this.remoteAuthority);\n",
"\t}\n",
"\n",
"\tprivate getScheme(defaultUri: URI | undefined, available: string[] | undefined): string {\n",
"\t\treturn defaultUri ? defaultUri.scheme : (available ? available[0] : Schemas.file);\n",
"\t}\n",
"\n",
"\tprivate async getRemoteAgentEnvironment(): Promise<IRemoteAgentEnvironment | null> {\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
"\tprivate getScheme(available: string[] | undefined): string {\n",
"\t\treturn available ? available[0] : Schemas.file;\n"
],
"file_path": "src/vs/workbench/services/dialogs/browser/remoteFileDialog.ts",
"type": "replace",
"edit_start_line_idx": 152
} | // A launch configuration that compiles the extension and then opens it inside a new window
// Use IntelliSense to learn about possible attributes.
// Hover to view descriptions of existing attributes.
// For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
{
"version": "0.2.0",
"configurations": [
{
"name": "Extension",
"type": "extensionHost",
"request": "launch",
"runtimeExecutable": "${execPath}",
"args": [
"--extensionDevelopmentPath=${workspaceFolder}",
"--remote=test+test"
],
"outFiles": [
"${workspaceFolder}/out/**/*.js"
]
}
]
} | extensions/vscode-test-resolver/.vscode/launch.json | 0 | https://github.com/microsoft/vscode/commit/985de26b3446636f86e2bb2b14dbeb9ec1e33207 | [
0.00017547362949699163,
0.00017515102808829397,
0.00017467436555307359,
0.00017530506011098623,
3.439984084252501e-7
] |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.