hunk
dict | file
stringlengths 0
11.8M
| file_path
stringlengths 2
234
| label
int64 0
1
| commit_url
stringlengths 74
103
| dependency_score
sequencelengths 5
5
|
---|---|---|---|---|---|
{
"id": 2,
"code_window": [
" // Receive render events\n",
" scope.$on('render',function(event, renderData) {\n",
" data = renderData || data;\n",
" annotations = data.annotations;\n",
" render_panel();\n",
" });\n",
"\n",
" // Re-render if the window is resized\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" annotations = data.annotations || annotations;\n"
],
"file_path": "src/app/directives/grafanaGraph.js",
"type": "replace",
"edit_start_line_idx": 41
} | /**
* AngularStrap - Twitter Bootstrap directives for AngularJS
* @version v0.7.5 - 2013-07-21
* @link http://mgcrea.github.com/angular-strap
* @author Olivier Louvignes <[email protected]>
* @license MIT License, http://www.opensource.org/licenses/MIT
*/
angular.module('$strap.config', []).value('$strapConfig', {});
angular.module('$strap.filters', ['$strap.config']);
angular.module('$strap.directives', ['$strap.config']);
angular.module('$strap', [
'$strap.filters',
'$strap.directives',
'$strap.config'
]);
'use strict';
angular.module('$strap.directives').directive('bsAlert', [
'$parse',
'$timeout',
'$compile',
function ($parse, $timeout, $compile) {
return {
restrict: 'A',
link: function postLink(scope, element, attrs) {
var getter = $parse(attrs.bsAlert), setter = getter.assign, value = getter(scope);
var closeAlert = function closeAlertFn(delay) {
$timeout(function () {
element.alert('close');
}, delay * 1);
};
if (!attrs.bsAlert) {
if (angular.isUndefined(attrs.closeButton) || attrs.closeButton !== '0' && attrs.closeButton !== 'false') {
element.prepend('<button type="button" class="close" data-dismiss="alert">×</button>');
}
if (attrs.closeAfter)
closeAlert(attrs.closeAfter);
} else {
scope.$watch(attrs.bsAlert, function (newValue, oldValue) {
value = newValue;
element.html((newValue.title ? '<strong>' + newValue.title + '</strong> ' : '') + newValue.content || '');
if (!!newValue.closed) {
element.hide();
}
$compile(element.contents())(scope);
if (newValue.type || oldValue.type) {
oldValue.type && element.removeClass('alert-' + oldValue.type);
newValue.type && element.addClass('alert-' + newValue.type);
}
if (angular.isDefined(newValue.closeAfter))
closeAlert(newValue.closeAfter);
else if (attrs.closeAfter)
closeAlert(attrs.closeAfter);
if (angular.isUndefined(attrs.closeButton) || attrs.closeButton !== '0' && attrs.closeButton !== 'false') {
element.prepend('<button type="button" class="close" data-dismiss="alert">×</button>');
}
}, true);
}
element.addClass('alert').alert();
if (element.hasClass('fade')) {
element.removeClass('in');
setTimeout(function () {
element.addClass('in');
});
}
var parentArray = attrs.ngRepeat && attrs.ngRepeat.split(' in ').pop();
element.on('close', function (ev) {
var removeElement;
if (parentArray) {
ev.preventDefault();
element.removeClass('in');
removeElement = function () {
element.trigger('closed');
if (scope.$parent) {
scope.$parent.$apply(function () {
var path = parentArray.split('.');
var curr = scope.$parent;
for (var i = 0; i < path.length; ++i) {
if (curr) {
curr = curr[path[i]];
}
}
if (curr) {
curr.splice(scope.$index, 1);
}
});
}
};
$.support.transition && element.hasClass('fade') ? element.on($.support.transition.end, removeElement) : removeElement();
} else if (value) {
ev.preventDefault();
element.removeClass('in');
removeElement = function () {
element.trigger('closed');
scope.$apply(function () {
value.closed = true;
});
};
$.support.transition && element.hasClass('fade') ? element.on($.support.transition.end, removeElement) : removeElement();
} else {
}
});
}
};
}
]);
'use strict';
angular.module('$strap.directives').directive('bsButton', [
'$parse',
'$timeout',
function ($parse, $timeout) {
return {
restrict: 'A',
require: '?ngModel',
link: function postLink(scope, element, attrs, controller) {
if (controller) {
if (!element.parent('[data-toggle="buttons-checkbox"], [data-toggle="buttons-radio"]').length) {
element.attr('data-toggle', 'button');
}
var startValue = !!scope.$eval(attrs.ngModel);
if (startValue) {
element.addClass('active');
}
scope.$watch(attrs.ngModel, function (newValue, oldValue) {
var bNew = !!newValue, bOld = !!oldValue;
if (bNew !== bOld) {
$.fn.button.Constructor.prototype.toggle.call(button);
} else if (bNew && !startValue) {
element.addClass('active');
}
});
}
if (!element.hasClass('btn')) {
element.on('click.button.data-api', function (ev) {
element.button('toggle');
});
}
element.button();
var button = element.data('button');
button.toggle = function () {
if (!controller) {
return $.fn.button.Constructor.prototype.toggle.call(this);
}
var $parent = element.parent('[data-toggle="buttons-radio"]');
if ($parent.length) {
element.siblings('[ng-model]').each(function (k, v) {
$parse($(v).attr('ng-model')).assign(scope, false);
});
scope.$digest();
if (!controller.$modelValue) {
controller.$setViewValue(!controller.$modelValue);
scope.$digest();
}
} else {
scope.$apply(function () {
controller.$setViewValue(!controller.$modelValue);
});
}
};
}
};
}
]).directive('bsButtonsCheckbox', [
'$parse',
function ($parse) {
return {
restrict: 'A',
require: '?ngModel',
compile: function compile(tElement, tAttrs, transclude) {
tElement.attr('data-toggle', 'buttons-checkbox').find('a, button').each(function (k, v) {
$(v).attr('bs-button', '');
});
}
};
}
]).directive('bsButtonsRadio', [
'$timeout',
function ($timeout) {
return {
restrict: 'A',
require: '?ngModel',
compile: function compile(tElement, tAttrs, transclude) {
tElement.attr('data-toggle', 'buttons-radio');
if (!tAttrs.ngModel) {
tElement.find('a, button').each(function (k, v) {
$(v).attr('bs-button', '');
});
}
return function postLink(scope, iElement, iAttrs, controller) {
if (controller) {
$timeout(function () {
iElement.find('[value]').button().filter('[value="' + controller.$viewValue + '"]').addClass('active');
});
iElement.on('click.button.data-api', function (ev) {
scope.$apply(function () {
controller.$setViewValue($(ev.target).closest('button').attr('value'));
});
});
scope.$watch(iAttrs.ngModel, function (newValue, oldValue) {
if (newValue !== oldValue) {
var $btn = iElement.find('[value="' + scope.$eval(iAttrs.ngModel) + '"]');
if ($btn.length) {
$btn.button('toggle');
}
}
});
}
};
}
};
}
]);
'use strict';
angular.module('$strap.directives').directive('bsButtonSelect', [
'$parse',
'$timeout',
function ($parse, $timeout) {
return {
restrict: 'A',
require: '?ngModel',
link: function postLink(scope, element, attrs, ctrl) {
var getter = $parse(attrs.bsButtonSelect), setter = getter.assign;
if (ctrl) {
element.text(scope.$eval(attrs.ngModel));
scope.$watch(attrs.ngModel, function (newValue, oldValue) {
element.text(newValue);
});
}
var values, value, index, newValue;
element.bind('click', function (ev) {
values = getter(scope);
value = ctrl ? scope.$eval(attrs.ngModel) : element.text();
index = values.indexOf(value);
newValue = index > values.length - 2 ? values[0] : values[index + 1];
scope.$apply(function () {
element.text(newValue);
if (ctrl) {
ctrl.$setViewValue(newValue);
}
});
});
}
};
}
]);
'use strict';
angular.module('$strap.directives').directive('bsDatepicker', [
'$timeout',
'$strapConfig',
function ($timeout, $strapConfig) {
var isAppleTouch = /(iP(a|o)d|iPhone)/g.test(navigator.userAgent);
var regexpMap = function regexpMap(language) {
language = language || 'en';
return {
'/': '[\\/]',
'-': '[-]',
'.': '[.]',
' ': '[\\s]',
'dd': '(?:(?:[0-2]?[0-9]{1})|(?:[3][01]{1}))',
'd': '(?:(?:[0-2]?[0-9]{1})|(?:[3][01]{1}))',
'mm': '(?:[0]?[1-9]|[1][012])',
'm': '(?:[0]?[1-9]|[1][012])',
'DD': '(?:' + $.fn.datepicker.dates[language].days.join('|') + ')',
'D': '(?:' + $.fn.datepicker.dates[language].daysShort.join('|') + ')',
'MM': '(?:' + $.fn.datepicker.dates[language].months.join('|') + ')',
'M': '(?:' + $.fn.datepicker.dates[language].monthsShort.join('|') + ')',
'yyyy': '(?:(?:[1]{1}[0-9]{1}[0-9]{1}[0-9]{1})|(?:[2]{1}[0-9]{3}))(?![[0-9]])',
'yy': '(?:(?:[0-9]{1}[0-9]{1}))(?![[0-9]])'
};
};
var regexpForDateFormat = function regexpForDateFormat(format, language) {
var re = format, map = regexpMap(language), i;
i = 0;
angular.forEach(map, function (v, k) {
re = re.split(k).join('${' + i + '}');
i++;
});
i = 0;
angular.forEach(map, function (v, k) {
re = re.split('${' + i + '}').join(v);
i++;
});
return new RegExp('^' + re + '$', ['i']);
};
return {
restrict: 'A',
require: '?ngModel',
link: function postLink(scope, element, attrs, controller) {
var options = angular.extend({ autoclose: true }, $strapConfig.datepicker || {}), type = attrs.dateType || options.type || 'date';
angular.forEach([
'format',
'weekStart',
'calendarWeeks',
'startDate',
'endDate',
'daysOfWeekDisabled',
'autoclose',
'startView',
'minViewMode',
'todayBtn',
'todayHighlight',
'keyboardNavigation',
'language',
'forceParse'
], function (key) {
if (angular.isDefined(attrs[key]))
options[key] = attrs[key];
});
var language = options.language || 'en', readFormat = attrs.dateFormat || options.format || $.fn.datepicker.dates[language] && $.fn.datepicker.dates[language].format || 'mm/dd/yyyy', format = isAppleTouch ? 'yyyy-mm-dd' : readFormat, dateFormatRegexp = regexpForDateFormat(format, language);
if (controller) {
controller.$formatters.unshift(function (modelValue) {
return type === 'date' && angular.isString(modelValue) && modelValue ? $.fn.datepicker.DPGlobal.parseDate(modelValue, $.fn.datepicker.DPGlobal.parseFormat(readFormat), language) : modelValue;
});
controller.$parsers.unshift(function (viewValue) {
if (!viewValue) {
controller.$setValidity('date', true);
return null;
} else if (type === 'date' && angular.isDate(viewValue)) {
controller.$setValidity('date', true);
return viewValue;
} else if (angular.isString(viewValue) && dateFormatRegexp.test(viewValue)) {
controller.$setValidity('date', true);
if (isAppleTouch)
return new Date(viewValue);
return type === 'string' ? viewValue : $.fn.datepicker.DPGlobal.parseDate(viewValue, $.fn.datepicker.DPGlobal.parseFormat(format), language);
} else {
controller.$setValidity('date', false);
return undefined;
}
});
controller.$render = function ngModelRender() {
if (isAppleTouch) {
var date = controller.$viewValue ? $.fn.datepicker.DPGlobal.formatDate(controller.$viewValue, $.fn.datepicker.DPGlobal.parseFormat(format), language) : '';
element.val(date);
return date;
}
if (!controller.$viewValue)
element.val('');
return element.datepicker('update', controller.$viewValue);
};
}
if (isAppleTouch) {
element.prop('type', 'date').css('-webkit-appearance', 'textfield');
} else {
if (controller) {
element.on('changeDate', function (ev) {
scope.$apply(function () {
controller.$setViewValue(type === 'string' ? element.val() : ev.date);
});
});
}
element.datepicker(angular.extend(options, {
format: format,
language: language
}));
scope.$on('$destroy', function () {
var datepicker = element.data('datepicker');
if (datepicker) {
datepicker.picker.remove();
element.data('datepicker', null);
}
});
attrs.$observe('startDate', function (value) {
element.datepicker('setStartDate', value);
});
attrs.$observe('endDate', function (value) {
element.datepicker('setEndDate', value);
});
}
var component = element.siblings('[data-toggle="datepicker"]');
if (component.length) {
component.on('click', function () {
if (!element.prop('disabled')) {
element.trigger('focus');
}
});
}
}
};
}
]);
'use strict';
angular.module('$strap.directives').directive('bsDropdown', [
'$parse',
'$compile',
'$timeout',
function ($parse, $compile, $timeout) {
var buildTemplate = function (items, ul) {
if (!ul)
ul = [
'<ul class="dropdown-menu" role="menu" aria-labelledby="drop1">',
'</ul>'
];
angular.forEach(items, function (item, index) {
if (item.divider)
return ul.splice(index + 1, 0, '<li class="divider"></li>');
var li = '<li' + (item.submenu && item.submenu.length ? ' class="dropdown-submenu"' : '') + '>' + '<a tabindex="1" ng-href="' + (item.href || '') + '"' + (item.click ? '" ng-click="' + item.click + '"' : '') + (item.target ? '" target="' + item.target + '"' : '') + (item.method ? ' data-method="' + item.method + '"' : '') + '>' + (item.text || '') + '</a>';
if (item.submenu && item.submenu.length)
li += buildTemplate(item.submenu).join('\n');
li += '</li>';
ul.splice(index + 1, 0, li);
});
return ul;
};
return {
restrict: 'EA',
scope: true,
link: function postLink(scope, iElement, iAttrs) {
var getter = $parse(iAttrs.bsDropdown), items = getter(scope);
$timeout(function () {
if (!angular.isArray(items)) {
}
var dropdown = angular.element(buildTemplate(items).join(''));
dropdown.insertAfter(iElement);
$compile(iElement.next('ul.dropdown-menu'))(scope);
});
iElement.addClass('dropdown-toggle').attr('data-toggle', 'dropdown');
}
};
}
]);
'use strict';
angular.module('$strap.directives').factory('$modal', [
'$rootScope',
'$compile',
'$http',
'$timeout',
'$q',
'$templateCache',
'$strapConfig',
function ($rootScope, $compile, $http, $timeout, $q, $templateCache, $strapConfig) {
var ModalFactory = function ModalFactory(config) {
function Modal(config) {
var options = angular.extend({ show: true }, $strapConfig.modal, config), scope = options.scope ? options.scope : $rootScope.$new(), templateUrl = options.template;
return $q.when($templateCache.get(templateUrl) || $http.get(templateUrl, { cache: true }).then(function (res) {
return res.data;
})).then(function onSuccess(template) {
var id = templateUrl.replace('.html', '').replace(/[\/|\.|:]/g, '-') + '-' + scope.$id;
var $modal = $('<div class="modal hide" tabindex="-1"></div>').attr('id', id).addClass('fade').html(template);
if (options.modalClass)
$modal.addClass(options.modalClass);
$('body').append($modal);
$timeout(function () {
$compile($modal)(scope);
});
scope.$modal = function (name) {
$modal.modal(name);
};
angular.forEach([
'show',
'hide'
], function (name) {
scope[name] = function () {
$modal.modal(name);
};
});
scope.dismiss = scope.hide;
angular.forEach([
'show',
'shown',
'hide',
'hidden'
], function (name) {
$modal.on(name, function (ev) {
scope.$emit('modal-' + name, ev);
});
});
$modal.on('shown', function (ev) {
$('input[autofocus], textarea[autofocus]', $modal).first().trigger('focus');
});
$modal.on('hidden', function (ev) {
if (!options.persist)
scope.$destroy();
});
scope.$on('$destroy', function () {
$modal.remove();
});
$modal.modal(options);
return $modal;
});
}
return new Modal(config);
};
return ModalFactory;
}
]).directive('bsModal', [
'$q',
'$modal',
function ($q, $modal) {
return {
restrict: 'A',
scope: true,
link: function postLink(scope, iElement, iAttrs, controller) {
var options = {
template: scope.$eval(iAttrs.bsModal),
persist: true,
show: false,
scope: scope
};
angular.forEach([
'modalClass',
'backdrop',
'keyboard'
], function (key) {
if (angular.isDefined(iAttrs[key]))
options[key] = iAttrs[key];
});
$q.when($modal(options)).then(function onSuccess(modal) {
iElement.attr('data-target', '#' + modal.attr('id')).attr('data-toggle', 'modal');
});
}
};
}
]);
'use strict';
angular.module('$strap.directives').directive('bsNavbar', [
'$location',
function ($location) {
return {
restrict: 'A',
link: function postLink(scope, element, attrs, controller) {
scope.$watch(function () {
return $location.path();
}, function (newValue, oldValue) {
$('li[data-match-route]', element).each(function (k, li) {
var $li = angular.element(li), pattern = $li.attr('data-match-route'), regexp = new RegExp('^' + pattern + '$', ['i']);
if (regexp.test(newValue)) {
$li.addClass('active').find('.collapse.in').collapse('hide');
} else {
$li.removeClass('active');
}
});
});
}
};
}
]);
'use strict';
angular.module('$strap.directives').directive('bsPopover', [
'$parse',
'$compile',
'$http',
'$timeout',
'$q',
'$templateCache',
function ($parse, $compile, $http, $timeout, $q, $templateCache) {
$('body').on('keyup', function (ev) {
if (ev.keyCode === 27) {
$('.popover.in').each(function () {
$(this).popover('hide');
});
}
});
return {
restrict: 'A',
scope: true,
link: function postLink(scope, element, attr, ctrl) {
var getter = $parse(attr.bsPopover), setter = getter.assign, value = getter(scope), options = {};
if (angular.isObject(value)) {
options = value;
}
$q.when(options.content || $templateCache.get(value) || $http.get(value, { cache: true })).then(function onSuccess(template) {
if (angular.isObject(template)) {
template = template.data;
}
if (!!attr.unique) {
element.on('show', function (ev) {
$('.popover.in').each(function () {
var $this = $(this), popover = $this.data('popover');
if (popover && !popover.$element.is(element)) {
$this.popover('hide');
}
});
});
}
if (!!attr.hide) {
scope.$watch(attr.hide, function (newValue, oldValue) {
if (!!newValue) {
popover.hide();
} else if (newValue !== oldValue) {
popover.show();
}
});
}
if (!!attr.show) {
scope.$watch(attr.show, function (newValue, oldValue) {
if (!!newValue) {
$timeout(function () {
popover.show();
});
} else if (newValue !== oldValue) {
popover.hide();
}
});
}
element.popover(angular.extend({}, options, {
content: template,
html: true
}));
var popover = element.data('popover');
popover.hasContent = function () {
return this.getTitle() || template;
};
popover.getPosition = function () {
var r = $.fn.popover.Constructor.prototype.getPosition.apply(this, arguments);
$compile(this.$tip)(scope);
scope.$digest();
this.$tip.data('popover', this);
return r;
};
scope.$popover = function (name) {
popover(name);
};
angular.forEach([
'show',
'hide'
], function (name) {
scope[name] = function () {
popover[name]();
};
});
scope.dismiss = scope.hide;
angular.forEach([
'show',
'shown',
'hide',
'hidden'
], function (name) {
element.on(name, function (ev) {
scope.$emit('popover-' + name, ev);
});
});
});
}
};
}
]);
'use strict';
angular.module('$strap.directives').directive('bsSelect', [
'$timeout',
function ($timeout) {
var NG_OPTIONS_REGEXP = /^\s*(.*?)(?:\s+as\s+(.*?))?(?:\s+group\s+by\s+(.*))?\s+for\s+(?:([\$\w][\$\w\d]*)|(?:\(\s*([\$\w][\$\w\d]*)\s*,\s*([\$\w][\$\w\d]*)\s*\)))\s+in\s+(.*)$/;
return {
restrict: 'A',
require: '?ngModel',
link: function postLink(scope, element, attrs, controller) {
var options = scope.$eval(attrs.bsSelect) || {};
$timeout(function () {
element.selectpicker(options);
element.next().removeClass('ng-scope');
});
if (controller) {
scope.$watch(attrs.ngModel, function (newValue, oldValue) {
if (!angular.equals(newValue, oldValue)) {
element.selectpicker('refresh');
}
});
}
}
};
}
]);
'use strict';
angular.module('$strap.directives').directive('bsTabs', [
'$parse',
'$compile',
'$timeout',
function ($parse, $compile, $timeout) {
var template = '<div class="tabs">' + '<ul class="nav nav-tabs">' + '<li ng-repeat="pane in panes" ng-class="{active:pane.active}">' + '<a data-target="#{{pane.id}}" data-index="{{$index}}" data-toggle="tab">{{pane.title}}</a>' + '</li>' + '</ul>' + '<div class="tab-content" ng-transclude>' + '</div>';
return {
restrict: 'A',
require: '?ngModel',
priority: 0,
scope: true,
template: template,
replace: true,
transclude: true,
compile: function compile(tElement, tAttrs, transclude) {
return function postLink(scope, iElement, iAttrs, controller) {
var getter = $parse(iAttrs.bsTabs), setter = getter.assign, value = getter(scope);
scope.panes = [];
var $tabs = iElement.find('ul.nav-tabs');
var $panes = iElement.find('div.tab-content');
var activeTab = 0, id, title, active;
$timeout(function () {
$panes.find('[data-title], [data-tab]').each(function (index) {
var $this = angular.element(this);
id = 'tab-' + scope.$id + '-' + index;
title = $this.data('title') || $this.data('tab');
active = !active && $this.hasClass('active');
$this.attr('id', id).addClass('tab-pane');
if (iAttrs.fade)
$this.addClass('fade');
scope.panes.push({
id: id,
title: title,
content: this.innerHTML,
active: active
});
});
if (scope.panes.length && !active) {
$panes.find('.tab-pane:first-child').addClass('active' + (iAttrs.fade ? ' in' : ''));
scope.panes[0].active = true;
}
});
if (controller) {
iElement.on('show', function (ev) {
var $target = $(ev.target);
scope.$apply(function () {
controller.$setViewValue($target.data('index'));
});
});
scope.$watch(iAttrs.ngModel, function (newValue, oldValue) {
if (angular.isUndefined(newValue))
return;
activeTab = newValue;
setTimeout(function () {
// Check if we're still on the same tab before making the switch
if(activeTab === newValue) {
var $next = $($tabs[0].querySelectorAll('li')[newValue * 1]);
if (!$next.hasClass('active')) {
$next.children('a').tab('show');
}
}
});
});
}
};
}
};
}
]);
'use strict';
angular.module('$strap.directives').directive('bsTimepicker', [
'$timeout',
'$strapConfig',
function ($timeout, $strapConfig) {
var TIME_REGEXP = '((?:(?:[0-1][0-9])|(?:[2][0-3])|(?:[0-9])):(?:[0-5][0-9])(?::[0-5][0-9])?(?:\\s?(?:am|AM|pm|PM))?)';
return {
restrict: 'A',
require: '?ngModel',
link: function postLink(scope, element, attrs, controller) {
if (controller) {
element.on('changeTime.timepicker', function (ev) {
$timeout(function () {
controller.$setViewValue(element.val());
});
});
var timeRegExp = new RegExp('^' + TIME_REGEXP + '$', ['i']);
controller.$parsers.unshift(function (viewValue) {
if (!viewValue || timeRegExp.test(viewValue)) {
controller.$setValidity('time', true);
return viewValue;
} else {
controller.$setValidity('time', false);
return;
}
});
}
element.attr('data-toggle', 'timepicker');
element.parent().addClass('bootstrap-timepicker');
element.timepicker($strapConfig.timepicker || {});
var timepicker = element.data('timepicker');
var component = element.siblings('[data-toggle="timepicker"]');
if (component.length) {
component.on('click', $.proxy(timepicker.showWidget, timepicker));
}
}
};
}
]);
'use strict';
angular.module('$strap.directives').directive('bsTooltip', [
'$parse',
'$compile',
function ($parse, $compile) {
return {
restrict: 'A',
scope: true,
link: function postLink(scope, element, attrs, ctrl) {
var getter = $parse(attrs.bsTooltip), setter = getter.assign, value = getter(scope);
scope.$watch(attrs.bsTooltip, function (newValue, oldValue) {
if (newValue !== oldValue) {
value = newValue;
}
});
if (!!attrs.unique) {
element.on('show', function (ev) {
$('.tooltip.in').each(function () {
var $this = $(this), tooltip = $this.data('tooltip');
if (tooltip && !tooltip.$element.is(element)) {
$this.tooltip('hide');
}
});
});
}
element.tooltip({
title: function () {
return angular.isFunction(value) ? value.apply(null, arguments) : value;
},
html: true
});
var tooltip = element.data('tooltip');
tooltip.show = function () {
var r = $.fn.tooltip.Constructor.prototype.show.apply(this, arguments);
this.tip().data('tooltip', this);
return r;
};
scope._tooltip = function (event) {
element.tooltip(event);
};
scope.hide = function () {
element.tooltip('hide');
};
scope.show = function () {
element.tooltip('show');
};
scope.dismiss = scope.hide;
}
};
}
]);
'use strict';
angular.module('$strap.directives').directive('bsTypeahead', [
'$parse',
function ($parse) {
return {
restrict: 'A',
require: '?ngModel',
link: function postLink(scope, element, attrs, controller) {
var getter = $parse(attrs.bsTypeahead), setter = getter.assign, value = getter(scope);
scope.$watch(attrs.bsTypeahead, function (newValue, oldValue) {
if (newValue !== oldValue) {
value = newValue;
}
});
element.attr('data-provide', 'typeahead');
element.typeahead({
source: function (query) {
return angular.isFunction(value) ? value.apply(null, arguments) : value;
},
minLength: attrs.minLength || 1,
items: attrs.items,
updater: function (value) {
if (controller) {
scope.$apply(function () {
controller.$setViewValue(value);
});
}
scope.$emit('typeahead-updated', value);
return value;
}
});
var typeahead = element.data('typeahead');
typeahead.lookup = function (ev) {
var items;
this.query = this.$element.val() || '';
if (this.query.length < this.options.minLength) {
return this.shown ? this.hide() : this;
}
items = $.isFunction(this.source) ? this.source(this.query, $.proxy(this.process, this)) : this.source;
return items ? this.process(items) : this;
};
if (!!attrs.matchAll) {
typeahead.matcher = function (item) {
return true;
};
}
if (attrs.minLength === '0') {
setTimeout(function () {
element.on('focus', function () {
element.val().length === 0 && setTimeout(element.typeahead.bind(element, 'lookup'), 200);
});
});
}
}
};
}
]); | src/vendor/angular/angular-strap.js | 0 | https://github.com/grafana/grafana/commit/e9a046e74d86b43b41c92bab5a8ac8beacb61441 | [
0.0024525809567421675,
0.00028281970298849046,
0.00016217843221966177,
0.000174516171682626,
0.00029618164990097284
] |
{
"id": 2,
"code_window": [
" // Receive render events\n",
" scope.$on('render',function(event, renderData) {\n",
" data = renderData || data;\n",
" annotations = data.annotations;\n",
" render_panel();\n",
" });\n",
"\n",
" // Re-render if the window is resized\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" annotations = data.annotations || annotations;\n"
],
"file_path": "src/app/directives/grafanaGraph.js",
"type": "replace",
"edit_start_line_idx": 41
} | <div style="margin-top:50px" ng-controller="dashcontrol">
<strong>type: </strong>{{type}} <br>
<strong>id: </strong>{{id}} <br>
</div> | src/app/partials/load.html | 0 | https://github.com/grafana/grafana/commit/e9a046e74d86b43b41c92bab5a8ac8beacb61441 | [
0.00016761502774897963,
0.00016761502774897963,
0.00016761502774897963,
0.00016761502774897963,
0
] |
{
"id": 0,
"code_window": [
"\n",
"\t\t\tconst dotGit = await this.git.getRepositoryDotGit(repositoryRoot);\n",
"\t\t\tconst repository = new Repository(this.git.open(repositoryRoot, dotGit), this, this, this.globalState, this.outputChannel);\n",
"\n",
"\t\t\tthis.open(repository);\n",
"\t\t\tawait repository.status();\n",
"\t\t} catch (ex) {\n",
"\t\t\t// noop\n",
"\t\t\tthis.outputChannel.appendLine(`Opening repository for path='${repoPath}' failed; ex=${ex}`);\n",
"\t\t}\n",
"\t}\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\t\trepository.status(); // do not await this, we want SCM to know about the repo asap\n"
],
"file_path": "extensions/git/src/model.ts",
"type": "replace",
"edit_start_line_idx": 302
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import { DisposableStore } from 'vs/base/common/lifecycle';
import { Emitter, Event } from 'vs/base/common/event';
import { ISCMViewService, ISCMRepository, ISCMService, ISCMViewVisibleRepositoryChangeEvent, ISCMMenus, ISCMProvider } from 'vs/workbench/contrib/scm/common/scm';
import { Iterable } from 'vs/base/common/iterator';
import { IInstantiationService } from 'vs/platform/instantiation/common/instantiation';
import { SCMMenus } from 'vs/workbench/contrib/scm/browser/menus';
import { IStorageService, StorageScope, StorageTarget } from 'vs/platform/storage/common/storage';
import { debounce } from 'vs/base/common/decorators';
import { ILogService } from 'vs/platform/log/common/log';
function getProviderStorageKey(provider: ISCMProvider): string {
return `${provider.contextValue}:${provider.label}${provider.rootUri ? `:${provider.rootUri.toString()}` : ''}`;
}
export interface ISCMViewServiceState {
readonly all: string[];
readonly visible: number[];
}
export class SCMViewService implements ISCMViewService {
declare readonly _serviceBrand: undefined;
readonly menus: ISCMMenus;
private didFinishLoading: boolean = false;
private provisionalVisibleRepository: ISCMRepository | undefined;
private previousState: ISCMViewServiceState | undefined;
private disposables = new DisposableStore();
private _visibleRepositoriesSet = new Set<ISCMRepository>();
private _visibleRepositories: ISCMRepository[] = [];
get visibleRepositories(): ISCMRepository[] {
return this._visibleRepositories;
}
set visibleRepositories(visibleRepositories: ISCMRepository[]) {
const set = new Set(visibleRepositories);
const added = new Set<ISCMRepository>();
const removed = new Set<ISCMRepository>();
for (const repository of visibleRepositories) {
if (!this._visibleRepositoriesSet.has(repository)) {
added.add(repository);
}
}
for (const repository of this._visibleRepositories) {
if (!set.has(repository)) {
removed.add(repository);
}
}
if (added.size === 0 && removed.size === 0) {
return;
}
this._visibleRepositories = visibleRepositories;
this._visibleRepositoriesSet = set;
this._onDidSetVisibleRepositories.fire({ added, removed });
if (this._focusedRepository && removed.has(this._focusedRepository)) {
this.focus(this._visibleRepositories[0]);
}
}
private _onDidChangeRepositories = new Emitter<ISCMViewVisibleRepositoryChangeEvent>();
private _onDidSetVisibleRepositories = new Emitter<ISCMViewVisibleRepositoryChangeEvent>();
readonly onDidChangeVisibleRepositories = Event.any(
this._onDidSetVisibleRepositories.event,
Event.debounce(
this._onDidChangeRepositories.event,
(last, e) => {
if (!last) {
return e;
}
return {
added: Iterable.concat(last.added, e.added),
removed: Iterable.concat(last.removed, e.removed),
};
}, 0)
);
private _focusedRepository: ISCMRepository | undefined;
get focusedRepository(): ISCMRepository | undefined {
return this._focusedRepository;
}
private _onDidFocusRepository = new Emitter<ISCMRepository | undefined>();
readonly onDidFocusRepository = this._onDidFocusRepository.event;
constructor(
@ISCMService private readonly scmService: ISCMService,
@IInstantiationService instantiationService: IInstantiationService,
@IStorageService private readonly storageService: IStorageService,
@ILogService private readonly logService: ILogService
) {
this.menus = instantiationService.createInstance(SCMMenus);
scmService.onDidAddRepository(this.onDidAddRepository, this, this.disposables);
scmService.onDidRemoveRepository(this.onDidRemoveRepository, this, this.disposables);
for (const repository of scmService.repositories) {
this.onDidAddRepository(repository);
}
try {
this.previousState = JSON.parse(storageService.get('scm:view:visibleRepositories', StorageScope.WORKSPACE, ''));
this.eventuallyFinishLoading();
} catch {
// noop
}
storageService.onWillSaveState(this.onWillSaveState, this, this.disposables);
}
private onDidAddRepository(repository: ISCMRepository): void {
this.logService.trace('SCMViewService#onDidAddRepository', getProviderStorageKey(repository.provider));
if (!this.didFinishLoading) {
this.eventuallyFinishLoading();
}
let removed: Iterable<ISCMRepository> = Iterable.empty();
if (this.previousState) {
const index = this.previousState.all.indexOf(getProviderStorageKey(repository.provider));
if (index === -1) { // saw a repo we did not expect
this.logService.trace('SCMViewService#onDidAddRepository', 'This is a new repository, so we stop the heuristics');
const added: ISCMRepository[] = [];
for (const repo of this.scmService.repositories) { // all should be visible
if (!this._visibleRepositoriesSet.has(repo)) {
added.push(repository);
}
}
this._visibleRepositories = [...this.scmService.repositories];
this._visibleRepositoriesSet = new Set(this.scmService.repositories);
this._onDidChangeRepositories.fire({ added, removed: Iterable.empty() });
this.finishLoading();
return;
}
const visible = this.previousState.visible.indexOf(index) > -1;
if (!visible) {
if (this._visibleRepositories.length === 0) { // should make it visible, until other repos come along
this.provisionalVisibleRepository = repository;
} else {
return;
}
} else {
if (this.provisionalVisibleRepository) {
this._visibleRepositories = [];
this._visibleRepositoriesSet = new Set();
removed = [this.provisionalVisibleRepository];
this.provisionalVisibleRepository = undefined;
}
}
}
this._visibleRepositories.push(repository);
this._visibleRepositoriesSet.add(repository);
this._onDidChangeRepositories.fire({ added: [repository], removed });
if (!this._focusedRepository) {
this.focus(repository);
}
}
private onDidRemoveRepository(repository: ISCMRepository): void {
this.logService.trace('SCMViewService#onDidRemoveRepository', getProviderStorageKey(repository.provider));
if (!this.didFinishLoading) {
this.eventuallyFinishLoading();
}
const index = this._visibleRepositories.indexOf(repository);
if (index > -1) {
let added: Iterable<ISCMRepository> = Iterable.empty();
this._visibleRepositories.splice(index, 1);
this._visibleRepositoriesSet.delete(repository);
if (this._visibleRepositories.length === 0 && this.scmService.repositories.length > 0) {
const first = this.scmService.repositories[0];
this._visibleRepositories.push(first);
this._visibleRepositoriesSet.add(first);
added = [first];
}
this._onDidChangeRepositories.fire({ added, removed: [repository] });
}
if (this._focusedRepository === repository) {
this.focus(this._visibleRepositories[0]);
}
}
isVisible(repository: ISCMRepository): boolean {
return this._visibleRepositoriesSet.has(repository);
}
toggleVisibility(repository: ISCMRepository, visible?: boolean): void {
if (typeof visible === 'undefined') {
visible = !this.isVisible(repository);
} else if (this.isVisible(repository) === visible) {
return;
}
if (visible) {
this.visibleRepositories = [...this.visibleRepositories, repository];
} else {
const index = this.visibleRepositories.indexOf(repository);
if (index > -1) {
this.visibleRepositories = [
...this.visibleRepositories.slice(0, index),
...this.visibleRepositories.slice(index + 1)
];
}
}
}
focus(repository: ISCMRepository | undefined): void {
if (repository && !this.visibleRepositories.includes(repository)) {
return;
}
this._focusedRepository = repository;
this._onDidFocusRepository.fire(repository);
}
private onWillSaveState(): void {
if (!this.didFinishLoading) { // don't remember state, if the workbench didn't really finish loading
return;
}
const all = this.scmService.repositories.map(r => getProviderStorageKey(r.provider));
const visible = this.visibleRepositories.map(r => all.indexOf(getProviderStorageKey(r.provider)));
const raw = JSON.stringify({ all, visible });
this.storageService.store('scm:view:visibleRepositories', raw, StorageScope.WORKSPACE, StorageTarget.MACHINE);
}
@debounce(2000)
private eventuallyFinishLoading(): void {
this.logService.trace('SCMViewService#eventuallyFinishLoading');
this.finishLoading();
}
private finishLoading(): void {
if (this.didFinishLoading) {
return;
}
this.logService.trace('SCMViewService#finishLoading');
this.didFinishLoading = true;
this.previousState = undefined;
}
dispose(): void {
this.disposables.dispose();
this._onDidChangeRepositories.dispose();
this._onDidSetVisibleRepositories.dispose();
}
}
| src/vs/workbench/contrib/scm/browser/scmViewService.ts | 1 | https://github.com/microsoft/vscode/commit/f18b29e132039246caebd4c6b52fcff06265c04d | [
0.014981287531554699,
0.0009354594512842596,
0.0001668154145590961,
0.00017793562437873334,
0.002776624634861946
] |
{
"id": 0,
"code_window": [
"\n",
"\t\t\tconst dotGit = await this.git.getRepositoryDotGit(repositoryRoot);\n",
"\t\t\tconst repository = new Repository(this.git.open(repositoryRoot, dotGit), this, this, this.globalState, this.outputChannel);\n",
"\n",
"\t\t\tthis.open(repository);\n",
"\t\t\tawait repository.status();\n",
"\t\t} catch (ex) {\n",
"\t\t\t// noop\n",
"\t\t\tthis.outputChannel.appendLine(`Opening repository for path='${repoPath}' failed; ex=${ex}`);\n",
"\t\t}\n",
"\t}\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\t\trepository.status(); // do not await this, we want SCM to know about the repo asap\n"
],
"file_path": "extensions/git/src/model.ts",
"type": "replace",
"edit_start_line_idx": 302
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import { asPromise } from 'vs/base/common/async';
import { CancellationToken } from 'vs/base/common/cancellation';
import { debounce } from 'vs/base/common/decorators';
import { Emitter } from 'vs/base/common/event';
import { DisposableStore, IDisposable, MutableDisposable } from 'vs/base/common/lifecycle';
import { MarshalledId } from 'vs/base/common/marshalling';
import { URI, UriComponents } from 'vs/base/common/uri';
import { IRange } from 'vs/editor/common/core/range';
import * as modes from 'vs/editor/common/modes';
import { ExtensionIdentifier, IExtensionDescription } from 'vs/platform/extensions/common/extensions';
import { ExtHostDocuments } from 'vs/workbench/api/common/extHostDocuments';
import * as extHostTypeConverter from 'vs/workbench/api/common/extHostTypeConverters';
import * as types from 'vs/workbench/api/common/extHostTypes';
import type * as vscode from 'vscode';
import { ExtHostCommentsShape, IMainContext, MainContext, CommentThreadChanges } from './extHost.protocol';
import { ExtHostCommands } from './extHostCommands';
type ProviderHandle = number;
export interface ExtHostComments {
createCommentController(extension: IExtensionDescription, id: string, label: string): vscode.CommentController;
}
export function createExtHostComments(mainContext: IMainContext, commands: ExtHostCommands, documents: ExtHostDocuments): ExtHostCommentsShape & ExtHostComments {
const proxy = mainContext.getProxy(MainContext.MainThreadComments);
class ExtHostCommentsImpl implements ExtHostCommentsShape, ExtHostComments, IDisposable {
private static handlePool = 0;
private _commentControllers: Map<ProviderHandle, ExtHostCommentController> = new Map<ProviderHandle, ExtHostCommentController>();
private _commentControllersByExtension: Map<string, ExtHostCommentController[]> = new Map<string, ExtHostCommentController[]>();
constructor(
) {
commands.registerArgumentProcessor({
processArgument: arg => {
if (arg && arg.$mid === MarshalledId.CommentController) {
const commentController = this._commentControllers.get(arg.handle);
if (!commentController) {
return arg;
}
return commentController;
} else if (arg && arg.$mid === MarshalledId.CommentThread) {
const commentController = this._commentControllers.get(arg.commentControlHandle);
if (!commentController) {
return arg;
}
const commentThread = commentController.getCommentThread(arg.commentThreadHandle);
if (!commentThread) {
return arg;
}
return commentThread;
} else if (arg && arg.$mid === MarshalledId.CommentThreadReply) {
const commentController = this._commentControllers.get(arg.thread.commentControlHandle);
if (!commentController) {
return arg;
}
const commentThread = commentController.getCommentThread(arg.thread.commentThreadHandle);
if (!commentThread) {
return arg;
}
return {
thread: commentThread,
text: arg.text
};
} else if (arg && arg.$mid === MarshalledId.CommentNode) {
const commentController = this._commentControllers.get(arg.thread.commentControlHandle);
if (!commentController) {
return arg;
}
const commentThread = commentController.getCommentThread(arg.thread.commentThreadHandle);
if (!commentThread) {
return arg;
}
let commentUniqueId = arg.commentUniqueId;
let comment = commentThread.getCommentByUniqueId(commentUniqueId);
if (!comment) {
return arg;
}
return comment;
} else if (arg && arg.$mid === MarshalledId.CommentThreadNode) {
const commentController = this._commentControllers.get(arg.thread.commentControlHandle);
if (!commentController) {
return arg;
}
const commentThread = commentController.getCommentThread(arg.thread.commentThreadHandle);
if (!commentThread) {
return arg;
}
let body = arg.text;
let commentUniqueId = arg.commentUniqueId;
let comment = commentThread.getCommentByUniqueId(commentUniqueId);
if (!comment) {
return arg;
}
comment.body = body;
return comment;
}
return arg;
}
});
}
createCommentController(extension: IExtensionDescription, id: string, label: string): vscode.CommentController {
const handle = ExtHostCommentsImpl.handlePool++;
const commentController = new ExtHostCommentController(extension, handle, id, label);
this._commentControllers.set(commentController.handle, commentController);
const commentControllers = this._commentControllersByExtension.get(ExtensionIdentifier.toKey(extension.identifier)) || [];
commentControllers.push(commentController);
this._commentControllersByExtension.set(ExtensionIdentifier.toKey(extension.identifier), commentControllers);
return commentController.value;
}
$createCommentThreadTemplate(commentControllerHandle: number, uriComponents: UriComponents, range: IRange): void {
const commentController = this._commentControllers.get(commentControllerHandle);
if (!commentController) {
return;
}
commentController.$createCommentThreadTemplate(uriComponents, range);
}
async $updateCommentThreadTemplate(commentControllerHandle: number, threadHandle: number, range: IRange) {
const commentController = this._commentControllers.get(commentControllerHandle);
if (!commentController) {
return;
}
commentController.$updateCommentThreadTemplate(threadHandle, range);
}
$deleteCommentThread(commentControllerHandle: number, commentThreadHandle: number) {
const commentController = this._commentControllers.get(commentControllerHandle);
if (commentController) {
commentController.$deleteCommentThread(commentThreadHandle);
}
}
$provideCommentingRanges(commentControllerHandle: number, uriComponents: UriComponents, token: CancellationToken): Promise<IRange[] | undefined> {
const commentController = this._commentControllers.get(commentControllerHandle);
if (!commentController || !commentController.commentingRangeProvider) {
return Promise.resolve(undefined);
}
const document = documents.getDocument(URI.revive(uriComponents));
return asPromise(() => {
return commentController.commentingRangeProvider!.provideCommentingRanges(document, token);
}).then(ranges => ranges ? ranges.map(x => extHostTypeConverter.Range.from(x)) : undefined);
}
$toggleReaction(commentControllerHandle: number, threadHandle: number, uri: UriComponents, comment: modes.Comment, reaction: modes.CommentReaction): Promise<void> {
const commentController = this._commentControllers.get(commentControllerHandle);
if (!commentController || !commentController.reactionHandler) {
return Promise.resolve(undefined);
}
return asPromise(() => {
const commentThread = commentController.getCommentThread(threadHandle);
if (commentThread) {
const vscodeComment = commentThread.getCommentByUniqueId(comment.uniqueIdInThread);
if (commentController !== undefined && vscodeComment) {
if (commentController.reactionHandler) {
return commentController.reactionHandler(vscodeComment, convertFromReaction(reaction));
}
}
}
return Promise.resolve(undefined);
});
}
dispose() {
}
}
type CommentThreadModification = Partial<{
range: vscode.Range,
label: string | undefined,
contextValue: string | undefined,
comments: vscode.Comment[],
collapsibleState: vscode.CommentThreadCollapsibleState
canReply: boolean;
}>;
class ExtHostCommentThread implements vscode.CommentThread {
private static _handlePool: number = 0;
readonly handle = ExtHostCommentThread._handlePool++;
public commentHandle: number = 0;
private modifications: CommentThreadModification = Object.create(null);
set threadId(id: string) {
this._id = id;
}
get threadId(): string {
return this._id!;
}
get id(): string {
return this._id!;
}
get resource(): vscode.Uri {
return this._uri;
}
get uri(): vscode.Uri {
return this._uri;
}
private readonly _onDidUpdateCommentThread = new Emitter<void>();
readonly onDidUpdateCommentThread = this._onDidUpdateCommentThread.event;
set range(range: vscode.Range) {
if (!range.isEqual(this._range)) {
this._range = range;
this.modifications.range = range;
this._onDidUpdateCommentThread.fire();
}
}
get range(): vscode.Range {
return this._range;
}
private _canReply: boolean = true;
set canReply(state: boolean) {
if (this._canReply !== state) {
this._canReply = state;
this.modifications.canReply = state;
this._onDidUpdateCommentThread.fire();
}
}
get canReply() {
return this._canReply;
}
private _label: string | undefined;
get label(): string | undefined {
return this._label;
}
set label(label: string | undefined) {
this._label = label;
this.modifications.label = label;
this._onDidUpdateCommentThread.fire();
}
private _contextValue: string | undefined;
get contextValue(): string | undefined {
return this._contextValue;
}
set contextValue(context: string | undefined) {
this._contextValue = context;
this.modifications.contextValue = context;
this._onDidUpdateCommentThread.fire();
}
get comments(): vscode.Comment[] {
return this._comments;
}
set comments(newComments: vscode.Comment[]) {
this._comments = newComments;
this.modifications.comments = newComments;
this._onDidUpdateCommentThread.fire();
}
private _collapseState?: vscode.CommentThreadCollapsibleState;
get collapsibleState(): vscode.CommentThreadCollapsibleState {
return this._collapseState!;
}
set collapsibleState(newState: vscode.CommentThreadCollapsibleState) {
this._collapseState = newState;
this.modifications.collapsibleState = newState;
this._onDidUpdateCommentThread.fire();
}
private _localDisposables: types.Disposable[];
private _isDiposed: boolean;
public get isDisposed(): boolean {
return this._isDiposed;
}
private _commentsMap: Map<vscode.Comment, number> = new Map<vscode.Comment, number>();
private _acceptInputDisposables = new MutableDisposable<DisposableStore>();
readonly value: vscode.CommentThread;
constructor(
commentControllerId: string,
private _commentControllerHandle: number,
private _id: string | undefined,
private _uri: vscode.Uri,
private _range: vscode.Range,
private _comments: vscode.Comment[],
extensionId: ExtensionIdentifier
) {
this._acceptInputDisposables.value = new DisposableStore();
if (this._id === undefined) {
this._id = `${commentControllerId}.${this.handle}`;
}
proxy.$createCommentThread(
_commentControllerHandle,
this.handle,
this._id,
this._uri,
extHostTypeConverter.Range.from(this._range),
extensionId
);
this._localDisposables = [];
this._isDiposed = false;
this._localDisposables.push(this.onDidUpdateCommentThread(() => {
this.eventuallyUpdateCommentThread();
}));
// set up comments after ctor to batch update events.
this.comments = _comments;
this._localDisposables.push({
dispose: () => {
proxy.$deleteCommentThread(
_commentControllerHandle,
this.handle
);
}
});
const that = this;
this.value = {
get uri() { return that.uri; },
get range() { return that.range; },
set range(value: vscode.Range) { that.range = value; },
get comments() { return that.comments; },
set comments(value: vscode.Comment[]) { that.comments = value; },
get collapsibleState() { return that.collapsibleState; },
set collapsibleState(value: vscode.CommentThreadCollapsibleState) { that.collapsibleState = value; },
get canReply() { return that.canReply; },
set canReply(state: boolean) { that.canReply = state; },
get contextValue() { return that.contextValue; },
set contextValue(value: string | undefined) { that.contextValue = value; },
get label() { return that.label; },
set label(value: string | undefined) { that.label = value; },
dispose: () => {
that.dispose();
}
};
}
@debounce(100)
eventuallyUpdateCommentThread(): void {
if (this._isDiposed) {
return;
}
if (!this._acceptInputDisposables.value) {
this._acceptInputDisposables.value = new DisposableStore();
}
const modified = (value: keyof CommentThreadModification): boolean =>
Object.prototype.hasOwnProperty.call(this.modifications, value);
const formattedModifications: CommentThreadChanges = {};
if (modified('range')) {
formattedModifications.range = extHostTypeConverter.Range.from(this._range);
}
if (modified('label')) {
formattedModifications.label = this.label;
}
if (modified('contextValue')) {
/*
* null -> cleared contextValue
* undefined -> no change
*/
formattedModifications.contextValue = this.contextValue ?? null;
}
if (modified('comments')) {
formattedModifications.comments =
this._comments.map(cmt => convertToModeComment(this, cmt, this._commentsMap));
}
if (modified('collapsibleState')) {
formattedModifications.collapseState = convertToCollapsibleState(this._collapseState);
}
if (modified('canReply')) {
formattedModifications.canReply = this.canReply;
}
this.modifications = {};
proxy.$updateCommentThread(
this._commentControllerHandle,
this.handle,
this._id!,
this._uri,
formattedModifications
);
}
getCommentByUniqueId(uniqueId: number): vscode.Comment | undefined {
for (let key of this._commentsMap) {
let comment = key[0];
let id = key[1];
if (uniqueId === id) {
return comment;
}
}
return;
}
dispose() {
this._isDiposed = true;
this._acceptInputDisposables.dispose();
this._localDisposables.forEach(disposable => disposable.dispose());
}
}
type ReactionHandler = (comment: vscode.Comment, reaction: vscode.CommentReaction) => Promise<void>;
class ExtHostCommentController {
get id(): string {
return this._id;
}
get label(): string {
return this._label;
}
public get handle(): number {
return this._handle;
}
private _threads: Map<number, ExtHostCommentThread> = new Map<number, ExtHostCommentThread>();
private _commentingRangeProvider?: vscode.CommentingRangeProvider;
get commentingRangeProvider(): vscode.CommentingRangeProvider | undefined {
return this._commentingRangeProvider;
}
set commentingRangeProvider(provider: vscode.CommentingRangeProvider | undefined) {
this._commentingRangeProvider = provider;
proxy.$updateCommentingRanges(this.handle);
}
private _reactionHandler?: ReactionHandler;
get reactionHandler(): ReactionHandler | undefined {
return this._reactionHandler;
}
set reactionHandler(handler: ReactionHandler | undefined) {
this._reactionHandler = handler;
proxy.$updateCommentControllerFeatures(this.handle, { reactionHandler: !!handler });
}
private _options: modes.CommentOptions | undefined;
get options() {
return this._options;
}
set options(options: modes.CommentOptions | undefined) {
this._options = options;
proxy.$updateCommentControllerFeatures(this.handle, { options: this._options });
}
private _localDisposables: types.Disposable[];
readonly value: vscode.CommentController;
constructor(
private _extension: IExtensionDescription,
private _handle: number,
private _id: string,
private _label: string
) {
proxy.$registerCommentController(this.handle, _id, _label);
const that = this;
this.value = Object.freeze({
id: that.id,
label: that.label,
get options() { return that.options; },
set options(options: vscode.CommentOptions | undefined) { that.options = options; },
get commentingRangeProvider(): vscode.CommentingRangeProvider | undefined { return that.commentingRangeProvider; },
set commentingRangeProvider(commentingRangeProvider: vscode.CommentingRangeProvider | undefined) { that.commentingRangeProvider = commentingRangeProvider; },
get reactionHandler(): ReactionHandler | undefined { return that.reactionHandler; },
set reactionHandler(handler: ReactionHandler | undefined) { that.reactionHandler = handler; },
createCommentThread(uri: vscode.Uri, range: vscode.Range, comments: vscode.Comment[]): vscode.CommentThread {
return that.createCommentThread(uri, range, comments).value;
},
dispose: () => { that.dispose(); },
});
this._localDisposables = [];
this._localDisposables.push({
dispose: () => {
proxy.$unregisterCommentController(this.handle);
}
});
}
createCommentThread(resource: vscode.Uri, range: vscode.Range, comments: vscode.Comment[]): ExtHostCommentThread;
createCommentThread(arg0: vscode.Uri | string, arg1: vscode.Uri | vscode.Range, arg2: vscode.Range | vscode.Comment[], arg3?: vscode.Comment[]): vscode.CommentThread {
if (typeof arg0 === 'string') {
const commentThread = new ExtHostCommentThread(this.id, this.handle, arg0, arg1 as vscode.Uri, arg2 as vscode.Range, arg3 as vscode.Comment[], this._extension.identifier);
this._threads.set(commentThread.handle, commentThread);
return commentThread;
} else {
const commentThread = new ExtHostCommentThread(this.id, this.handle, undefined, arg0 as vscode.Uri, arg1 as vscode.Range, arg2 as vscode.Comment[], this._extension.identifier);
this._threads.set(commentThread.handle, commentThread);
return commentThread;
}
}
$createCommentThreadTemplate(uriComponents: UriComponents, range: IRange): ExtHostCommentThread {
const commentThread = new ExtHostCommentThread(this.id, this.handle, undefined, URI.revive(uriComponents), extHostTypeConverter.Range.to(range), [], this._extension.identifier);
commentThread.collapsibleState = modes.CommentThreadCollapsibleState.Expanded;
this._threads.set(commentThread.handle, commentThread);
return commentThread;
}
$updateCommentThreadTemplate(threadHandle: number, range: IRange): void {
let thread = this._threads.get(threadHandle);
if (thread) {
thread.range = extHostTypeConverter.Range.to(range);
}
}
$deleteCommentThread(threadHandle: number): void {
let thread = this._threads.get(threadHandle);
if (thread) {
thread.dispose();
}
this._threads.delete(threadHandle);
}
getCommentThread(handle: number): ExtHostCommentThread | undefined {
return this._threads.get(handle);
}
dispose(): void {
this._threads.forEach(value => {
value.dispose();
});
this._localDisposables.forEach(disposable => disposable.dispose());
}
}
function convertToModeComment(thread: ExtHostCommentThread, vscodeComment: vscode.Comment, commentsMap: Map<vscode.Comment, number>): modes.Comment {
let commentUniqueId = commentsMap.get(vscodeComment)!;
if (!commentUniqueId) {
commentUniqueId = ++thread.commentHandle;
commentsMap.set(vscodeComment, commentUniqueId);
}
const iconPath = vscodeComment.author && vscodeComment.author.iconPath ? vscodeComment.author.iconPath.toString() : undefined;
return {
mode: vscodeComment.mode,
contextValue: vscodeComment.contextValue,
uniqueIdInThread: commentUniqueId,
body: extHostTypeConverter.MarkdownString.from(vscodeComment.body),
userName: vscodeComment.author.name,
userIconPath: iconPath,
label: vscodeComment.label,
commentReactions: vscodeComment.reactions ? vscodeComment.reactions.map(reaction => convertToReaction(reaction)) : undefined
};
}
function convertToReaction(reaction: vscode.CommentReaction): modes.CommentReaction {
return {
label: reaction.label,
iconPath: reaction.iconPath ? extHostTypeConverter.pathOrURIToURI(reaction.iconPath) : undefined,
count: reaction.count,
hasReacted: reaction.authorHasReacted,
};
}
function convertFromReaction(reaction: modes.CommentReaction): vscode.CommentReaction {
return {
label: reaction.label || '',
count: reaction.count || 0,
iconPath: reaction.iconPath ? URI.revive(reaction.iconPath) : '',
authorHasReacted: reaction.hasReacted || false
};
}
function convertToCollapsibleState(kind: vscode.CommentThreadCollapsibleState | undefined): modes.CommentThreadCollapsibleState {
if (kind !== undefined) {
switch (kind) {
case types.CommentThreadCollapsibleState.Expanded:
return modes.CommentThreadCollapsibleState.Expanded;
case types.CommentThreadCollapsibleState.Collapsed:
return modes.CommentThreadCollapsibleState.Collapsed;
}
}
return modes.CommentThreadCollapsibleState.Collapsed;
}
return new ExtHostCommentsImpl();
}
| src/vs/workbench/api/common/extHostComments.ts | 0 | https://github.com/microsoft/vscode/commit/f18b29e132039246caebd4c6b52fcff06265c04d | [
0.00017928778834175318,
0.0001731455558910966,
0.0001643333089305088,
0.00017359593766741455,
0.00000310371592604497
] |
{
"id": 0,
"code_window": [
"\n",
"\t\t\tconst dotGit = await this.git.getRepositoryDotGit(repositoryRoot);\n",
"\t\t\tconst repository = new Repository(this.git.open(repositoryRoot, dotGit), this, this, this.globalState, this.outputChannel);\n",
"\n",
"\t\t\tthis.open(repository);\n",
"\t\t\tawait repository.status();\n",
"\t\t} catch (ex) {\n",
"\t\t\t// noop\n",
"\t\t\tthis.outputChannel.appendLine(`Opening repository for path='${repoPath}' failed; ex=${ex}`);\n",
"\t\t}\n",
"\t}\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\t\trepository.status(); // do not await this, we want SCM to know about the repo asap\n"
],
"file_path": "extensions/git/src/model.ts",
"type": "replace",
"edit_start_line_idx": 302
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
//@ts-check
'use strict';
const withBrowserDefaults = require('../shared.webpack.config').browser;
const path = require('path');
module.exports = withBrowserDefaults({
context: __dirname,
entry: {
extension: './src/extension.ts'
},
output: {
filename: 'extension.js',
path: path.join(__dirname, 'dist')
}
});
| extensions/search-result/extension-browser.webpack.config.js | 0 | https://github.com/microsoft/vscode/commit/f18b29e132039246caebd4c6b52fcff06265c04d | [
0.0001755345583660528,
0.00017313483112957329,
0.00016978365601971745,
0.00017408626445103437,
0.000002442286586301634
] |
{
"id": 0,
"code_window": [
"\n",
"\t\t\tconst dotGit = await this.git.getRepositoryDotGit(repositoryRoot);\n",
"\t\t\tconst repository = new Repository(this.git.open(repositoryRoot, dotGit), this, this, this.globalState, this.outputChannel);\n",
"\n",
"\t\t\tthis.open(repository);\n",
"\t\t\tawait repository.status();\n",
"\t\t} catch (ex) {\n",
"\t\t\t// noop\n",
"\t\t\tthis.outputChannel.appendLine(`Opening repository for path='${repoPath}' failed; ex=${ex}`);\n",
"\t\t}\n",
"\t}\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\t\trepository.status(); // do not await this, we want SCM to know about the repo asap\n"
],
"file_path": "extensions/git/src/model.ts",
"type": "replace",
"edit_start_line_idx": 302
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import { toErrorMessage } from 'vs/base/common/errorMessage';
import { IReference, dispose, Disposable } from 'vs/base/common/lifecycle';
import { Schemas } from 'vs/base/common/network';
import { URI, UriComponents } from 'vs/base/common/uri';
import { ITextModel } from 'vs/editor/common/model';
import { IModelService, shouldSynchronizeModel } from 'vs/editor/common/services/modelService';
import { ITextModelService } from 'vs/editor/common/services/resolverService';
import { IFileService, FileOperation } from 'vs/platform/files/common/files';
import { MainThreadDocumentsAndEditors } from 'vs/workbench/api/browser/mainThreadDocumentsAndEditors';
import { ExtHostContext, ExtHostDocumentsShape, IExtHostContext, MainThreadDocumentsShape } from 'vs/workbench/api/common/extHost.protocol';
import { ITextFileService } from 'vs/workbench/services/textfile/common/textfiles';
import { IWorkbenchEnvironmentService } from 'vs/workbench/services/environment/common/environmentService';
import { toLocalResource, extUri, IExtUri } from 'vs/base/common/resources';
import { IWorkingCopyFileService } from 'vs/workbench/services/workingCopy/common/workingCopyFileService';
import { IUriIdentityService } from 'vs/platform/uriIdentity/common/uriIdentity';
import { Emitter } from 'vs/base/common/event';
import { IPathService } from 'vs/workbench/services/path/common/pathService';
import { ResourceMap } from 'vs/base/common/map';
export class BoundModelReferenceCollection {
private _data = new Array<{ uri: URI, length: number, dispose(): void }>();
private _length = 0;
constructor(
private readonly _extUri: IExtUri,
private readonly _maxAge: number = 1000 * 60 * 3, // auto-dispse by age
private readonly _maxLength: number = 1024 * 1024 * 80, // auto-dispose by total length
private readonly _maxSize: number = 50 // auto-dispose by number of references
) {
//
}
dispose(): void {
this._data = dispose(this._data);
}
remove(uri: URI): void {
for (const entry of [...this._data] /* copy array because dispose will modify it */) {
if (this._extUri.isEqualOrParent(entry.uri, uri)) {
entry.dispose();
}
}
}
add(uri: URI, ref: IReference<any>, length: number = 0): void {
// const length = ref.object.textEditorModel.getValueLength();
let handle: any;
let entry: { uri: URI, length: number, dispose(): void };
const dispose = () => {
const idx = this._data.indexOf(entry);
if (idx >= 0) {
this._length -= length;
ref.dispose();
clearTimeout(handle);
this._data.splice(idx, 1);
}
};
handle = setTimeout(dispose, this._maxAge);
entry = { uri, length, dispose };
this._data.push(entry);
this._length += length;
this._cleanup();
}
private _cleanup(): void {
// clean-up wrt total length
while (this._length > this._maxLength) {
this._data[0].dispose();
}
// clean-up wrt number of documents
const extraSize = Math.ceil(this._maxSize * 1.2);
if (this._data.length >= extraSize) {
dispose(this._data.slice(0, extraSize - this._maxSize));
}
}
}
class ModelTracker extends Disposable {
private _knownVersionId: number;
constructor(
private readonly _model: ITextModel,
private readonly _onIsCaughtUpWithContentChanges: Emitter<URI>,
private readonly _proxy: ExtHostDocumentsShape,
private readonly _textFileService: ITextFileService,
) {
super();
this._knownVersionId = this._model.getVersionId();
this._register(this._model.onDidChangeContent((e) => {
this._knownVersionId = e.versionId;
this._proxy.$acceptModelChanged(this._model.uri, e, this._textFileService.isDirty(this._model.uri));
if (this.isCaughtUpWithContentChanges()) {
this._onIsCaughtUpWithContentChanges.fire(this._model.uri);
}
}));
}
public isCaughtUpWithContentChanges(): boolean {
return (this._model.getVersionId() === this._knownVersionId);
}
}
export class MainThreadDocuments extends Disposable implements MainThreadDocumentsShape {
private _onIsCaughtUpWithContentChanges = this._register(new Emitter<URI>());
public readonly onIsCaughtUpWithContentChanges = this._onIsCaughtUpWithContentChanges.event;
private readonly _proxy: ExtHostDocumentsShape;
private readonly _modelTrackers = new ResourceMap<ModelTracker>();
private readonly _modelIsSynced = new ResourceMap<void>();
private readonly _modelReferenceCollection: BoundModelReferenceCollection;
constructor(
documentsAndEditors: MainThreadDocumentsAndEditors,
extHostContext: IExtHostContext,
@IModelService private readonly _modelService: IModelService,
@ITextFileService private readonly _textFileService: ITextFileService,
@IFileService private readonly _fileService: IFileService,
@ITextModelService private readonly _textModelResolverService: ITextModelService,
@IWorkbenchEnvironmentService private readonly _environmentService: IWorkbenchEnvironmentService,
@IUriIdentityService private readonly _uriIdentityService: IUriIdentityService,
@IWorkingCopyFileService workingCopyFileService: IWorkingCopyFileService,
@IPathService private readonly _pathService: IPathService
) {
super();
this._modelReferenceCollection = this._register(new BoundModelReferenceCollection(_uriIdentityService.extUri));
this._proxy = extHostContext.getProxy(ExtHostContext.ExtHostDocuments);
this._register(documentsAndEditors.onDocumentAdd(models => models.forEach(this._onModelAdded, this)));
this._register(documentsAndEditors.onDocumentRemove(urls => urls.forEach(this._onModelRemoved, this)));
this._register(_modelService.onModelModeChanged(this._onModelModeChanged, this));
this._register(_textFileService.files.onDidSave(e => {
if (this._shouldHandleFileEvent(e.model.resource)) {
this._proxy.$acceptModelSaved(e.model.resource);
}
}));
this._register(_textFileService.files.onDidChangeDirty(m => {
if (this._shouldHandleFileEvent(m.resource)) {
this._proxy.$acceptDirtyStateChanged(m.resource, m.isDirty());
}
}));
this._register(workingCopyFileService.onDidRunWorkingCopyFileOperation(e => {
const isMove = e.operation === FileOperation.MOVE;
if (isMove || e.operation === FileOperation.DELETE) {
for (const pair of e.files) {
const removed = isMove ? pair.source : pair.target;
if (removed) {
this._modelReferenceCollection.remove(removed);
}
}
}
}));
}
public override dispose(): void {
dispose(this._modelTrackers.values());
this._modelTrackers.clear();
super.dispose();
}
public isCaughtUpWithContentChanges(resource: URI): boolean {
const tracker = this._modelTrackers.get(resource);
if (tracker) {
return tracker.isCaughtUpWithContentChanges();
}
return true;
}
private _shouldHandleFileEvent(resource: URI): boolean {
const model = this._modelService.getModel(resource);
return !!model && shouldSynchronizeModel(model);
}
private _onModelAdded(model: ITextModel): void {
// Same filter as in mainThreadEditorsTracker
if (!shouldSynchronizeModel(model)) {
// don't synchronize too large models
return;
}
this._modelIsSynced.set(model.uri, undefined);
this._modelTrackers.set(model.uri, new ModelTracker(model, this._onIsCaughtUpWithContentChanges, this._proxy, this._textFileService));
}
private _onModelModeChanged(event: { model: ITextModel; oldModeId: string; }): void {
let { model } = event;
if (!this._modelIsSynced.has(model.uri)) {
return;
}
this._proxy.$acceptModelModeChanged(model.uri, model.getLanguageId());
}
private _onModelRemoved(modelUrl: URI): void {
if (!this._modelIsSynced.has(modelUrl)) {
return;
}
this._modelIsSynced.delete(modelUrl);
this._modelTrackers.get(modelUrl)!.dispose();
this._modelTrackers.delete(modelUrl);
}
// --- from extension host process
$trySaveDocument(uri: UriComponents): Promise<boolean> {
return this._textFileService.save(URI.revive(uri)).then(target => !!target);
}
$tryOpenDocument(uriData: UriComponents): Promise<URI> {
const inputUri = URI.revive(uriData);
if (!inputUri.scheme || !(inputUri.fsPath || inputUri.authority)) {
return Promise.reject(new Error(`Invalid uri. Scheme and authority or path must be set.`));
}
const canonicalUri = this._uriIdentityService.asCanonicalUri(inputUri);
let promise: Promise<URI>;
switch (canonicalUri.scheme) {
case Schemas.untitled:
promise = this._handleUntitledScheme(canonicalUri);
break;
case Schemas.file:
default:
promise = this._handleAsResourceInput(canonicalUri);
break;
}
return promise.then(documentUri => {
if (!documentUri) {
return Promise.reject(new Error(`cannot open ${canonicalUri.toString()}`));
} else if (!extUri.isEqual(documentUri, canonicalUri)) {
return Promise.reject(new Error(`cannot open ${canonicalUri.toString()}. Detail: Actual document opened as ${documentUri.toString()}`));
} else if (!this._modelIsSynced.has(canonicalUri)) {
return Promise.reject(new Error(`cannot open ${canonicalUri.toString()}. Detail: Files above 50MB cannot be synchronized with extensions.`));
} else {
return canonicalUri;
}
}, err => {
return Promise.reject(new Error(`cannot open ${canonicalUri.toString()}. Detail: ${toErrorMessage(err)}`));
});
}
$tryCreateDocument(options?: { language?: string, content?: string }): Promise<URI> {
return this._doCreateUntitled(undefined, options ? options.language : undefined, options ? options.content : undefined);
}
private _handleAsResourceInput(uri: URI): Promise<URI> {
return this._textModelResolverService.createModelReference(uri).then(ref => {
this._modelReferenceCollection.add(uri, ref, ref.object.textEditorModel.getValueLength());
return ref.object.textEditorModel.uri;
});
}
private _handleUntitledScheme(uri: URI): Promise<URI> {
const asLocalUri = toLocalResource(uri, this._environmentService.remoteAuthority, this._pathService.defaultUriScheme);
return this._fileService.resolve(asLocalUri).then(stats => {
// don't create a new file ontop of an existing file
return Promise.reject(new Error('file already exists'));
}, err => {
return this._doCreateUntitled(Boolean(uri.path) ? uri : undefined);
});
}
private _doCreateUntitled(associatedResource?: URI, mode?: string, initialValue?: string): Promise<URI> {
return this._textFileService.untitled.resolve({
associatedResource,
mode,
initialValue
}).then(model => {
const resource = model.resource;
if (!this._modelIsSynced.has(resource)) {
throw new Error(`expected URI ${resource.toString()} to have come to LIFE`);
}
this._proxy.$acceptDirtyStateChanged(resource, true); // mark as dirty
return resource;
});
}
}
| src/vs/workbench/api/browser/mainThreadDocuments.ts | 0 | https://github.com/microsoft/vscode/commit/f18b29e132039246caebd4c6b52fcff06265c04d | [
0.00017733292770572007,
0.0001741731830406934,
0.00016793511167634279,
0.00017467880388721824,
0.000002300919277331559
] |
{
"id": 1,
"code_window": [
"\treadonly onDidFocusRepository = this._onDidFocusRepository.event;\n",
"\n",
"\tconstructor(\n",
"\t\t@ISCMService private readonly scmService: ISCMService,\n",
"\t\t@IInstantiationService instantiationService: IInstantiationService,\n",
"\t\t@IStorageService private readonly storageService: IStorageService,\n",
"\t\t@ILogService private readonly logService: ILogService\n",
"\t) {\n",
"\t\tthis.menus = instantiationService.createInstance(SCMMenus);\n",
"\n",
"\t\tscmService.onDidAddRepository(this.onDidAddRepository, this, this.disposables);\n",
"\t\tscmService.onDidRemoveRepository(this.onDidRemoveRepository, this, this.disposables);\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\t@IStorageService private readonly storageService: IStorageService\n"
],
"file_path": "src/vs/workbench/contrib/scm/browser/scmViewService.ts",
"type": "replace",
"edit_start_line_idx": 102
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import { DisposableStore } from 'vs/base/common/lifecycle';
import { Emitter, Event } from 'vs/base/common/event';
import { ISCMViewService, ISCMRepository, ISCMService, ISCMViewVisibleRepositoryChangeEvent, ISCMMenus, ISCMProvider } from 'vs/workbench/contrib/scm/common/scm';
import { Iterable } from 'vs/base/common/iterator';
import { IInstantiationService } from 'vs/platform/instantiation/common/instantiation';
import { SCMMenus } from 'vs/workbench/contrib/scm/browser/menus';
import { IStorageService, StorageScope, StorageTarget } from 'vs/platform/storage/common/storage';
import { debounce } from 'vs/base/common/decorators';
import { ILogService } from 'vs/platform/log/common/log';
function getProviderStorageKey(provider: ISCMProvider): string {
return `${provider.contextValue}:${provider.label}${provider.rootUri ? `:${provider.rootUri.toString()}` : ''}`;
}
export interface ISCMViewServiceState {
readonly all: string[];
readonly visible: number[];
}
export class SCMViewService implements ISCMViewService {
declare readonly _serviceBrand: undefined;
readonly menus: ISCMMenus;
private didFinishLoading: boolean = false;
private provisionalVisibleRepository: ISCMRepository | undefined;
private previousState: ISCMViewServiceState | undefined;
private disposables = new DisposableStore();
private _visibleRepositoriesSet = new Set<ISCMRepository>();
private _visibleRepositories: ISCMRepository[] = [];
get visibleRepositories(): ISCMRepository[] {
return this._visibleRepositories;
}
set visibleRepositories(visibleRepositories: ISCMRepository[]) {
const set = new Set(visibleRepositories);
const added = new Set<ISCMRepository>();
const removed = new Set<ISCMRepository>();
for (const repository of visibleRepositories) {
if (!this._visibleRepositoriesSet.has(repository)) {
added.add(repository);
}
}
for (const repository of this._visibleRepositories) {
if (!set.has(repository)) {
removed.add(repository);
}
}
if (added.size === 0 && removed.size === 0) {
return;
}
this._visibleRepositories = visibleRepositories;
this._visibleRepositoriesSet = set;
this._onDidSetVisibleRepositories.fire({ added, removed });
if (this._focusedRepository && removed.has(this._focusedRepository)) {
this.focus(this._visibleRepositories[0]);
}
}
private _onDidChangeRepositories = new Emitter<ISCMViewVisibleRepositoryChangeEvent>();
private _onDidSetVisibleRepositories = new Emitter<ISCMViewVisibleRepositoryChangeEvent>();
readonly onDidChangeVisibleRepositories = Event.any(
this._onDidSetVisibleRepositories.event,
Event.debounce(
this._onDidChangeRepositories.event,
(last, e) => {
if (!last) {
return e;
}
return {
added: Iterable.concat(last.added, e.added),
removed: Iterable.concat(last.removed, e.removed),
};
}, 0)
);
private _focusedRepository: ISCMRepository | undefined;
get focusedRepository(): ISCMRepository | undefined {
return this._focusedRepository;
}
private _onDidFocusRepository = new Emitter<ISCMRepository | undefined>();
readonly onDidFocusRepository = this._onDidFocusRepository.event;
constructor(
@ISCMService private readonly scmService: ISCMService,
@IInstantiationService instantiationService: IInstantiationService,
@IStorageService private readonly storageService: IStorageService,
@ILogService private readonly logService: ILogService
) {
this.menus = instantiationService.createInstance(SCMMenus);
scmService.onDidAddRepository(this.onDidAddRepository, this, this.disposables);
scmService.onDidRemoveRepository(this.onDidRemoveRepository, this, this.disposables);
for (const repository of scmService.repositories) {
this.onDidAddRepository(repository);
}
try {
this.previousState = JSON.parse(storageService.get('scm:view:visibleRepositories', StorageScope.WORKSPACE, ''));
this.eventuallyFinishLoading();
} catch {
// noop
}
storageService.onWillSaveState(this.onWillSaveState, this, this.disposables);
}
private onDidAddRepository(repository: ISCMRepository): void {
this.logService.trace('SCMViewService#onDidAddRepository', getProviderStorageKey(repository.provider));
if (!this.didFinishLoading) {
this.eventuallyFinishLoading();
}
let removed: Iterable<ISCMRepository> = Iterable.empty();
if (this.previousState) {
const index = this.previousState.all.indexOf(getProviderStorageKey(repository.provider));
if (index === -1) { // saw a repo we did not expect
this.logService.trace('SCMViewService#onDidAddRepository', 'This is a new repository, so we stop the heuristics');
const added: ISCMRepository[] = [];
for (const repo of this.scmService.repositories) { // all should be visible
if (!this._visibleRepositoriesSet.has(repo)) {
added.push(repository);
}
}
this._visibleRepositories = [...this.scmService.repositories];
this._visibleRepositoriesSet = new Set(this.scmService.repositories);
this._onDidChangeRepositories.fire({ added, removed: Iterable.empty() });
this.finishLoading();
return;
}
const visible = this.previousState.visible.indexOf(index) > -1;
if (!visible) {
if (this._visibleRepositories.length === 0) { // should make it visible, until other repos come along
this.provisionalVisibleRepository = repository;
} else {
return;
}
} else {
if (this.provisionalVisibleRepository) {
this._visibleRepositories = [];
this._visibleRepositoriesSet = new Set();
removed = [this.provisionalVisibleRepository];
this.provisionalVisibleRepository = undefined;
}
}
}
this._visibleRepositories.push(repository);
this._visibleRepositoriesSet.add(repository);
this._onDidChangeRepositories.fire({ added: [repository], removed });
if (!this._focusedRepository) {
this.focus(repository);
}
}
private onDidRemoveRepository(repository: ISCMRepository): void {
this.logService.trace('SCMViewService#onDidRemoveRepository', getProviderStorageKey(repository.provider));
if (!this.didFinishLoading) {
this.eventuallyFinishLoading();
}
const index = this._visibleRepositories.indexOf(repository);
if (index > -1) {
let added: Iterable<ISCMRepository> = Iterable.empty();
this._visibleRepositories.splice(index, 1);
this._visibleRepositoriesSet.delete(repository);
if (this._visibleRepositories.length === 0 && this.scmService.repositories.length > 0) {
const first = this.scmService.repositories[0];
this._visibleRepositories.push(first);
this._visibleRepositoriesSet.add(first);
added = [first];
}
this._onDidChangeRepositories.fire({ added, removed: [repository] });
}
if (this._focusedRepository === repository) {
this.focus(this._visibleRepositories[0]);
}
}
isVisible(repository: ISCMRepository): boolean {
return this._visibleRepositoriesSet.has(repository);
}
toggleVisibility(repository: ISCMRepository, visible?: boolean): void {
if (typeof visible === 'undefined') {
visible = !this.isVisible(repository);
} else if (this.isVisible(repository) === visible) {
return;
}
if (visible) {
this.visibleRepositories = [...this.visibleRepositories, repository];
} else {
const index = this.visibleRepositories.indexOf(repository);
if (index > -1) {
this.visibleRepositories = [
...this.visibleRepositories.slice(0, index),
...this.visibleRepositories.slice(index + 1)
];
}
}
}
focus(repository: ISCMRepository | undefined): void {
if (repository && !this.visibleRepositories.includes(repository)) {
return;
}
this._focusedRepository = repository;
this._onDidFocusRepository.fire(repository);
}
private onWillSaveState(): void {
if (!this.didFinishLoading) { // don't remember state, if the workbench didn't really finish loading
return;
}
const all = this.scmService.repositories.map(r => getProviderStorageKey(r.provider));
const visible = this.visibleRepositories.map(r => all.indexOf(getProviderStorageKey(r.provider)));
const raw = JSON.stringify({ all, visible });
this.storageService.store('scm:view:visibleRepositories', raw, StorageScope.WORKSPACE, StorageTarget.MACHINE);
}
@debounce(2000)
private eventuallyFinishLoading(): void {
this.logService.trace('SCMViewService#eventuallyFinishLoading');
this.finishLoading();
}
private finishLoading(): void {
if (this.didFinishLoading) {
return;
}
this.logService.trace('SCMViewService#finishLoading');
this.didFinishLoading = true;
this.previousState = undefined;
}
dispose(): void {
this.disposables.dispose();
this._onDidChangeRepositories.dispose();
this._onDidSetVisibleRepositories.dispose();
}
}
| src/vs/workbench/contrib/scm/browser/scmViewService.ts | 1 | https://github.com/microsoft/vscode/commit/f18b29e132039246caebd4c6b52fcff06265c04d | [
0.9973337650299072,
0.07378767430782318,
0.00016375549603253603,
0.0004557768115773797,
0.2558842897415161
] |
{
"id": 1,
"code_window": [
"\treadonly onDidFocusRepository = this._onDidFocusRepository.event;\n",
"\n",
"\tconstructor(\n",
"\t\t@ISCMService private readonly scmService: ISCMService,\n",
"\t\t@IInstantiationService instantiationService: IInstantiationService,\n",
"\t\t@IStorageService private readonly storageService: IStorageService,\n",
"\t\t@ILogService private readonly logService: ILogService\n",
"\t) {\n",
"\t\tthis.menus = instantiationService.createInstance(SCMMenus);\n",
"\n",
"\t\tscmService.onDidAddRepository(this.onDidAddRepository, this, this.disposables);\n",
"\t\tscmService.onDidRemoveRepository(this.onDidRemoveRepository, this, this.disposables);\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\t@IStorageService private readonly storageService: IStorageService\n"
],
"file_path": "src/vs/workbench/contrib/scm/browser/scmViewService.ts",
"type": "replace",
"edit_start_line_idx": 102
} | /*---------------------------------------------------------------------------------------------
* 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 { registerSingleton } from 'vs/platform/instantiation/common/extensions';
import { IFileService } from 'vs/platform/files/common/files';
import { AbstractExtensionResourceLoaderService, IExtensionResourceLoaderService } from 'vs/workbench/services/extensionResourceLoader/common/extensionResourceLoader';
import { FileAccess, Schemas } from 'vs/base/common/network';
import { IProductService } from 'vs/platform/product/common/productService';
import { IStorageService } from 'vs/platform/storage/common/storage';
import { IEnvironmentService } from 'vs/platform/environment/common/environment';
import { ILogService } from 'vs/platform/log/common/log';
import { IConfigurationService } from 'vs/platform/configuration/common/configuration';
class ExtensionResourceLoaderService extends AbstractExtensionResourceLoaderService {
declare readonly _serviceBrand: undefined;
constructor(
@IFileService fileService: IFileService,
@IStorageService storageService: IStorageService,
@IProductService productService: IProductService,
@IEnvironmentService environmentService: IEnvironmentService,
@IConfigurationService configurationService: IConfigurationService,
@ILogService private readonly _logService: ILogService,
) {
super(fileService, storageService, productService, environmentService, configurationService);
}
async readExtensionResource(uri: URI): Promise<string> {
uri = FileAccess.asBrowserUri(uri);
if (uri.scheme !== Schemas.http && uri.scheme !== Schemas.https) {
const result = await this._fileService.readFile(uri);
return result.value.toString();
}
const requestInit: RequestInit = {};
if (this.isExtensionGalleryResource(uri)) {
requestInit.headers = await this.getExtensionGalleryRequestHeaders();
requestInit.mode = 'cors'; /* set mode to cors so that above headers are always passed */
}
const response = await fetch(uri.toString(true), requestInit);
if (response.status !== 200) {
this._logService.info(`Request to '${uri.toString(true)}' failed with status code ${response.status}`);
throw new Error(response.statusText);
}
return response.text();
}
}
registerSingleton(IExtensionResourceLoaderService, ExtensionResourceLoaderService);
| src/vs/workbench/services/extensionResourceLoader/browser/extensionResourceLoaderService.ts | 0 | https://github.com/microsoft/vscode/commit/f18b29e132039246caebd4c6b52fcff06265c04d | [
0.00025430883397348225,
0.0001888721453724429,
0.0001726680202409625,
0.00017375194875057787,
0.00002959336961794179
] |
{
"id": 1,
"code_window": [
"\treadonly onDidFocusRepository = this._onDidFocusRepository.event;\n",
"\n",
"\tconstructor(\n",
"\t\t@ISCMService private readonly scmService: ISCMService,\n",
"\t\t@IInstantiationService instantiationService: IInstantiationService,\n",
"\t\t@IStorageService private readonly storageService: IStorageService,\n",
"\t\t@ILogService private readonly logService: ILogService\n",
"\t) {\n",
"\t\tthis.menus = instantiationService.createInstance(SCMMenus);\n",
"\n",
"\t\tscmService.onDidAddRepository(this.onDidAddRepository, this, this.disposables);\n",
"\t\tscmService.onDidRemoveRepository(this.onDidRemoveRepository, this, this.disposables);\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\t@IStorageService private readonly storageService: IStorageService\n"
],
"file_path": "src/vs/workbench/contrib/scm/browser/scmViewService.ts",
"type": "replace",
"edit_start_line_idx": 102
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import { registerSingleton } from 'vs/platform/instantiation/common/extensions';
import { IWorkspacesService, IWorkspaceFolderCreationData, IWorkspaceIdentifier, IEnterWorkspaceResult, IRecentlyOpened, restoreRecentlyOpened, IRecent, isRecentFile, isRecentFolder, toStoreData, IStoredWorkspaceFolder, getStoredWorkspaceFolder, WORKSPACE_EXTENSION, IStoredWorkspace } from 'vs/platform/workspaces/common/workspaces';
import { URI } from 'vs/base/common/uri';
import { Emitter } from 'vs/base/common/event';
import { IStorageService, StorageScope, StorageTarget } from 'vs/platform/storage/common/storage';
import { IWorkspaceContextService, WorkbenchState } from 'vs/platform/workspace/common/workspace';
import { ILogService } from 'vs/platform/log/common/log';
import { Disposable } from 'vs/base/common/lifecycle';
import { getWorkspaceIdentifier } from 'vs/workbench/services/workspaces/browser/workspaces';
import { IFileService, FileOperationError, FileOperationResult } from 'vs/platform/files/common/files';
import { IWorkbenchEnvironmentService } from 'vs/workbench/services/environment/common/environmentService';
import { joinPath } from 'vs/base/common/resources';
import { VSBuffer } from 'vs/base/common/buffer';
import { isWindows } from 'vs/base/common/platform';
import { IUriIdentityService } from 'vs/platform/uriIdentity/common/uriIdentity';
export class BrowserWorkspacesService extends Disposable implements IWorkspacesService {
static readonly RECENTLY_OPENED_KEY = 'recently.opened';
declare readonly _serviceBrand: undefined;
private readonly _onRecentlyOpenedChange = this._register(new Emitter<void>());
readonly onDidChangeRecentlyOpened = this._onRecentlyOpenedChange.event;
constructor(
@IStorageService private readonly storageService: IStorageService,
@IWorkspaceContextService private readonly workspaceService: IWorkspaceContextService,
@ILogService private readonly logService: ILogService,
@IFileService private readonly fileService: IFileService,
@IWorkbenchEnvironmentService private readonly environmentService: IWorkbenchEnvironmentService,
@IUriIdentityService private readonly uriIdentityService: IUriIdentityService,
) {
super();
// Opening a workspace should push it as most
// recently used to the workspaces history
this.addWorkspaceToRecentlyOpened();
this.registerListeners();
}
private registerListeners(): void {
this._register(this.storageService.onDidChangeValue(event => {
if (event.key === BrowserWorkspacesService.RECENTLY_OPENED_KEY && event.scope === StorageScope.GLOBAL) {
this._onRecentlyOpenedChange.fire();
}
}));
}
private addWorkspaceToRecentlyOpened(): void {
const workspace = this.workspaceService.getWorkspace();
switch (this.workspaceService.getWorkbenchState()) {
case WorkbenchState.FOLDER:
this.addRecentlyOpened([{ folderUri: workspace.folders[0].uri }]);
break;
case WorkbenchState.WORKSPACE:
this.addRecentlyOpened([{ workspace: { id: workspace.id, configPath: workspace.configuration! } }]);
break;
}
}
//#region Workspaces History
async getRecentlyOpened(): Promise<IRecentlyOpened> {
const recentlyOpenedRaw = this.storageService.get(BrowserWorkspacesService.RECENTLY_OPENED_KEY, StorageScope.GLOBAL);
if (recentlyOpenedRaw) {
return restoreRecentlyOpened(JSON.parse(recentlyOpenedRaw), this.logService);
}
return { workspaces: [], files: [] };
}
async addRecentlyOpened(recents: IRecent[]): Promise<void> {
const recentlyOpened = await this.getRecentlyOpened();
recents.forEach(recent => {
if (isRecentFile(recent)) {
this.doRemoveRecentlyOpened(recentlyOpened, [recent.fileUri]);
recentlyOpened.files.unshift(recent);
} else if (isRecentFolder(recent)) {
this.doRemoveRecentlyOpened(recentlyOpened, [recent.folderUri]);
recentlyOpened.workspaces.unshift(recent);
} else {
this.doRemoveRecentlyOpened(recentlyOpened, [recent.workspace.configPath]);
recentlyOpened.workspaces.unshift(recent);
}
});
return this.saveRecentlyOpened(recentlyOpened);
}
async removeRecentlyOpened(paths: URI[]): Promise<void> {
const recentlyOpened = await this.getRecentlyOpened();
this.doRemoveRecentlyOpened(recentlyOpened, paths);
return this.saveRecentlyOpened(recentlyOpened);
}
private doRemoveRecentlyOpened(recentlyOpened: IRecentlyOpened, paths: URI[]): void {
recentlyOpened.files = recentlyOpened.files.filter(file => {
return !paths.some(path => path.toString() === file.fileUri.toString());
});
recentlyOpened.workspaces = recentlyOpened.workspaces.filter(workspace => {
return !paths.some(path => path.toString() === (isRecentFolder(workspace) ? workspace.folderUri.toString() : workspace.workspace.configPath.toString()));
});
}
private async saveRecentlyOpened(data: IRecentlyOpened): Promise<void> {
return this.storageService.store(BrowserWorkspacesService.RECENTLY_OPENED_KEY, JSON.stringify(toStoreData(data)), StorageScope.GLOBAL, StorageTarget.USER);
}
async clearRecentlyOpened(): Promise<void> {
this.storageService.remove(BrowserWorkspacesService.RECENTLY_OPENED_KEY, StorageScope.GLOBAL);
}
//#endregion
//#region Workspace Management
async enterWorkspace(path: URI): Promise<IEnterWorkspaceResult | undefined> {
return { workspace: await this.getWorkspaceIdentifier(path) };
}
async createUntitledWorkspace(folders?: IWorkspaceFolderCreationData[], remoteAuthority?: string): Promise<IWorkspaceIdentifier> {
const randomId = (Date.now() + Math.round(Math.random() * 1000)).toString();
const newUntitledWorkspacePath = joinPath(this.environmentService.untitledWorkspacesHome, `Untitled-${randomId}.${WORKSPACE_EXTENSION}`);
// Build array of workspace folders to store
const storedWorkspaceFolder: IStoredWorkspaceFolder[] = [];
if (folders) {
for (const folder of folders) {
storedWorkspaceFolder.push(getStoredWorkspaceFolder(folder.uri, true, folder.name, this.environmentService.untitledWorkspacesHome, !isWindows, this.uriIdentityService.extUri));
}
}
// Store at untitled workspaces location
const storedWorkspace: IStoredWorkspace = { folders: storedWorkspaceFolder, remoteAuthority };
await this.fileService.writeFile(newUntitledWorkspacePath, VSBuffer.fromString(JSON.stringify(storedWorkspace, null, '\t')));
return this.getWorkspaceIdentifier(newUntitledWorkspacePath);
}
async deleteUntitledWorkspace(workspace: IWorkspaceIdentifier): Promise<void> {
try {
await this.fileService.del(workspace.configPath);
} catch (error) {
if ((<FileOperationError>error).fileOperationResult !== FileOperationResult.FILE_NOT_FOUND) {
throw error; // re-throw any other error than file not found which is OK
}
}
}
async getWorkspaceIdentifier(workspacePath: URI): Promise<IWorkspaceIdentifier> {
return getWorkspaceIdentifier(workspacePath);
}
//#endregion
//#region Dirty Workspaces
async getDirtyWorkspaces(): Promise<Array<IWorkspaceIdentifier | URI>> {
return []; // Currently not supported in web
}
//#endregion
}
registerSingleton(IWorkspacesService, BrowserWorkspacesService, true);
| src/vs/workbench/services/workspaces/browser/workspacesService.ts | 0 | https://github.com/microsoft/vscode/commit/f18b29e132039246caebd4c6b52fcff06265c04d | [
0.0007998807705007493,
0.00021258984634187073,
0.000161512682097964,
0.00017190157086588442,
0.00014516983355861157
] |
{
"id": 1,
"code_window": [
"\treadonly onDidFocusRepository = this._onDidFocusRepository.event;\n",
"\n",
"\tconstructor(\n",
"\t\t@ISCMService private readonly scmService: ISCMService,\n",
"\t\t@IInstantiationService instantiationService: IInstantiationService,\n",
"\t\t@IStorageService private readonly storageService: IStorageService,\n",
"\t\t@ILogService private readonly logService: ILogService\n",
"\t) {\n",
"\t\tthis.menus = instantiationService.createInstance(SCMMenus);\n",
"\n",
"\t\tscmService.onDidAddRepository(this.onDidAddRepository, this, this.disposables);\n",
"\t\tscmService.onDidRemoveRepository(this.onDidRemoveRepository, this, this.disposables);\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\t@IStorageService private readonly storageService: IStorageService\n"
],
"file_path": "src/vs/workbench/contrib/scm/browser/scmViewService.ts",
"type": "replace",
"edit_start_line_idx": 102
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import { quickSelect } from 'vs/base/common/arrays';
import { CharCode } from 'vs/base/common/charCode';
import { anyScore, fuzzyScore, FuzzyScore, fuzzyScoreGracefulAggressive, FuzzyScorer } from 'vs/base/common/filters';
import { compareIgnoreCase } from 'vs/base/common/strings';
import { InternalSuggestOptions } from 'vs/editor/common/config/editorOptions';
import { CompletionItemKind, CompletionItemProvider } from 'vs/editor/common/modes';
import { WordDistance } from 'vs/editor/contrib/suggest/wordDistance';
import { CompletionItem } from './suggest';
type StrictCompletionItem = Required<CompletionItem>;
export interface ICompletionStats {
pLabelLen: number;
}
export class LineContext {
constructor(
readonly leadingLineContent: string,
readonly characterCountDelta: number,
) { }
}
const enum Refilter {
Nothing = 0,
All = 1,
Incr = 2
}
/**
* Sorted, filtered completion view model
* */
export class CompletionModel {
private readonly _items: CompletionItem[];
private readonly _column: number;
private readonly _wordDistance: WordDistance;
private readonly _options: InternalSuggestOptions;
private readonly _snippetCompareFn = CompletionModel._compareCompletionItems;
private _lineContext: LineContext;
private _refilterKind: Refilter;
private _filteredItems?: StrictCompletionItem[];
private _providerInfo?: Map<CompletionItemProvider, boolean>;
private _stats?: ICompletionStats;
constructor(
items: CompletionItem[],
column: number,
lineContext: LineContext,
wordDistance: WordDistance,
options: InternalSuggestOptions,
snippetSuggestions: 'top' | 'bottom' | 'inline' | 'none',
readonly clipboardText: string | undefined
) {
this._items = items;
this._column = column;
this._wordDistance = wordDistance;
this._options = options;
this._refilterKind = Refilter.All;
this._lineContext = lineContext;
if (snippetSuggestions === 'top') {
this._snippetCompareFn = CompletionModel._compareCompletionItemsSnippetsUp;
} else if (snippetSuggestions === 'bottom') {
this._snippetCompareFn = CompletionModel._compareCompletionItemsSnippetsDown;
}
}
get lineContext(): LineContext {
return this._lineContext;
}
set lineContext(value: LineContext) {
if (this._lineContext.leadingLineContent !== value.leadingLineContent
|| this._lineContext.characterCountDelta !== value.characterCountDelta
) {
this._refilterKind = this._lineContext.characterCountDelta < value.characterCountDelta && this._filteredItems ? Refilter.Incr : Refilter.All;
this._lineContext = value;
}
}
get items(): CompletionItem[] {
this._ensureCachedState();
return this._filteredItems!;
}
get allProvider(): IterableIterator<CompletionItemProvider> {
this._ensureCachedState();
return this._providerInfo!.keys();
}
get incomplete(): Set<CompletionItemProvider> {
this._ensureCachedState();
const result = new Set<CompletionItemProvider>();
for (let [provider, incomplete] of this._providerInfo!) {
if (incomplete) {
result.add(provider);
}
}
return result;
}
adopt(except: Set<CompletionItemProvider>): CompletionItem[] {
let res: CompletionItem[] = [];
for (let i = 0; i < this._items.length;) {
if (!except.has(this._items[i].provider)) {
res.push(this._items[i]);
// unordered removed
this._items[i] = this._items[this._items.length - 1];
this._items.pop();
} else {
// continue with next item
i++;
}
}
this._refilterKind = Refilter.All;
return res;
}
get stats(): ICompletionStats {
this._ensureCachedState();
return this._stats!;
}
private _ensureCachedState(): void {
if (this._refilterKind !== Refilter.Nothing) {
this._createCachedState();
}
}
private _createCachedState(): void {
this._providerInfo = new Map();
const labelLengths: number[] = [];
const { leadingLineContent, characterCountDelta } = this._lineContext;
let word = '';
let wordLow = '';
// incrementally filter less
const source = this._refilterKind === Refilter.All ? this._items : this._filteredItems!;
const target: StrictCompletionItem[] = [];
// picks a score function based on the number of
// items that we have to score/filter and based on the
// user-configuration
const scoreFn: FuzzyScorer = (!this._options.filterGraceful || source.length > 2000) ? fuzzyScore : fuzzyScoreGracefulAggressive;
for (let i = 0; i < source.length; i++) {
const item = source[i];
if (item.isInvalid) {
continue; // SKIP invalid items
}
// collect all support, know if their result is incomplete
this._providerInfo.set(item.provider, Boolean(item.container.incomplete));
// 'word' is that remainder of the current line that we
// filter and score against. In theory each suggestion uses a
// different word, but in practice not - that's why we cache
const overwriteBefore = item.position.column - item.editStart.column;
const wordLen = overwriteBefore + characterCountDelta - (item.position.column - this._column);
if (word.length !== wordLen) {
word = wordLen === 0 ? '' : leadingLineContent.slice(-wordLen);
wordLow = word.toLowerCase();
}
// remember the word against which this item was
// scored
item.word = word;
if (wordLen === 0) {
// when there is nothing to score against, don't
// event try to do. Use a const rank and rely on
// the fallback-sort using the initial sort order.
// use a score of `-100` because that is out of the
// bound of values `fuzzyScore` will return
item.score = FuzzyScore.Default;
} else {
// skip word characters that are whitespace until
// we have hit the replace range (overwriteBefore)
let wordPos = 0;
while (wordPos < overwriteBefore) {
const ch = word.charCodeAt(wordPos);
if (ch === CharCode.Space || ch === CharCode.Tab) {
wordPos += 1;
} else {
break;
}
}
if (wordPos >= wordLen) {
// the wordPos at which scoring starts is the whole word
// and therefore the same rules as not having a word apply
item.score = FuzzyScore.Default;
} else if (typeof item.completion.filterText === 'string') {
// when there is a `filterText` it must match the `word`.
// if it matches we check with the label to compute highlights
// and if that doesn't yield a result we have no highlights,
// despite having the match
let match = scoreFn(word, wordLow, wordPos, item.completion.filterText, item.filterTextLow!, 0, false);
if (!match) {
continue; // NO match
}
if (compareIgnoreCase(item.completion.filterText, item.textLabel) === 0) {
// filterText and label are actually the same -> use good highlights
item.score = match;
} else {
// re-run the scorer on the label in the hope of a result BUT use the rank
// of the filterText-match
item.score = anyScore(word, wordLow, wordPos, item.textLabel, item.labelLow, 0);
item.score[0] = match[0]; // use score from filterText
}
} else {
// by default match `word` against the `label`
let match = scoreFn(word, wordLow, wordPos, item.textLabel, item.labelLow, 0, false);
if (!match) {
continue; // NO match
}
item.score = match;
}
}
item.idx = i;
item.distance = this._wordDistance.distance(item.position, item.completion);
target.push(item as StrictCompletionItem);
// update stats
labelLengths.push(item.textLabel.length);
}
this._filteredItems = target.sort(this._snippetCompareFn);
this._refilterKind = Refilter.Nothing;
this._stats = {
pLabelLen: labelLengths.length ?
quickSelect(labelLengths.length - .85, labelLengths, (a, b) => a - b)
: 0
};
}
private static _compareCompletionItems(a: StrictCompletionItem, b: StrictCompletionItem): number {
if (a.score[0] > b.score[0]) {
return -1;
} else if (a.score[0] < b.score[0]) {
return 1;
} else if (a.distance < b.distance) {
return -1;
} else if (a.distance > b.distance) {
return 1;
} else if (a.idx < b.idx) {
return -1;
} else if (a.idx > b.idx) {
return 1;
} else {
return 0;
}
}
private static _compareCompletionItemsSnippetsDown(a: StrictCompletionItem, b: StrictCompletionItem): number {
if (a.completion.kind !== b.completion.kind) {
if (a.completion.kind === CompletionItemKind.Snippet) {
return 1;
} else if (b.completion.kind === CompletionItemKind.Snippet) {
return -1;
}
}
return CompletionModel._compareCompletionItems(a, b);
}
private static _compareCompletionItemsSnippetsUp(a: StrictCompletionItem, b: StrictCompletionItem): number {
if (a.completion.kind !== b.completion.kind) {
if (a.completion.kind === CompletionItemKind.Snippet) {
return -1;
} else if (b.completion.kind === CompletionItemKind.Snippet) {
return 1;
}
}
return CompletionModel._compareCompletionItems(a, b);
}
}
| src/vs/editor/contrib/suggest/completionModel.ts | 0 | https://github.com/microsoft/vscode/commit/f18b29e132039246caebd4c6b52fcff06265c04d | [
0.00021186434605624527,
0.00017514228238724172,
0.00016491064161527902,
0.00017419553478248417,
0.0000074133736234216485
] |
{
"id": 2,
"code_window": [
"\t\tstorageService.onWillSaveState(this.onWillSaveState, this, this.disposables);\n",
"\t}\n",
"\n",
"\tprivate onDidAddRepository(repository: ISCMRepository): void {\n",
"\t\tthis.logService.trace('SCMViewService#onDidAddRepository', getProviderStorageKey(repository.provider));\n",
"\n",
"\t\tif (!this.didFinishLoading) {\n",
"\t\t\tthis.eventuallyFinishLoading();\n",
"\t\t}\n",
"\n",
"\t\tlet removed: Iterable<ISCMRepository> = Iterable.empty();\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [],
"file_path": "src/vs/workbench/contrib/scm/browser/scmViewService.ts",
"type": "replace",
"edit_start_line_idx": 125
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import { workspace, WorkspaceFoldersChangeEvent, Uri, window, Event, EventEmitter, QuickPickItem, Disposable, SourceControl, SourceControlResourceGroup, TextEditor, Memento, OutputChannel, commands } from 'vscode';
import { Repository, RepositoryState } from './repository';
import { memoize, sequentialize, debounce } from './decorators';
import { dispose, anyEvent, filterEvent, isDescendant, pathEquals, toDisposable, eventToPromise } from './util';
import { Git } from './git';
import * as path from 'path';
import * as fs from 'fs';
import * as nls from 'vscode-nls';
import { fromGitUri } from './uri';
import { APIState as State, RemoteSourceProvider, CredentialsProvider, PushErrorHandler, PublishEvent } from './api/git';
import { Askpass } from './askpass';
import { IRemoteSourceProviderRegistry } from './remoteProvider';
import { IPushErrorHandlerRegistry } from './pushError';
import { ApiRepository } from './api/api1';
const localize = nls.loadMessageBundle();
class RepositoryPick implements QuickPickItem {
@memoize get label(): string {
return path.basename(this.repository.root);
}
@memoize get description(): string {
return [this.repository.headLabel, this.repository.syncLabel]
.filter(l => !!l)
.join(' ');
}
constructor(public readonly repository: Repository, public readonly index: number) { }
}
export interface ModelChangeEvent {
repository: Repository;
uri: Uri;
}
export interface OriginalResourceChangeEvent {
repository: Repository;
uri: Uri;
}
interface OpenRepository extends Disposable {
repository: Repository;
}
export class Model implements IRemoteSourceProviderRegistry, IPushErrorHandlerRegistry {
private _onDidOpenRepository = new EventEmitter<Repository>();
readonly onDidOpenRepository: Event<Repository> = this._onDidOpenRepository.event;
private _onDidCloseRepository = new EventEmitter<Repository>();
readonly onDidCloseRepository: Event<Repository> = this._onDidCloseRepository.event;
private _onDidChangeRepository = new EventEmitter<ModelChangeEvent>();
readonly onDidChangeRepository: Event<ModelChangeEvent> = this._onDidChangeRepository.event;
private _onDidChangeOriginalResource = new EventEmitter<OriginalResourceChangeEvent>();
readonly onDidChangeOriginalResource: Event<OriginalResourceChangeEvent> = this._onDidChangeOriginalResource.event;
private openRepositories: OpenRepository[] = [];
get repositories(): Repository[] { return this.openRepositories.map(r => r.repository); }
private possibleGitRepositoryPaths = new Set<string>();
private _onDidChangeState = new EventEmitter<State>();
readonly onDidChangeState = this._onDidChangeState.event;
private _onDidPublish = new EventEmitter<PublishEvent>();
readonly onDidPublish = this._onDidPublish.event;
firePublishEvent(repository: Repository, branch?: string) {
this._onDidPublish.fire({ repository: new ApiRepository(repository), branch: branch });
}
private _state: State = 'uninitialized';
get state(): State { return this._state; }
setState(state: State): void {
this._state = state;
this._onDidChangeState.fire(state);
commands.executeCommand('setContext', 'git.state', state);
}
@memoize
get isInitialized(): Promise<void> {
if (this._state === 'initialized') {
return Promise.resolve();
}
return eventToPromise(filterEvent(this.onDidChangeState, s => s === 'initialized')) as Promise<any>;
}
private remoteSourceProviders = new Set<RemoteSourceProvider>();
private _onDidAddRemoteSourceProvider = new EventEmitter<RemoteSourceProvider>();
readonly onDidAddRemoteSourceProvider = this._onDidAddRemoteSourceProvider.event;
private _onDidRemoveRemoteSourceProvider = new EventEmitter<RemoteSourceProvider>();
readonly onDidRemoveRemoteSourceProvider = this._onDidRemoveRemoteSourceProvider.event;
private pushErrorHandlers = new Set<PushErrorHandler>();
private disposables: Disposable[] = [];
constructor(readonly git: Git, private readonly askpass: Askpass, private globalState: Memento, private outputChannel: OutputChannel) {
workspace.onDidChangeWorkspaceFolders(this.onDidChangeWorkspaceFolders, this, this.disposables);
window.onDidChangeVisibleTextEditors(this.onDidChangeVisibleTextEditors, this, this.disposables);
workspace.onDidChangeConfiguration(this.onDidChangeConfiguration, this, this.disposables);
const fsWatcher = workspace.createFileSystemWatcher('**');
this.disposables.push(fsWatcher);
const onWorkspaceChange = anyEvent(fsWatcher.onDidChange, fsWatcher.onDidCreate, fsWatcher.onDidDelete);
const onGitRepositoryChange = filterEvent(onWorkspaceChange, uri => /\/\.git/.test(uri.path));
const onPossibleGitRepositoryChange = filterEvent(onGitRepositoryChange, uri => !this.getRepository(uri));
onPossibleGitRepositoryChange(this.onPossibleGitRepositoryChange, this, this.disposables);
this.setState('uninitialized');
this.doInitialScan().finally(() => this.setState('initialized'));
}
private async doInitialScan(): Promise<void> {
await Promise.all([
this.onDidChangeWorkspaceFolders({ added: workspace.workspaceFolders || [], removed: [] }),
this.onDidChangeVisibleTextEditors(window.visibleTextEditors),
this.scanWorkspaceFolders()
]);
}
/**
* Scans the first level of each workspace folder, looking
* for git repositories.
*/
private async scanWorkspaceFolders(): Promise<void> {
const config = workspace.getConfiguration('git');
const autoRepositoryDetection = config.get<boolean | 'subFolders' | 'openEditors'>('autoRepositoryDetection');
if (autoRepositoryDetection !== true && autoRepositoryDetection !== 'subFolders') {
return;
}
await Promise.all((workspace.workspaceFolders || []).map(async folder => {
const root = folder.uri.fsPath;
const children = await new Promise<string[]>((c, e) => fs.readdir(root, (err, r) => err ? e(err) : c(r)));
const subfolders = new Set(children.filter(child => child !== '.git').map(child => path.join(root, child)));
const scanPaths = (workspace.isTrusted ? workspace.getConfiguration('git', folder.uri) : config).get<string[]>('scanRepositories') || [];
for (const scanPath of scanPaths) {
if (scanPath !== '.git') {
continue;
}
if (path.isAbsolute(scanPath)) {
console.warn(localize('not supported', "Absolute paths not supported in 'git.scanRepositories' setting."));
continue;
}
subfolders.add(path.join(root, scanPath));
}
await Promise.all([...subfolders].map(f => this.openRepository(f)));
}));
}
private onPossibleGitRepositoryChange(uri: Uri): void {
const config = workspace.getConfiguration('git');
const autoRepositoryDetection = config.get<boolean | 'subFolders' | 'openEditors'>('autoRepositoryDetection');
if (autoRepositoryDetection === false) {
return;
}
this.eventuallyScanPossibleGitRepository(uri.fsPath.replace(/\.git.*$/, ''));
}
private eventuallyScanPossibleGitRepository(path: string) {
this.possibleGitRepositoryPaths.add(path);
this.eventuallyScanPossibleGitRepositories();
}
@debounce(500)
private eventuallyScanPossibleGitRepositories(): void {
for (const path of this.possibleGitRepositoryPaths) {
this.openRepository(path);
}
this.possibleGitRepositoryPaths.clear();
}
private async onDidChangeWorkspaceFolders({ added, removed }: WorkspaceFoldersChangeEvent): Promise<void> {
const possibleRepositoryFolders = added
.filter(folder => !this.getOpenRepository(folder.uri));
const activeRepositoriesList = window.visibleTextEditors
.map(editor => this.getRepository(editor.document.uri))
.filter(repository => !!repository) as Repository[];
const activeRepositories = new Set<Repository>(activeRepositoriesList);
const openRepositoriesToDispose = removed
.map(folder => this.getOpenRepository(folder.uri))
.filter(r => !!r)
.filter(r => !activeRepositories.has(r!.repository))
.filter(r => !(workspace.workspaceFolders || []).some(f => isDescendant(f.uri.fsPath, r!.repository.root))) as OpenRepository[];
openRepositoriesToDispose.forEach(r => r.dispose());
await Promise.all(possibleRepositoryFolders.map(p => this.openRepository(p.uri.fsPath)));
}
private onDidChangeConfiguration(): void {
const possibleRepositoryFolders = (workspace.workspaceFolders || [])
.filter(folder => workspace.getConfiguration('git', folder.uri).get<boolean>('enabled') === true)
.filter(folder => !this.getOpenRepository(folder.uri));
const openRepositoriesToDispose = this.openRepositories
.map(repository => ({ repository, root: Uri.file(repository.repository.root) }))
.filter(({ root }) => workspace.getConfiguration('git', root).get<boolean>('enabled') !== true)
.map(({ repository }) => repository);
possibleRepositoryFolders.forEach(p => this.openRepository(p.uri.fsPath));
openRepositoriesToDispose.forEach(r => r.dispose());
}
private async onDidChangeVisibleTextEditors(editors: readonly TextEditor[]): Promise<void> {
if (!workspace.isTrusted) {
return;
}
const config = workspace.getConfiguration('git');
const autoRepositoryDetection = config.get<boolean | 'subFolders' | 'openEditors'>('autoRepositoryDetection');
if (autoRepositoryDetection !== true && autoRepositoryDetection !== 'openEditors') {
return;
}
await Promise.all(editors.map(async editor => {
const uri = editor.document.uri;
if (uri.scheme !== 'file') {
return;
}
const repository = this.getRepository(uri);
if (repository) {
return;
}
await this.openRepository(path.dirname(uri.fsPath));
}));
}
@sequentialize
async openRepository(repoPath: string): Promise<void> {
if (this.getRepository(repoPath)) {
return;
}
const config = workspace.getConfiguration('git', Uri.file(repoPath));
const enabled = config.get<boolean>('enabled') === true;
if (!enabled) {
return;
}
if (!workspace.isTrusted) {
// Check if the folder is a bare repo: if it has a file named HEAD && `rev-parse --show -cdup` is empty
try {
fs.accessSync(path.join(repoPath, 'HEAD'), fs.constants.F_OK);
const result = await this.git.exec(repoPath, ['-C', repoPath, 'rev-parse', '--show-cdup'], { log: false });
if (result.stderr.trim() === '' && result.stdout.trim() === '') {
return;
}
} catch {
// If this throw, we should be good to open the repo (e.g. HEAD doesn't exist)
}
}
try {
const rawRoot = await this.git.getRepositoryRoot(repoPath);
// This can happen whenever `path` has the wrong case sensitivity in
// case insensitive file systems
// https://github.com/microsoft/vscode/issues/33498
const repositoryRoot = Uri.file(rawRoot).fsPath;
if (this.getRepository(repositoryRoot)) {
return;
}
if (this.shouldRepositoryBeIgnored(rawRoot)) {
return;
}
const dotGit = await this.git.getRepositoryDotGit(repositoryRoot);
const repository = new Repository(this.git.open(repositoryRoot, dotGit), this, this, this.globalState, this.outputChannel);
this.open(repository);
await repository.status();
} catch (ex) {
// noop
this.outputChannel.appendLine(`Opening repository for path='${repoPath}' failed; ex=${ex}`);
}
}
private shouldRepositoryBeIgnored(repositoryRoot: string): boolean {
const config = workspace.getConfiguration('git');
const ignoredRepos = config.get<string[]>('ignoredRepositories') || [];
for (const ignoredRepo of ignoredRepos) {
if (path.isAbsolute(ignoredRepo)) {
if (pathEquals(ignoredRepo, repositoryRoot)) {
return true;
}
} else {
for (const folder of workspace.workspaceFolders || []) {
if (pathEquals(path.join(folder.uri.fsPath, ignoredRepo), repositoryRoot)) {
return true;
}
}
}
}
return false;
}
private open(repository: Repository): void {
this.outputChannel.appendLine(`Open repository: ${repository.root}`);
const onDidDisappearRepository = filterEvent(repository.onDidChangeState, state => state === RepositoryState.Disposed);
const disappearListener = onDidDisappearRepository(() => dispose());
const changeListener = repository.onDidChangeRepository(uri => this._onDidChangeRepository.fire({ repository, uri }));
const originalResourceChangeListener = repository.onDidChangeOriginalResource(uri => this._onDidChangeOriginalResource.fire({ repository, uri }));
const shouldDetectSubmodules = workspace
.getConfiguration('git', Uri.file(repository.root))
.get<boolean>('detectSubmodules') as boolean;
const submodulesLimit = workspace
.getConfiguration('git', Uri.file(repository.root))
.get<number>('detectSubmodulesLimit') as number;
const checkForSubmodules = () => {
if (!shouldDetectSubmodules) {
return;
}
if (repository.submodules.length > submodulesLimit) {
window.showWarningMessage(localize('too many submodules', "The '{0}' repository has {1} submodules which won't be opened automatically. You can still open each one individually by opening a file within.", path.basename(repository.root), repository.submodules.length));
statusListener.dispose();
}
repository.submodules
.slice(0, submodulesLimit)
.map(r => path.join(repository.root, r.path))
.forEach(p => this.eventuallyScanPossibleGitRepository(p));
};
const statusListener = repository.onDidRunGitStatus(checkForSubmodules);
checkForSubmodules();
const dispose = () => {
disappearListener.dispose();
changeListener.dispose();
originalResourceChangeListener.dispose();
statusListener.dispose();
repository.dispose();
this.openRepositories = this.openRepositories.filter(e => e !== openRepository);
this._onDidCloseRepository.fire(repository);
};
const openRepository = { repository, dispose };
this.openRepositories.push(openRepository);
this._onDidOpenRepository.fire(repository);
}
close(repository: Repository): void {
const openRepository = this.getOpenRepository(repository);
if (!openRepository) {
return;
}
this.outputChannel.appendLine(`Close repository: ${repository.root}`);
openRepository.dispose();
}
async pickRepository(): Promise<Repository | undefined> {
if (this.openRepositories.length === 0) {
throw new Error(localize('no repositories', "There are no available repositories"));
}
const picks = this.openRepositories.map((e, index) => new RepositoryPick(e.repository, index));
const active = window.activeTextEditor;
const repository = active && this.getRepository(active.document.fileName);
const index = picks.findIndex(pick => pick.repository === repository);
// Move repository pick containing the active text editor to appear first
if (index > -1) {
picks.unshift(...picks.splice(index, 1));
}
const placeHolder = localize('pick repo', "Choose a repository");
const pick = await window.showQuickPick(picks, { placeHolder });
return pick && pick.repository;
}
getRepository(sourceControl: SourceControl): Repository | undefined;
getRepository(resourceGroup: SourceControlResourceGroup): Repository | undefined;
getRepository(path: string): Repository | undefined;
getRepository(resource: Uri): Repository | undefined;
getRepository(hint: any): Repository | undefined {
const liveRepository = this.getOpenRepository(hint);
return liveRepository && liveRepository.repository;
}
private getOpenRepository(repository: Repository): OpenRepository | undefined;
private getOpenRepository(sourceControl: SourceControl): OpenRepository | undefined;
private getOpenRepository(resourceGroup: SourceControlResourceGroup): OpenRepository | undefined;
private getOpenRepository(path: string): OpenRepository | undefined;
private getOpenRepository(resource: Uri): OpenRepository | undefined;
private getOpenRepository(hint: any): OpenRepository | undefined {
if (!hint) {
return undefined;
}
if (hint instanceof Repository) {
return this.openRepositories.filter(r => r.repository === hint)[0];
}
if (typeof hint === 'string') {
hint = Uri.file(hint);
}
if (hint instanceof Uri) {
let resourcePath: string;
if (hint.scheme === 'git') {
resourcePath = fromGitUri(hint).path;
} else {
resourcePath = hint.fsPath;
}
outer:
for (const liveRepository of this.openRepositories.sort((a, b) => b.repository.root.length - a.repository.root.length)) {
if (!isDescendant(liveRepository.repository.root, resourcePath)) {
continue;
}
for (const submodule of liveRepository.repository.submodules) {
const submoduleRoot = path.join(liveRepository.repository.root, submodule.path);
if (isDescendant(submoduleRoot, resourcePath)) {
continue outer;
}
}
return liveRepository;
}
return undefined;
}
for (const liveRepository of this.openRepositories) {
const repository = liveRepository.repository;
if (hint === repository.sourceControl) {
return liveRepository;
}
if (hint === repository.mergeGroup || hint === repository.indexGroup || hint === repository.workingTreeGroup) {
return liveRepository;
}
}
return undefined;
}
getRepositoryForSubmodule(submoduleUri: Uri): Repository | undefined {
for (const repository of this.repositories) {
for (const submodule of repository.submodules) {
const submodulePath = path.join(repository.root, submodule.path);
if (submodulePath === submoduleUri.fsPath) {
return repository;
}
}
}
return undefined;
}
registerRemoteSourceProvider(provider: RemoteSourceProvider): Disposable {
this.remoteSourceProviders.add(provider);
this._onDidAddRemoteSourceProvider.fire(provider);
return toDisposable(() => {
this.remoteSourceProviders.delete(provider);
this._onDidRemoveRemoteSourceProvider.fire(provider);
});
}
registerCredentialsProvider(provider: CredentialsProvider): Disposable {
return this.askpass.registerCredentialsProvider(provider);
}
getRemoteProviders(): RemoteSourceProvider[] {
return [...this.remoteSourceProviders.values()];
}
registerPushErrorHandler(handler: PushErrorHandler): Disposable {
this.pushErrorHandlers.add(handler);
return toDisposable(() => this.pushErrorHandlers.delete(handler));
}
getPushErrorHandlers(): PushErrorHandler[] {
return [...this.pushErrorHandlers];
}
dispose(): void {
const openRepositories = [...this.openRepositories];
openRepositories.forEach(r => r.dispose());
this.openRepositories = [];
this.possibleGitRepositoryPaths.clear();
this.disposables = dispose(this.disposables);
}
}
| extensions/git/src/model.ts | 1 | https://github.com/microsoft/vscode/commit/f18b29e132039246caebd4c6b52fcff06265c04d | [
0.832467257976532,
0.01722363568842411,
0.00016433079144917428,
0.00018670526333153248,
0.11212596297264099
] |
{
"id": 2,
"code_window": [
"\t\tstorageService.onWillSaveState(this.onWillSaveState, this, this.disposables);\n",
"\t}\n",
"\n",
"\tprivate onDidAddRepository(repository: ISCMRepository): void {\n",
"\t\tthis.logService.trace('SCMViewService#onDidAddRepository', getProviderStorageKey(repository.provider));\n",
"\n",
"\t\tif (!this.didFinishLoading) {\n",
"\t\t\tthis.eventuallyFinishLoading();\n",
"\t\t}\n",
"\n",
"\t\tlet removed: Iterable<ISCMRepository> = Iterable.empty();\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [],
"file_path": "src/vs/workbench/contrib/scm/browser/scmViewService.ts",
"type": "replace",
"edit_start_line_idx": 125
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import * as assert from 'assert';
import { KeyChord, KeyCode, KeyMod, ScanCode } from 'vs/base/common/keyCodes';
import { SimpleKeybinding, createKeybinding, ScanCodeBinding } from 'vs/base/common/keybindings';
import { KeybindingParser } from 'vs/base/common/keybindingParser';
import { OperatingSystem } from 'vs/base/common/platform';
import { IUserFriendlyKeybinding } from 'vs/platform/keybinding/common/keybinding';
import { USLayoutResolvedKeybinding } from 'vs/platform/keybinding/common/usLayoutResolvedKeybinding';
import { KeybindingIO } from 'vs/workbench/services/keybinding/common/keybindingIO';
suite('keybindingIO', () => {
test('serialize/deserialize', () => {
function testOneSerialization(keybinding: number, expected: string, msg: string, OS: OperatingSystem): void {
let usLayoutResolvedKeybinding = new USLayoutResolvedKeybinding(createKeybinding(keybinding, OS)!, OS);
let actualSerialized = usLayoutResolvedKeybinding.getUserSettingsLabel();
assert.strictEqual(actualSerialized, expected, expected + ' - ' + msg);
}
function testSerialization(keybinding: number, expectedWin: string, expectedMac: string, expectedLinux: string): void {
testOneSerialization(keybinding, expectedWin, 'win', OperatingSystem.Windows);
testOneSerialization(keybinding, expectedMac, 'mac', OperatingSystem.Macintosh);
testOneSerialization(keybinding, expectedLinux, 'linux', OperatingSystem.Linux);
}
function testOneDeserialization(keybinding: string, _expected: number, msg: string, OS: OperatingSystem): void {
let actualDeserialized = KeybindingParser.parseKeybinding(keybinding, OS);
let expected = createKeybinding(_expected, OS);
assert.deepStrictEqual(actualDeserialized, expected, keybinding + ' - ' + msg);
}
function testDeserialization(inWin: string, inMac: string, inLinux: string, expected: number): void {
testOneDeserialization(inWin, expected, 'win', OperatingSystem.Windows);
testOneDeserialization(inMac, expected, 'mac', OperatingSystem.Macintosh);
testOneDeserialization(inLinux, expected, 'linux', OperatingSystem.Linux);
}
function testRoundtrip(keybinding: number, expectedWin: string, expectedMac: string, expectedLinux: string): void {
testSerialization(keybinding, expectedWin, expectedMac, expectedLinux);
testDeserialization(expectedWin, expectedMac, expectedLinux, keybinding);
}
testRoundtrip(KeyCode.Digit0, '0', '0', '0');
testRoundtrip(KeyCode.KeyA, 'a', 'a', 'a');
testRoundtrip(KeyCode.UpArrow, 'up', 'up', 'up');
testRoundtrip(KeyCode.RightArrow, 'right', 'right', 'right');
testRoundtrip(KeyCode.DownArrow, 'down', 'down', 'down');
testRoundtrip(KeyCode.LeftArrow, 'left', 'left', 'left');
// one modifier
testRoundtrip(KeyMod.Alt | KeyCode.KeyA, 'alt+a', 'alt+a', 'alt+a');
testRoundtrip(KeyMod.CtrlCmd | KeyCode.KeyA, 'ctrl+a', 'cmd+a', 'ctrl+a');
testRoundtrip(KeyMod.Shift | KeyCode.KeyA, 'shift+a', 'shift+a', 'shift+a');
testRoundtrip(KeyMod.WinCtrl | KeyCode.KeyA, 'win+a', 'ctrl+a', 'meta+a');
// two modifiers
testRoundtrip(KeyMod.CtrlCmd | KeyMod.Alt | KeyCode.KeyA, 'ctrl+alt+a', 'alt+cmd+a', 'ctrl+alt+a');
testRoundtrip(KeyMod.CtrlCmd | KeyMod.Shift | KeyCode.KeyA, 'ctrl+shift+a', 'shift+cmd+a', 'ctrl+shift+a');
testRoundtrip(KeyMod.CtrlCmd | KeyMod.WinCtrl | KeyCode.KeyA, 'ctrl+win+a', 'ctrl+cmd+a', 'ctrl+meta+a');
testRoundtrip(KeyMod.Shift | KeyMod.Alt | KeyCode.KeyA, 'shift+alt+a', 'shift+alt+a', 'shift+alt+a');
testRoundtrip(KeyMod.Shift | KeyMod.WinCtrl | KeyCode.KeyA, 'shift+win+a', 'ctrl+shift+a', 'shift+meta+a');
testRoundtrip(KeyMod.Alt | KeyMod.WinCtrl | KeyCode.KeyA, 'alt+win+a', 'ctrl+alt+a', 'alt+meta+a');
// three modifiers
testRoundtrip(KeyMod.CtrlCmd | KeyMod.Shift | KeyMod.Alt | KeyCode.KeyA, 'ctrl+shift+alt+a', 'shift+alt+cmd+a', 'ctrl+shift+alt+a');
testRoundtrip(KeyMod.CtrlCmd | KeyMod.Shift | KeyMod.WinCtrl | KeyCode.KeyA, 'ctrl+shift+win+a', 'ctrl+shift+cmd+a', 'ctrl+shift+meta+a');
testRoundtrip(KeyMod.Shift | KeyMod.Alt | KeyMod.WinCtrl | KeyCode.KeyA, 'shift+alt+win+a', 'ctrl+shift+alt+a', 'shift+alt+meta+a');
// all modifiers
testRoundtrip(KeyMod.CtrlCmd | KeyMod.Shift | KeyMod.Alt | KeyMod.WinCtrl | KeyCode.KeyA, 'ctrl+shift+alt+win+a', 'ctrl+shift+alt+cmd+a', 'ctrl+shift+alt+meta+a');
// chords
testRoundtrip(KeyChord(KeyMod.CtrlCmd | KeyCode.KeyA, KeyMod.CtrlCmd | KeyCode.KeyA), 'ctrl+a ctrl+a', 'cmd+a cmd+a', 'ctrl+a ctrl+a');
testRoundtrip(KeyChord(KeyMod.CtrlCmd | KeyCode.UpArrow, KeyMod.CtrlCmd | KeyCode.UpArrow), 'ctrl+up ctrl+up', 'cmd+up cmd+up', 'ctrl+up ctrl+up');
// OEM keys
testRoundtrip(KeyCode.Semicolon, ';', ';', ';');
testRoundtrip(KeyCode.Equal, '=', '=', '=');
testRoundtrip(KeyCode.Comma, ',', ',', ',');
testRoundtrip(KeyCode.Minus, '-', '-', '-');
testRoundtrip(KeyCode.Period, '.', '.', '.');
testRoundtrip(KeyCode.Slash, '/', '/', '/');
testRoundtrip(KeyCode.Backquote, '`', '`', '`');
testRoundtrip(KeyCode.ABNT_C1, 'abnt_c1', 'abnt_c1', 'abnt_c1');
testRoundtrip(KeyCode.ABNT_C2, 'abnt_c2', 'abnt_c2', 'abnt_c2');
testRoundtrip(KeyCode.BracketLeft, '[', '[', '[');
testRoundtrip(KeyCode.Backslash, '\\', '\\', '\\');
testRoundtrip(KeyCode.BracketRight, ']', ']', ']');
testRoundtrip(KeyCode.Quote, '\'', '\'', '\'');
testRoundtrip(KeyCode.OEM_8, 'oem_8', 'oem_8', 'oem_8');
testRoundtrip(KeyCode.IntlBackslash, 'oem_102', 'oem_102', 'oem_102');
// OEM aliases
testDeserialization('OEM_1', 'OEM_1', 'OEM_1', KeyCode.Semicolon);
testDeserialization('OEM_PLUS', 'OEM_PLUS', 'OEM_PLUS', KeyCode.Equal);
testDeserialization('OEM_COMMA', 'OEM_COMMA', 'OEM_COMMA', KeyCode.Comma);
testDeserialization('OEM_MINUS', 'OEM_MINUS', 'OEM_MINUS', KeyCode.Minus);
testDeserialization('OEM_PERIOD', 'OEM_PERIOD', 'OEM_PERIOD', KeyCode.Period);
testDeserialization('OEM_2', 'OEM_2', 'OEM_2', KeyCode.Slash);
testDeserialization('OEM_3', 'OEM_3', 'OEM_3', KeyCode.Backquote);
testDeserialization('ABNT_C1', 'ABNT_C1', 'ABNT_C1', KeyCode.ABNT_C1);
testDeserialization('ABNT_C2', 'ABNT_C2', 'ABNT_C2', KeyCode.ABNT_C2);
testDeserialization('OEM_4', 'OEM_4', 'OEM_4', KeyCode.BracketLeft);
testDeserialization('OEM_5', 'OEM_5', 'OEM_5', KeyCode.Backslash);
testDeserialization('OEM_6', 'OEM_6', 'OEM_6', KeyCode.BracketRight);
testDeserialization('OEM_7', 'OEM_7', 'OEM_7', KeyCode.Quote);
testDeserialization('OEM_8', 'OEM_8', 'OEM_8', KeyCode.OEM_8);
testDeserialization('OEM_102', 'OEM_102', 'OEM_102', KeyCode.IntlBackslash);
// accepts '-' as separator
testDeserialization('ctrl-shift-alt-win-a', 'ctrl-shift-alt-cmd-a', 'ctrl-shift-alt-meta-a', KeyMod.CtrlCmd | KeyMod.Shift | KeyMod.Alt | KeyMod.WinCtrl | KeyCode.KeyA);
// various input mistakes
testDeserialization(' ctrl-shift-alt-win-A ', ' shift-alt-cmd-Ctrl-A ', ' ctrl-shift-alt-META-A ', KeyMod.CtrlCmd | KeyMod.Shift | KeyMod.Alt | KeyMod.WinCtrl | KeyCode.KeyA);
});
test('deserialize scan codes', () => {
assert.deepStrictEqual(
KeybindingParser.parseUserBinding('ctrl+shift+[comma] ctrl+/'),
[new ScanCodeBinding(true, true, false, false, ScanCode.Comma), new SimpleKeybinding(true, false, false, false, KeyCode.Slash)]
);
});
test('issue #10452 - invalid command', () => {
let strJSON = `[{ "key": "ctrl+k ctrl+f", "command": ["firstcommand", "seccondcommand"] }]`;
let userKeybinding = <IUserFriendlyKeybinding>JSON.parse(strJSON)[0];
let keybindingItem = KeybindingIO.readUserKeybindingItem(userKeybinding);
assert.strictEqual(keybindingItem.command, null);
});
test('issue #10452 - invalid when', () => {
let strJSON = `[{ "key": "ctrl+k ctrl+f", "command": "firstcommand", "when": [] }]`;
let userKeybinding = <IUserFriendlyKeybinding>JSON.parse(strJSON)[0];
let keybindingItem = KeybindingIO.readUserKeybindingItem(userKeybinding);
assert.strictEqual(keybindingItem.when, undefined);
});
test('issue #10452 - invalid key', () => {
let strJSON = `[{ "key": [], "command": "firstcommand" }]`;
let userKeybinding = <IUserFriendlyKeybinding>JSON.parse(strJSON)[0];
let keybindingItem = KeybindingIO.readUserKeybindingItem(userKeybinding);
assert.deepStrictEqual(keybindingItem.parts, []);
});
test('issue #10452 - invalid key 2', () => {
let strJSON = `[{ "key": "", "command": "firstcommand" }]`;
let userKeybinding = <IUserFriendlyKeybinding>JSON.parse(strJSON)[0];
let keybindingItem = KeybindingIO.readUserKeybindingItem(userKeybinding);
assert.deepStrictEqual(keybindingItem.parts, []);
});
test('test commands args', () => {
let strJSON = `[{ "key": "ctrl+k ctrl+f", "command": "firstcommand", "when": [], "args": { "text": "theText" } }]`;
let userKeybinding = <IUserFriendlyKeybinding>JSON.parse(strJSON)[0];
let keybindingItem = KeybindingIO.readUserKeybindingItem(userKeybinding);
assert.strictEqual(keybindingItem.commandArgs.text, 'theText');
});
});
| src/vs/workbench/services/keybinding/test/browser/keybindingIO.test.ts | 0 | https://github.com/microsoft/vscode/commit/f18b29e132039246caebd4c6b52fcff06265c04d | [
0.00017526796727906913,
0.00017170295177493244,
0.00016688047617208213,
0.0001716888800729066,
0.0000023488667011406505
] |
{
"id": 2,
"code_window": [
"\t\tstorageService.onWillSaveState(this.onWillSaveState, this, this.disposables);\n",
"\t}\n",
"\n",
"\tprivate onDidAddRepository(repository: ISCMRepository): void {\n",
"\t\tthis.logService.trace('SCMViewService#onDidAddRepository', getProviderStorageKey(repository.provider));\n",
"\n",
"\t\tif (!this.didFinishLoading) {\n",
"\t\t\tthis.eventuallyFinishLoading();\n",
"\t\t}\n",
"\n",
"\t\tlet removed: Iterable<ISCMRepository> = Iterable.empty();\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [],
"file_path": "src/vs/workbench/contrib/scm/browser/scmViewService.ts",
"type": "replace",
"edit_start_line_idx": 125
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import { ProxyChannel } from 'vs/base/parts/ipc/common/ipc';
import { Server } from 'vs/base/parts/ipc/node/ipc.cp';
import { NsfwWatcherService } from 'vs/platform/files/node/watcher/nsfw/nsfwWatcherService';
const server = new Server('watcher');
const service = new NsfwWatcherService();
server.registerChannel('watcher', ProxyChannel.fromService(service));
| src/vs/platform/files/node/watcher/nsfw/watcherApp.ts | 0 | https://github.com/microsoft/vscode/commit/f18b29e132039246caebd4c6b52fcff06265c04d | [
0.00017524808936286718,
0.00017298723105341196,
0.00017072635819204152,
0.00017298723105341196,
0.00000226086558541283
] |
{
"id": 2,
"code_window": [
"\t\tstorageService.onWillSaveState(this.onWillSaveState, this, this.disposables);\n",
"\t}\n",
"\n",
"\tprivate onDidAddRepository(repository: ISCMRepository): void {\n",
"\t\tthis.logService.trace('SCMViewService#onDidAddRepository', getProviderStorageKey(repository.provider));\n",
"\n",
"\t\tif (!this.didFinishLoading) {\n",
"\t\t\tthis.eventuallyFinishLoading();\n",
"\t\t}\n",
"\n",
"\t\tlet removed: Iterable<ISCMRepository> = Iterable.empty();\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [],
"file_path": "src/vs/workbench/contrib/scm/browser/scmViewService.ts",
"type": "replace",
"edit_start_line_idx": 125
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import { ICommonEncryptionService } from 'vs/platform/encryption/common/encryptionService';
import { createDecorator } from 'vs/platform/instantiation/common/instantiation';
export const IEncryptionMainService = createDecorator<IEncryptionMainService>('encryptionMainService');
export interface IEncryptionMainService extends ICommonEncryptionService { }
export interface Encryption {
encrypt(salt: string, value: string): Promise<string>;
decrypt(salt: string, value: string): Promise<string>;
}
export class EncryptionMainService implements ICommonEncryptionService {
declare readonly _serviceBrand: undefined;
constructor(
private machineId: string) {
}
private encryption(): Promise<Encryption> {
return new Promise((resolve, reject) => require(['vscode-encrypt'], resolve, reject));
}
async encrypt(value: string): Promise<string> {
try {
const encryption = await this.encryption();
return encryption.encrypt(this.machineId, value);
} catch (e) {
return value;
}
}
async decrypt(value: string): Promise<string> {
try {
const encryption = await this.encryption();
return encryption.decrypt(this.machineId, value);
} catch (e) {
return value;
}
}
}
| src/vs/platform/encryption/electron-main/encryptionMainService.ts | 0 | https://github.com/microsoft/vscode/commit/f18b29e132039246caebd4c6b52fcff06265c04d | [
0.0001750550145516172,
0.00017035575001500547,
0.00016727253387216479,
0.0001691478246357292,
0.000002697811623875168
] |
{
"id": 3,
"code_window": [
"\t\tif (this.previousState) {\n",
"\t\t\tconst index = this.previousState.all.indexOf(getProviderStorageKey(repository.provider));\n",
"\n",
"\t\t\tif (index === -1) { // saw a repo we did not expect\n",
"\t\t\t\tthis.logService.trace('SCMViewService#onDidAddRepository', 'This is a new repository, so we stop the heuristics');\n",
"\n",
"\t\t\t\tconst added: ISCMRepository[] = [];\n",
"\t\t\t\tfor (const repo of this.scmService.repositories) { // all should be visible\n",
"\t\t\t\t\tif (!this._visibleRepositoriesSet.has(repo)) {\n",
"\t\t\t\t\t\tadded.push(repository);\n",
"\t\t\t\t\t}\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [],
"file_path": "src/vs/workbench/contrib/scm/browser/scmViewService.ts",
"type": "replace",
"edit_start_line_idx": 137
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import { DisposableStore } from 'vs/base/common/lifecycle';
import { Emitter, Event } from 'vs/base/common/event';
import { ISCMViewService, ISCMRepository, ISCMService, ISCMViewVisibleRepositoryChangeEvent, ISCMMenus, ISCMProvider } from 'vs/workbench/contrib/scm/common/scm';
import { Iterable } from 'vs/base/common/iterator';
import { IInstantiationService } from 'vs/platform/instantiation/common/instantiation';
import { SCMMenus } from 'vs/workbench/contrib/scm/browser/menus';
import { IStorageService, StorageScope, StorageTarget } from 'vs/platform/storage/common/storage';
import { debounce } from 'vs/base/common/decorators';
import { ILogService } from 'vs/platform/log/common/log';
function getProviderStorageKey(provider: ISCMProvider): string {
return `${provider.contextValue}:${provider.label}${provider.rootUri ? `:${provider.rootUri.toString()}` : ''}`;
}
export interface ISCMViewServiceState {
readonly all: string[];
readonly visible: number[];
}
export class SCMViewService implements ISCMViewService {
declare readonly _serviceBrand: undefined;
readonly menus: ISCMMenus;
private didFinishLoading: boolean = false;
private provisionalVisibleRepository: ISCMRepository | undefined;
private previousState: ISCMViewServiceState | undefined;
private disposables = new DisposableStore();
private _visibleRepositoriesSet = new Set<ISCMRepository>();
private _visibleRepositories: ISCMRepository[] = [];
get visibleRepositories(): ISCMRepository[] {
return this._visibleRepositories;
}
set visibleRepositories(visibleRepositories: ISCMRepository[]) {
const set = new Set(visibleRepositories);
const added = new Set<ISCMRepository>();
const removed = new Set<ISCMRepository>();
for (const repository of visibleRepositories) {
if (!this._visibleRepositoriesSet.has(repository)) {
added.add(repository);
}
}
for (const repository of this._visibleRepositories) {
if (!set.has(repository)) {
removed.add(repository);
}
}
if (added.size === 0 && removed.size === 0) {
return;
}
this._visibleRepositories = visibleRepositories;
this._visibleRepositoriesSet = set;
this._onDidSetVisibleRepositories.fire({ added, removed });
if (this._focusedRepository && removed.has(this._focusedRepository)) {
this.focus(this._visibleRepositories[0]);
}
}
private _onDidChangeRepositories = new Emitter<ISCMViewVisibleRepositoryChangeEvent>();
private _onDidSetVisibleRepositories = new Emitter<ISCMViewVisibleRepositoryChangeEvent>();
readonly onDidChangeVisibleRepositories = Event.any(
this._onDidSetVisibleRepositories.event,
Event.debounce(
this._onDidChangeRepositories.event,
(last, e) => {
if (!last) {
return e;
}
return {
added: Iterable.concat(last.added, e.added),
removed: Iterable.concat(last.removed, e.removed),
};
}, 0)
);
private _focusedRepository: ISCMRepository | undefined;
get focusedRepository(): ISCMRepository | undefined {
return this._focusedRepository;
}
private _onDidFocusRepository = new Emitter<ISCMRepository | undefined>();
readonly onDidFocusRepository = this._onDidFocusRepository.event;
constructor(
@ISCMService private readonly scmService: ISCMService,
@IInstantiationService instantiationService: IInstantiationService,
@IStorageService private readonly storageService: IStorageService,
@ILogService private readonly logService: ILogService
) {
this.menus = instantiationService.createInstance(SCMMenus);
scmService.onDidAddRepository(this.onDidAddRepository, this, this.disposables);
scmService.onDidRemoveRepository(this.onDidRemoveRepository, this, this.disposables);
for (const repository of scmService.repositories) {
this.onDidAddRepository(repository);
}
try {
this.previousState = JSON.parse(storageService.get('scm:view:visibleRepositories', StorageScope.WORKSPACE, ''));
this.eventuallyFinishLoading();
} catch {
// noop
}
storageService.onWillSaveState(this.onWillSaveState, this, this.disposables);
}
private onDidAddRepository(repository: ISCMRepository): void {
this.logService.trace('SCMViewService#onDidAddRepository', getProviderStorageKey(repository.provider));
if (!this.didFinishLoading) {
this.eventuallyFinishLoading();
}
let removed: Iterable<ISCMRepository> = Iterable.empty();
if (this.previousState) {
const index = this.previousState.all.indexOf(getProviderStorageKey(repository.provider));
if (index === -1) { // saw a repo we did not expect
this.logService.trace('SCMViewService#onDidAddRepository', 'This is a new repository, so we stop the heuristics');
const added: ISCMRepository[] = [];
for (const repo of this.scmService.repositories) { // all should be visible
if (!this._visibleRepositoriesSet.has(repo)) {
added.push(repository);
}
}
this._visibleRepositories = [...this.scmService.repositories];
this._visibleRepositoriesSet = new Set(this.scmService.repositories);
this._onDidChangeRepositories.fire({ added, removed: Iterable.empty() });
this.finishLoading();
return;
}
const visible = this.previousState.visible.indexOf(index) > -1;
if (!visible) {
if (this._visibleRepositories.length === 0) { // should make it visible, until other repos come along
this.provisionalVisibleRepository = repository;
} else {
return;
}
} else {
if (this.provisionalVisibleRepository) {
this._visibleRepositories = [];
this._visibleRepositoriesSet = new Set();
removed = [this.provisionalVisibleRepository];
this.provisionalVisibleRepository = undefined;
}
}
}
this._visibleRepositories.push(repository);
this._visibleRepositoriesSet.add(repository);
this._onDidChangeRepositories.fire({ added: [repository], removed });
if (!this._focusedRepository) {
this.focus(repository);
}
}
private onDidRemoveRepository(repository: ISCMRepository): void {
this.logService.trace('SCMViewService#onDidRemoveRepository', getProviderStorageKey(repository.provider));
if (!this.didFinishLoading) {
this.eventuallyFinishLoading();
}
const index = this._visibleRepositories.indexOf(repository);
if (index > -1) {
let added: Iterable<ISCMRepository> = Iterable.empty();
this._visibleRepositories.splice(index, 1);
this._visibleRepositoriesSet.delete(repository);
if (this._visibleRepositories.length === 0 && this.scmService.repositories.length > 0) {
const first = this.scmService.repositories[0];
this._visibleRepositories.push(first);
this._visibleRepositoriesSet.add(first);
added = [first];
}
this._onDidChangeRepositories.fire({ added, removed: [repository] });
}
if (this._focusedRepository === repository) {
this.focus(this._visibleRepositories[0]);
}
}
isVisible(repository: ISCMRepository): boolean {
return this._visibleRepositoriesSet.has(repository);
}
toggleVisibility(repository: ISCMRepository, visible?: boolean): void {
if (typeof visible === 'undefined') {
visible = !this.isVisible(repository);
} else if (this.isVisible(repository) === visible) {
return;
}
if (visible) {
this.visibleRepositories = [...this.visibleRepositories, repository];
} else {
const index = this.visibleRepositories.indexOf(repository);
if (index > -1) {
this.visibleRepositories = [
...this.visibleRepositories.slice(0, index),
...this.visibleRepositories.slice(index + 1)
];
}
}
}
focus(repository: ISCMRepository | undefined): void {
if (repository && !this.visibleRepositories.includes(repository)) {
return;
}
this._focusedRepository = repository;
this._onDidFocusRepository.fire(repository);
}
private onWillSaveState(): void {
if (!this.didFinishLoading) { // don't remember state, if the workbench didn't really finish loading
return;
}
const all = this.scmService.repositories.map(r => getProviderStorageKey(r.provider));
const visible = this.visibleRepositories.map(r => all.indexOf(getProviderStorageKey(r.provider)));
const raw = JSON.stringify({ all, visible });
this.storageService.store('scm:view:visibleRepositories', raw, StorageScope.WORKSPACE, StorageTarget.MACHINE);
}
@debounce(2000)
private eventuallyFinishLoading(): void {
this.logService.trace('SCMViewService#eventuallyFinishLoading');
this.finishLoading();
}
private finishLoading(): void {
if (this.didFinishLoading) {
return;
}
this.logService.trace('SCMViewService#finishLoading');
this.didFinishLoading = true;
this.previousState = undefined;
}
dispose(): void {
this.disposables.dispose();
this._onDidChangeRepositories.dispose();
this._onDidSetVisibleRepositories.dispose();
}
}
| src/vs/workbench/contrib/scm/browser/scmViewService.ts | 1 | https://github.com/microsoft/vscode/commit/f18b29e132039246caebd4c6b52fcff06265c04d | [
0.9988728165626526,
0.323354035615921,
0.00016205152496695518,
0.008227542042732239,
0.45536190271377563
] |
{
"id": 3,
"code_window": [
"\t\tif (this.previousState) {\n",
"\t\t\tconst index = this.previousState.all.indexOf(getProviderStorageKey(repository.provider));\n",
"\n",
"\t\t\tif (index === -1) { // saw a repo we did not expect\n",
"\t\t\t\tthis.logService.trace('SCMViewService#onDidAddRepository', 'This is a new repository, so we stop the heuristics');\n",
"\n",
"\t\t\t\tconst added: ISCMRepository[] = [];\n",
"\t\t\t\tfor (const repo of this.scmService.repositories) { // all should be visible\n",
"\t\t\t\t\tif (!this._visibleRepositoriesSet.has(repo)) {\n",
"\t\t\t\t\t\tadded.push(repository);\n",
"\t\t\t\t\t}\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [],
"file_path": "src/vs/workbench/contrib/scm/browser/scmViewService.ts",
"type": "replace",
"edit_start_line_idx": 137
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import { mapArrayOrNot } from 'vs/base/common/arrays';
import { CancellationToken } from 'vs/base/common/cancellation';
import * as glob from 'vs/base/common/glob';
import { IDisposable } from 'vs/base/common/lifecycle';
import * as objects from 'vs/base/common/objects';
import * as extpath from 'vs/base/common/extpath';
import { fuzzyContains, getNLines } from 'vs/base/common/strings';
import { URI, UriComponents } from 'vs/base/common/uri';
import { IFilesConfiguration } from 'vs/platform/files/common/files';
import { createDecorator } from 'vs/platform/instantiation/common/instantiation';
import { ITelemetryData } from 'vs/platform/telemetry/common/telemetry';
import { Event } from 'vs/base/common/event';
import * as paths from 'vs/base/common/path';
import { isPromiseCanceledError } from 'vs/base/common/errors';
import { TextSearchCompleteMessageType } from 'vs/workbench/services/search/common/searchExtTypes';
import { isPromise } from 'vs/base/common/types';
export { TextSearchCompleteMessageType };
export const VIEWLET_ID = 'workbench.view.search';
export const PANEL_ID = 'workbench.panel.search';
export const VIEW_ID = 'workbench.view.search';
export const SEARCH_EXCLUDE_CONFIG = 'search.exclude';
// Warning: this pattern is used in the search editor to detect offsets. If you
// change this, also change the search-result built-in extension
const SEARCH_ELIDED_PREFIX = '⟪ ';
const SEARCH_ELIDED_SUFFIX = ' characters skipped ⟫';
const SEARCH_ELIDED_MIN_LEN = (SEARCH_ELIDED_PREFIX.length + SEARCH_ELIDED_SUFFIX.length + 5) * 2;
export const ISearchService = createDecorator<ISearchService>('searchService');
/**
* A service that enables to search for files or with in files.
*/
export interface ISearchService {
readonly _serviceBrand: undefined;
textSearch(query: ITextQuery, token?: CancellationToken, onProgress?: (result: ISearchProgressItem) => void): Promise<ISearchComplete>;
fileSearch(query: IFileQuery, token?: CancellationToken): Promise<ISearchComplete>;
clearCache(cacheKey: string): Promise<void>;
registerSearchResultProvider(scheme: string, type: SearchProviderType, provider: ISearchResultProvider): IDisposable;
}
/**
* TODO@roblou - split text from file search entirely, or share code in a more natural way.
*/
export const enum SearchProviderType {
file,
text
}
export interface ISearchResultProvider {
textSearch(query: ITextQuery, onProgress?: (p: ISearchProgressItem) => void, token?: CancellationToken): Promise<ISearchComplete>;
fileSearch(query: IFileQuery, token?: CancellationToken): Promise<ISearchComplete>;
clearCache(cacheKey: string): Promise<void>;
}
export interface IFolderQuery<U extends UriComponents = URI> {
folder: U;
folderName?: string;
excludePattern?: glob.IExpression;
includePattern?: glob.IExpression;
fileEncoding?: string;
disregardIgnoreFiles?: boolean;
disregardGlobalIgnoreFiles?: boolean;
ignoreSymlinks?: boolean;
}
export interface ICommonQueryProps<U extends UriComponents> {
/** For telemetry - indicates what is triggering the source */
_reason?: string;
folderQueries: IFolderQuery<U>[];
includePattern?: glob.IExpression;
excludePattern?: glob.IExpression;
extraFileResources?: U[];
onlyOpenEditors?: boolean;
maxResults?: number;
usingSearchPaths?: boolean;
}
export interface IFileQueryProps<U extends UriComponents> extends ICommonQueryProps<U> {
type: QueryType.File;
filePattern?: string;
/**
* If true no results will be returned. Instead `limitHit` will indicate if at least one result exists or not.
* Currently does not work with queries including a 'siblings clause'.
*/
exists?: boolean;
sortByScore?: boolean;
cacheKey?: string;
}
export interface ITextQueryProps<U extends UriComponents> extends ICommonQueryProps<U> {
type: QueryType.Text;
contentPattern: IPatternInfo;
previewOptions?: ITextSearchPreviewOptions;
maxFileSize?: number;
usePCRE2?: boolean;
afterContext?: number;
beforeContext?: number;
userDisabledExcludesAndIgnoreFiles?: boolean;
}
export type IFileQuery = IFileQueryProps<URI>;
export type IRawFileQuery = IFileQueryProps<UriComponents>;
export type ITextQuery = ITextQueryProps<URI>;
export type IRawTextQuery = ITextQueryProps<UriComponents>;
export type IRawQuery = IRawTextQuery | IRawFileQuery;
export type ISearchQuery = ITextQuery | IFileQuery;
export const enum QueryType {
File = 1,
Text = 2
}
/* __GDPR__FRAGMENT__
"IPatternInfo" : {
"pattern" : { "classification": "CustomerContent", "purpose": "FeatureInsight" },
"isRegExp": { "classification": "SystemMetaData", "purpose": "FeatureInsight", "isMeasurement": true },
"isWordMatch": { "classification": "SystemMetaData", "purpose": "FeatureInsight", "isMeasurement": true },
"wordSeparators": { "classification": "SystemMetaData", "purpose": "FeatureInsight" },
"isMultiline": { "classification": "SystemMetaData", "purpose": "FeatureInsight", "isMeasurement": true },
"isCaseSensitive": { "classification": "SystemMetaData", "purpose": "FeatureInsight", "isMeasurement": true },
"isSmartCase": { "classification": "SystemMetaData", "purpose": "FeatureInsight", "isMeasurement": true }
}
*/
export interface IPatternInfo {
pattern: string;
isRegExp?: boolean;
isWordMatch?: boolean;
wordSeparators?: string;
isMultiline?: boolean;
isUnicode?: boolean;
isCaseSensitive?: boolean;
}
export interface IExtendedExtensionSearchOptions {
usePCRE2?: boolean;
}
export interface IFileMatch<U extends UriComponents = URI> {
resource: U;
results?: ITextSearchResult[];
}
export type IRawFileMatch2 = IFileMatch<UriComponents>;
export interface ITextSearchPreviewOptions {
matchLines: number;
charsPerLine: number;
}
export interface ISearchRange {
readonly startLineNumber: number;
readonly startColumn: number;
readonly endLineNumber: number;
readonly endColumn: number;
}
export interface ITextSearchResultPreview {
text: string;
matches: ISearchRange | ISearchRange[];
}
export interface ITextSearchMatch {
uri?: URI;
ranges: ISearchRange | ISearchRange[];
preview: ITextSearchResultPreview;
}
export interface ITextSearchContext {
uri?: URI;
text: string;
lineNumber: number;
}
export type ITextSearchResult = ITextSearchMatch | ITextSearchContext;
export function resultIsMatch(result: ITextSearchResult): result is ITextSearchMatch {
return !!(<ITextSearchMatch>result).preview;
}
export interface IProgressMessage {
message: string;
}
export type ISearchProgressItem = IFileMatch | IProgressMessage;
export function isFileMatch(p: ISearchProgressItem): p is IFileMatch {
return !!(<IFileMatch>p).resource;
}
export function isProgressMessage(p: ISearchProgressItem | ISerializedSearchProgressItem): p is IProgressMessage {
return !!(p as IProgressMessage).message;
}
export interface ITextSearchCompleteMessage {
text: string;
type: TextSearchCompleteMessageType;
trusted?: boolean;
}
export interface ISearchCompleteStats {
limitHit?: boolean;
messages: ITextSearchCompleteMessage[];
stats?: IFileSearchStats | ITextSearchStats;
}
export interface ISearchComplete extends ISearchCompleteStats {
results: IFileMatch[];
exit?: SearchCompletionExitCode
}
export const enum SearchCompletionExitCode {
Normal,
NewSearchStarted
}
export interface ITextSearchStats {
type: 'textSearchProvider' | 'searchProcess';
}
export interface IFileSearchStats {
fromCache: boolean;
detailStats: ISearchEngineStats | ICachedSearchStats | IFileSearchProviderStats;
resultCount: number;
type: 'fileSearchProvider' | 'searchProcess';
sortingTime?: number;
}
export interface ICachedSearchStats {
cacheWasResolved: boolean;
cacheLookupTime: number;
cacheFilterTime: number;
cacheEntryCount: number;
}
export interface ISearchEngineStats {
fileWalkTime: number;
directoriesWalked: number;
filesWalked: number;
cmdTime: number;
cmdResultCount?: number;
}
export interface IFileSearchProviderStats {
providerTime: number;
postProcessTime: number;
}
export class FileMatch implements IFileMatch {
results: ITextSearchResult[] = [];
constructor(public resource: URI) {
// empty
}
}
export class TextSearchMatch implements ITextSearchMatch {
ranges: ISearchRange | ISearchRange[];
preview: ITextSearchResultPreview;
constructor(text: string, range: ISearchRange | ISearchRange[], previewOptions?: ITextSearchPreviewOptions) {
this.ranges = range;
// Trim preview if this is one match and a single-line match with a preview requested.
// Otherwise send the full text, like for replace or for showing multiple previews.
// TODO this is fishy.
const ranges = Array.isArray(range) ? range : [range];
if (previewOptions && previewOptions.matchLines === 1 && isSingleLineRangeList(ranges)) {
// 1 line preview requested
text = getNLines(text, previewOptions.matchLines);
let result = '';
let shift = 0;
let lastEnd = 0;
const leadingChars = Math.floor(previewOptions.charsPerLine / 5);
const matches: ISearchRange[] = [];
for (const range of ranges) {
const previewStart = Math.max(range.startColumn - leadingChars, 0);
const previewEnd = range.startColumn + previewOptions.charsPerLine;
if (previewStart > lastEnd + leadingChars + SEARCH_ELIDED_MIN_LEN) {
const elision = SEARCH_ELIDED_PREFIX + (previewStart - lastEnd) + SEARCH_ELIDED_SUFFIX;
result += elision + text.slice(previewStart, previewEnd);
shift += previewStart - (lastEnd + elision.length);
} else {
result += text.slice(lastEnd, previewEnd);
}
matches.push(new OneLineRange(0, range.startColumn - shift, range.endColumn - shift));
lastEnd = previewEnd;
}
this.preview = { text: result, matches: Array.isArray(this.ranges) ? matches : matches[0] };
} else {
const firstMatchLine = Array.isArray(range) ? range[0].startLineNumber : range.startLineNumber;
this.preview = {
text,
matches: mapArrayOrNot(range, r => new SearchRange(r.startLineNumber - firstMatchLine, r.startColumn, r.endLineNumber - firstMatchLine, r.endColumn))
};
}
}
}
function isSingleLineRangeList(ranges: ISearchRange[]): boolean {
const line = ranges[0].startLineNumber;
for (const r of ranges) {
if (r.startLineNumber !== line || r.endLineNumber !== line) {
return false;
}
}
return true;
}
export class SearchRange implements ISearchRange {
startLineNumber: number;
startColumn: number;
endLineNumber: number;
endColumn: number;
constructor(startLineNumber: number, startColumn: number, endLineNumber: number, endColumn: number) {
this.startLineNumber = startLineNumber;
this.startColumn = startColumn;
this.endLineNumber = endLineNumber;
this.endColumn = endColumn;
}
}
export class OneLineRange extends SearchRange {
constructor(lineNumber: number, startColumn: number, endColumn: number) {
super(lineNumber, startColumn, lineNumber, endColumn);
}
}
export const enum SearchSortOrder {
Default = 'default',
FileNames = 'fileNames',
Type = 'type',
Modified = 'modified',
CountDescending = 'countDescending',
CountAscending = 'countAscending'
}
export interface ISearchConfigurationProperties {
exclude: glob.IExpression;
useRipgrep: boolean;
/**
* Use ignore file for file search.
*/
useIgnoreFiles: boolean;
useGlobalIgnoreFiles: boolean;
followSymlinks: boolean;
smartCase: boolean;
globalFindClipboard: boolean;
location: 'sidebar' | 'panel';
useReplacePreview: boolean;
showLineNumbers: boolean;
usePCRE2: boolean;
actionsPosition: 'auto' | 'right';
maintainFileSearchCache: boolean;
maxResults: number | null;
collapseResults: 'auto' | 'alwaysCollapse' | 'alwaysExpand';
searchOnType: boolean;
seedOnFocus: boolean;
seedWithNearestWord: boolean;
searchOnTypeDebouncePeriod: number;
mode: 'view' | 'reuseEditor' | 'newEditor';
searchEditor: {
doubleClickBehaviour: 'selectWord' | 'goToLocation' | 'openLocationToSide',
reusePriorSearchConfiguration: boolean,
defaultNumberOfContextLines: number | null,
experimental: {}
};
sortOrder: SearchSortOrder;
}
export interface ISearchConfiguration extends IFilesConfiguration {
search: ISearchConfigurationProperties;
editor: {
wordSeparators: string;
};
}
export function getExcludes(configuration: ISearchConfiguration, includeSearchExcludes = true): glob.IExpression | undefined {
const fileExcludes = configuration && configuration.files && configuration.files.exclude;
const searchExcludes = includeSearchExcludes && configuration && configuration.search && configuration.search.exclude;
if (!fileExcludes && !searchExcludes) {
return undefined;
}
if (!fileExcludes || !searchExcludes) {
return fileExcludes || searchExcludes;
}
let allExcludes: glob.IExpression = Object.create(null);
// clone the config as it could be frozen
allExcludes = objects.mixin(allExcludes, objects.deepClone(fileExcludes));
allExcludes = objects.mixin(allExcludes, objects.deepClone(searchExcludes), true);
return allExcludes;
}
export function pathIncludedInQuery(queryProps: ICommonQueryProps<URI>, fsPath: string): boolean {
if (queryProps.excludePattern && glob.match(queryProps.excludePattern, fsPath)) {
return false;
}
if (queryProps.includePattern || queryProps.usingSearchPaths) {
if (queryProps.includePattern && glob.match(queryProps.includePattern, fsPath)) {
return true;
}
// If searchPaths are being used, the extra file must be in a subfolder and match the pattern, if present
if (queryProps.usingSearchPaths) {
return !!queryProps.folderQueries && queryProps.folderQueries.some(fq => {
const searchPath = fq.folder.fsPath;
if (extpath.isEqualOrParent(fsPath, searchPath)) {
const relPath = paths.relative(searchPath, fsPath);
return !fq.includePattern || !!glob.match(fq.includePattern, relPath);
} else {
return false;
}
});
}
return false;
}
return true;
}
export enum SearchErrorCode {
unknownEncoding = 1,
regexParseError,
globParseError,
invalidLiteral,
rgProcessError,
other,
canceled
}
export class SearchError extends Error {
constructor(message: string, readonly code?: SearchErrorCode) {
super(message);
}
}
export function deserializeSearchError(error: Error): SearchError {
const errorMsg = error.message;
if (isPromiseCanceledError(error)) {
return new SearchError(errorMsg, SearchErrorCode.canceled);
}
try {
const details = JSON.parse(errorMsg);
return new SearchError(details.message, details.code);
} catch (e) {
return new SearchError(errorMsg, SearchErrorCode.other);
}
}
export function serializeSearchError(searchError: SearchError): Error {
const details = { message: searchError.message, code: searchError.code };
return new Error(JSON.stringify(details));
}
export interface ITelemetryEvent {
eventName: string;
data: ITelemetryData;
}
export interface IRawSearchService {
fileSearch(search: IRawFileQuery): Event<ISerializedSearchProgressItem | ISerializedSearchComplete>;
textSearch(search: IRawTextQuery): Event<ISerializedSearchProgressItem | ISerializedSearchComplete>;
clearCache(cacheKey: string): Promise<void>;
}
export interface IRawFileMatch {
base?: string;
/**
* The path of the file relative to the containing `base` folder.
* This path is exactly as it appears on the filesystem.
*/
relativePath: string;
/**
* This path is transformed for search purposes. For example, this could be
* the `relativePath` with the workspace folder name prepended. This way the
* search algorithm would also match against the name of the containing folder.
*
* If not given, the search algorithm should use `relativePath`.
*/
searchPath: string | undefined;
}
export interface ISearchEngine<T> {
search: (onResult: (matches: T) => void, onProgress: (progress: IProgressMessage) => void, done: (error: Error | null, complete: ISearchEngineSuccess) => void) => void;
cancel: () => void;
}
export interface ISerializedSearchSuccess {
type: 'success';
limitHit: boolean;
messages: ITextSearchCompleteMessage[];
stats?: IFileSearchStats | ITextSearchStats;
}
export interface ISearchEngineSuccess {
limitHit: boolean;
messages: ITextSearchCompleteMessage[];
stats: ISearchEngineStats;
}
export interface ISerializedSearchError {
type: 'error';
error: {
message: string,
stack: string
};
}
export type ISerializedSearchComplete = ISerializedSearchSuccess | ISerializedSearchError;
export function isSerializedSearchComplete(arg: ISerializedSearchProgressItem | ISerializedSearchComplete): arg is ISerializedSearchComplete {
if ((arg as any).type === 'error') {
return true;
} else if ((arg as any).type === 'success') {
return true;
} else {
return false;
}
}
export function isSerializedSearchSuccess(arg: ISerializedSearchComplete): arg is ISerializedSearchSuccess {
return arg.type === 'success';
}
export function isSerializedFileMatch(arg: ISerializedSearchProgressItem): arg is ISerializedFileMatch {
return !!(<ISerializedFileMatch>arg).path;
}
export function isFilePatternMatch(candidate: IRawFileMatch, normalizedFilePatternLowercase: string): boolean {
const pathToMatch = candidate.searchPath ? candidate.searchPath : candidate.relativePath;
return fuzzyContains(pathToMatch, normalizedFilePatternLowercase);
}
export interface ISerializedFileMatch {
path: string;
results?: ITextSearchResult[];
numMatches?: number;
}
// Type of the possible values for progress calls from the engine
export type ISerializedSearchProgressItem = ISerializedFileMatch | ISerializedFileMatch[] | IProgressMessage;
export type IFileSearchProgressItem = IRawFileMatch | IRawFileMatch[] | IProgressMessage;
export class SerializableFileMatch implements ISerializedFileMatch {
path: string;
results: ITextSearchMatch[];
constructor(path: string) {
this.path = path;
this.results = [];
}
addMatch(match: ITextSearchMatch): void {
this.results.push(match);
}
serialize(): ISerializedFileMatch {
return {
path: this.path,
results: this.results,
numMatches: this.results.length
};
}
}
/**
* Computes the patterns that the provider handles. Discards sibling clauses and 'false' patterns
*/
export function resolvePatternsForProvider(globalPattern: glob.IExpression | undefined, folderPattern: glob.IExpression | undefined): string[] {
const merged = {
...(globalPattern || {}),
...(folderPattern || {})
};
return Object.keys(merged)
.filter(key => {
const value = merged[key];
return typeof value === 'boolean' && value;
});
}
export class QueryGlobTester {
private _excludeExpression: glob.IExpression;
private _parsedExcludeExpression: glob.ParsedExpression;
private _parsedIncludeExpression: glob.ParsedExpression | null = null;
constructor(config: ISearchQuery, folderQuery: IFolderQuery) {
this._excludeExpression = {
...(config.excludePattern || {}),
...(folderQuery.excludePattern || {})
};
this._parsedExcludeExpression = glob.parse(this._excludeExpression);
// Empty includeExpression means include nothing, so no {} shortcuts
let includeExpression: glob.IExpression | undefined = config.includePattern;
if (folderQuery.includePattern) {
if (includeExpression) {
includeExpression = {
...includeExpression,
...folderQuery.includePattern
};
} else {
includeExpression = folderQuery.includePattern;
}
}
if (includeExpression) {
this._parsedIncludeExpression = glob.parse(includeExpression);
}
}
matchesExcludesSync(testPath: string, basename?: string, hasSibling?: (name: string) => boolean): boolean {
if (this._parsedExcludeExpression && this._parsedExcludeExpression(testPath, basename, hasSibling)) {
return true;
}
return false;
}
/**
* Guaranteed sync - siblingsFn should not return a promise.
*/
includedInQuerySync(testPath: string, basename?: string, hasSibling?: (name: string) => boolean): boolean {
if (this._parsedExcludeExpression && this._parsedExcludeExpression(testPath, basename, hasSibling)) {
return false;
}
if (this._parsedIncludeExpression && !this._parsedIncludeExpression(testPath, basename, hasSibling)) {
return false;
}
return true;
}
/**
* Evaluating the exclude expression is only async if it includes sibling clauses. As an optimization, avoid doing anything with Promises
* unless the expression is async.
*/
includedInQuery(testPath: string, basename?: string, hasSibling?: (name: string) => boolean | Promise<boolean>): Promise<boolean> | boolean {
const excluded = this._parsedExcludeExpression(testPath, basename, hasSibling);
const isIncluded = () => {
return this._parsedIncludeExpression ?
!!(this._parsedIncludeExpression(testPath, basename, hasSibling)) :
true;
};
if (isPromise(excluded)) {
return excluded.then(excluded => {
if (excluded) {
return false;
}
return isIncluded();
});
}
return isIncluded();
}
hasSiblingExcludeClauses(): boolean {
return hasSiblingClauses(this._excludeExpression);
}
}
function hasSiblingClauses(pattern: glob.IExpression): boolean {
for (const key in pattern) {
if (typeof pattern[key] !== 'boolean') {
return true;
}
}
return false;
}
| src/vs/workbench/services/search/common/search.ts | 0 | https://github.com/microsoft/vscode/commit/f18b29e132039246caebd4c6b52fcff06265c04d | [
0.0005332776345312595,
0.00017514277715235949,
0.00016226287698373199,
0.0001702033041510731,
0.000042922554712276906
] |
{
"id": 3,
"code_window": [
"\t\tif (this.previousState) {\n",
"\t\t\tconst index = this.previousState.all.indexOf(getProviderStorageKey(repository.provider));\n",
"\n",
"\t\t\tif (index === -1) { // saw a repo we did not expect\n",
"\t\t\t\tthis.logService.trace('SCMViewService#onDidAddRepository', 'This is a new repository, so we stop the heuristics');\n",
"\n",
"\t\t\t\tconst added: ISCMRepository[] = [];\n",
"\t\t\t\tfor (const repo of this.scmService.repositories) { // all should be visible\n",
"\t\t\t\t\tif (!this._visibleRepositoriesSet.has(repo)) {\n",
"\t\t\t\t\t\tadded.push(repository);\n",
"\t\t\t\t\t}\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [],
"file_path": "src/vs/workbench/contrib/scm/browser/scmViewService.ts",
"type": "replace",
"edit_start_line_idx": 137
} | {
"extends": "../tsconfig.base.json",
"compilerOptions": {
"outDir": "./out"
},
"include": [
"src/**/*"
]
}
| extensions/vscode-notebook-tests/tsconfig.json | 0 | https://github.com/microsoft/vscode/commit/f18b29e132039246caebd4c6b52fcff06265c04d | [
0.00017122637655120343,
0.00017122637655120343,
0.00017122637655120343,
0.00017122637655120343,
0
] |
{
"id": 3,
"code_window": [
"\t\tif (this.previousState) {\n",
"\t\t\tconst index = this.previousState.all.indexOf(getProviderStorageKey(repository.provider));\n",
"\n",
"\t\t\tif (index === -1) { // saw a repo we did not expect\n",
"\t\t\t\tthis.logService.trace('SCMViewService#onDidAddRepository', 'This is a new repository, so we stop the heuristics');\n",
"\n",
"\t\t\t\tconst added: ISCMRepository[] = [];\n",
"\t\t\t\tfor (const repo of this.scmService.repositories) { // all should be visible\n",
"\t\t\t\t\tif (!this._visibleRepositoriesSet.has(repo)) {\n",
"\t\t\t\t\t\tadded.push(repository);\n",
"\t\t\t\t\t}\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [],
"file_path": "src/vs/workbench/contrib/scm/browser/scmViewService.ts",
"type": "replace",
"edit_start_line_idx": 137
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import { generateUuid } from 'vs/base/common/uuid';
import { IExtHostRpcService } from 'vs/workbench/api/common/extHostRpcService';
import { BaseExtHostTerminalService, ExtHostTerminal, ITerminalInternalOptions } from 'vs/workbench/api/common/extHostTerminalService';
import type * as vscode from 'vscode';
export class ExtHostTerminalService extends BaseExtHostTerminalService {
constructor(
@IExtHostRpcService extHostRpc: IExtHostRpcService
) {
super(true, extHostRpc);
}
public createTerminal(name?: string, shellPath?: string, shellArgs?: string[] | string): vscode.Terminal {
return this.createTerminalFromOptions({ name, shellPath, shellArgs });
}
public createTerminalFromOptions(options: vscode.TerminalOptions, internalOptions?: ITerminalInternalOptions): vscode.Terminal {
const terminal = new ExtHostTerminal(this._proxy, generateUuid(), options, options.name);
this._terminals.push(terminal);
terminal.create(options, this._serializeParentTerminal(options, internalOptions));
return terminal.value;
}
}
| src/vs/workbench/api/node/extHostTerminalService.ts | 0 | https://github.com/microsoft/vscode/commit/f18b29e132039246caebd4c6b52fcff06265c04d | [
0.00017422225209884346,
0.00017073721392080188,
0.00016419703024439514,
0.00017379235941916704,
0.000004627937414625194
] |
{
"id": 4,
"code_window": [
"\t}\n",
"\n",
"\tprivate onDidRemoveRepository(repository: ISCMRepository): void {\n",
"\t\tthis.logService.trace('SCMViewService#onDidRemoveRepository', getProviderStorageKey(repository.provider));\n",
"\n",
"\t\tif (!this.didFinishLoading) {\n",
"\t\t\tthis.eventuallyFinishLoading();\n",
"\t\t}\n",
"\n",
"\t\tconst index = this._visibleRepositories.indexOf(repository);\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [],
"file_path": "src/vs/workbench/contrib/scm/browser/scmViewService.ts",
"type": "replace",
"edit_start_line_idx": 181
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import { DisposableStore } from 'vs/base/common/lifecycle';
import { Emitter, Event } from 'vs/base/common/event';
import { ISCMViewService, ISCMRepository, ISCMService, ISCMViewVisibleRepositoryChangeEvent, ISCMMenus, ISCMProvider } from 'vs/workbench/contrib/scm/common/scm';
import { Iterable } from 'vs/base/common/iterator';
import { IInstantiationService } from 'vs/platform/instantiation/common/instantiation';
import { SCMMenus } from 'vs/workbench/contrib/scm/browser/menus';
import { IStorageService, StorageScope, StorageTarget } from 'vs/platform/storage/common/storage';
import { debounce } from 'vs/base/common/decorators';
import { ILogService } from 'vs/platform/log/common/log';
function getProviderStorageKey(provider: ISCMProvider): string {
return `${provider.contextValue}:${provider.label}${provider.rootUri ? `:${provider.rootUri.toString()}` : ''}`;
}
export interface ISCMViewServiceState {
readonly all: string[];
readonly visible: number[];
}
export class SCMViewService implements ISCMViewService {
declare readonly _serviceBrand: undefined;
readonly menus: ISCMMenus;
private didFinishLoading: boolean = false;
private provisionalVisibleRepository: ISCMRepository | undefined;
private previousState: ISCMViewServiceState | undefined;
private disposables = new DisposableStore();
private _visibleRepositoriesSet = new Set<ISCMRepository>();
private _visibleRepositories: ISCMRepository[] = [];
get visibleRepositories(): ISCMRepository[] {
return this._visibleRepositories;
}
set visibleRepositories(visibleRepositories: ISCMRepository[]) {
const set = new Set(visibleRepositories);
const added = new Set<ISCMRepository>();
const removed = new Set<ISCMRepository>();
for (const repository of visibleRepositories) {
if (!this._visibleRepositoriesSet.has(repository)) {
added.add(repository);
}
}
for (const repository of this._visibleRepositories) {
if (!set.has(repository)) {
removed.add(repository);
}
}
if (added.size === 0 && removed.size === 0) {
return;
}
this._visibleRepositories = visibleRepositories;
this._visibleRepositoriesSet = set;
this._onDidSetVisibleRepositories.fire({ added, removed });
if (this._focusedRepository && removed.has(this._focusedRepository)) {
this.focus(this._visibleRepositories[0]);
}
}
private _onDidChangeRepositories = new Emitter<ISCMViewVisibleRepositoryChangeEvent>();
private _onDidSetVisibleRepositories = new Emitter<ISCMViewVisibleRepositoryChangeEvent>();
readonly onDidChangeVisibleRepositories = Event.any(
this._onDidSetVisibleRepositories.event,
Event.debounce(
this._onDidChangeRepositories.event,
(last, e) => {
if (!last) {
return e;
}
return {
added: Iterable.concat(last.added, e.added),
removed: Iterable.concat(last.removed, e.removed),
};
}, 0)
);
private _focusedRepository: ISCMRepository | undefined;
get focusedRepository(): ISCMRepository | undefined {
return this._focusedRepository;
}
private _onDidFocusRepository = new Emitter<ISCMRepository | undefined>();
readonly onDidFocusRepository = this._onDidFocusRepository.event;
constructor(
@ISCMService private readonly scmService: ISCMService,
@IInstantiationService instantiationService: IInstantiationService,
@IStorageService private readonly storageService: IStorageService,
@ILogService private readonly logService: ILogService
) {
this.menus = instantiationService.createInstance(SCMMenus);
scmService.onDidAddRepository(this.onDidAddRepository, this, this.disposables);
scmService.onDidRemoveRepository(this.onDidRemoveRepository, this, this.disposables);
for (const repository of scmService.repositories) {
this.onDidAddRepository(repository);
}
try {
this.previousState = JSON.parse(storageService.get('scm:view:visibleRepositories', StorageScope.WORKSPACE, ''));
this.eventuallyFinishLoading();
} catch {
// noop
}
storageService.onWillSaveState(this.onWillSaveState, this, this.disposables);
}
private onDidAddRepository(repository: ISCMRepository): void {
this.logService.trace('SCMViewService#onDidAddRepository', getProviderStorageKey(repository.provider));
if (!this.didFinishLoading) {
this.eventuallyFinishLoading();
}
let removed: Iterable<ISCMRepository> = Iterable.empty();
if (this.previousState) {
const index = this.previousState.all.indexOf(getProviderStorageKey(repository.provider));
if (index === -1) { // saw a repo we did not expect
this.logService.trace('SCMViewService#onDidAddRepository', 'This is a new repository, so we stop the heuristics');
const added: ISCMRepository[] = [];
for (const repo of this.scmService.repositories) { // all should be visible
if (!this._visibleRepositoriesSet.has(repo)) {
added.push(repository);
}
}
this._visibleRepositories = [...this.scmService.repositories];
this._visibleRepositoriesSet = new Set(this.scmService.repositories);
this._onDidChangeRepositories.fire({ added, removed: Iterable.empty() });
this.finishLoading();
return;
}
const visible = this.previousState.visible.indexOf(index) > -1;
if (!visible) {
if (this._visibleRepositories.length === 0) { // should make it visible, until other repos come along
this.provisionalVisibleRepository = repository;
} else {
return;
}
} else {
if (this.provisionalVisibleRepository) {
this._visibleRepositories = [];
this._visibleRepositoriesSet = new Set();
removed = [this.provisionalVisibleRepository];
this.provisionalVisibleRepository = undefined;
}
}
}
this._visibleRepositories.push(repository);
this._visibleRepositoriesSet.add(repository);
this._onDidChangeRepositories.fire({ added: [repository], removed });
if (!this._focusedRepository) {
this.focus(repository);
}
}
private onDidRemoveRepository(repository: ISCMRepository): void {
this.logService.trace('SCMViewService#onDidRemoveRepository', getProviderStorageKey(repository.provider));
if (!this.didFinishLoading) {
this.eventuallyFinishLoading();
}
const index = this._visibleRepositories.indexOf(repository);
if (index > -1) {
let added: Iterable<ISCMRepository> = Iterable.empty();
this._visibleRepositories.splice(index, 1);
this._visibleRepositoriesSet.delete(repository);
if (this._visibleRepositories.length === 0 && this.scmService.repositories.length > 0) {
const first = this.scmService.repositories[0];
this._visibleRepositories.push(first);
this._visibleRepositoriesSet.add(first);
added = [first];
}
this._onDidChangeRepositories.fire({ added, removed: [repository] });
}
if (this._focusedRepository === repository) {
this.focus(this._visibleRepositories[0]);
}
}
isVisible(repository: ISCMRepository): boolean {
return this._visibleRepositoriesSet.has(repository);
}
toggleVisibility(repository: ISCMRepository, visible?: boolean): void {
if (typeof visible === 'undefined') {
visible = !this.isVisible(repository);
} else if (this.isVisible(repository) === visible) {
return;
}
if (visible) {
this.visibleRepositories = [...this.visibleRepositories, repository];
} else {
const index = this.visibleRepositories.indexOf(repository);
if (index > -1) {
this.visibleRepositories = [
...this.visibleRepositories.slice(0, index),
...this.visibleRepositories.slice(index + 1)
];
}
}
}
focus(repository: ISCMRepository | undefined): void {
if (repository && !this.visibleRepositories.includes(repository)) {
return;
}
this._focusedRepository = repository;
this._onDidFocusRepository.fire(repository);
}
private onWillSaveState(): void {
if (!this.didFinishLoading) { // don't remember state, if the workbench didn't really finish loading
return;
}
const all = this.scmService.repositories.map(r => getProviderStorageKey(r.provider));
const visible = this.visibleRepositories.map(r => all.indexOf(getProviderStorageKey(r.provider)));
const raw = JSON.stringify({ all, visible });
this.storageService.store('scm:view:visibleRepositories', raw, StorageScope.WORKSPACE, StorageTarget.MACHINE);
}
@debounce(2000)
private eventuallyFinishLoading(): void {
this.logService.trace('SCMViewService#eventuallyFinishLoading');
this.finishLoading();
}
private finishLoading(): void {
if (this.didFinishLoading) {
return;
}
this.logService.trace('SCMViewService#finishLoading');
this.didFinishLoading = true;
this.previousState = undefined;
}
dispose(): void {
this.disposables.dispose();
this._onDidChangeRepositories.dispose();
this._onDidSetVisibleRepositories.dispose();
}
}
| src/vs/workbench/contrib/scm/browser/scmViewService.ts | 1 | https://github.com/microsoft/vscode/commit/f18b29e132039246caebd4c6b52fcff06265c04d | [
0.9986610412597656,
0.3299809992313385,
0.00016596865316387266,
0.024888671934604645,
0.433906227350235
] |
{
"id": 4,
"code_window": [
"\t}\n",
"\n",
"\tprivate onDidRemoveRepository(repository: ISCMRepository): void {\n",
"\t\tthis.logService.trace('SCMViewService#onDidRemoveRepository', getProviderStorageKey(repository.provider));\n",
"\n",
"\t\tif (!this.didFinishLoading) {\n",
"\t\t\tthis.eventuallyFinishLoading();\n",
"\t\t}\n",
"\n",
"\t\tconst index = this._visibleRepositories.indexOf(repository);\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [],
"file_path": "src/vs/workbench/contrib/scm/browser/scmViewService.ts",
"type": "replace",
"edit_start_line_idx": 181
} | /*---------------------------------------------------------------------------------------------
* 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 'vs/base/common/assert';
import * as Types from 'vs/base/common/types';
export interface IRegistry {
/**
* Adds the extension functions and properties defined by data to the
* platform. The provided id must be unique.
* @param id a unique identifier
* @param data a contribution
*/
add(id: string, data: any): void;
/**
* Returns true iff there is an extension with the provided id.
* @param id an extension identifier
*/
knows(id: string): boolean;
/**
* Returns the extension functions and properties defined by the specified key or null.
* @param id an extension identifier
*/
as<T>(id: string): T;
}
class RegistryImpl implements IRegistry {
private readonly data = new Map<string, any>();
public add(id: string, data: any): void {
Assert.ok(Types.isString(id));
Assert.ok(Types.isObject(data));
Assert.ok(!this.data.has(id), 'There is already an extension with this id');
this.data.set(id, data);
}
public knows(id: string): boolean {
return this.data.has(id);
}
public as(id: string): any {
return this.data.get(id) || null;
}
}
export const Registry: IRegistry = new RegistryImpl();
| src/vs/platform/registry/common/platform.ts | 0 | https://github.com/microsoft/vscode/commit/f18b29e132039246caebd4c6b52fcff06265c04d | [
0.00017805895186029375,
0.00017064517305698246,
0.0001615242363186553,
0.00017139299598056823,
0.0000050690246098383795
] |
{
"id": 4,
"code_window": [
"\t}\n",
"\n",
"\tprivate onDidRemoveRepository(repository: ISCMRepository): void {\n",
"\t\tthis.logService.trace('SCMViewService#onDidRemoveRepository', getProviderStorageKey(repository.provider));\n",
"\n",
"\t\tif (!this.didFinishLoading) {\n",
"\t\t\tthis.eventuallyFinishLoading();\n",
"\t\t}\n",
"\n",
"\t\tconst index = this._visibleRepositories.indexOf(repository);\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [],
"file_path": "src/vs/workbench/contrib/scm/browser/scmViewService.ts",
"type": "replace",
"edit_start_line_idx": 181
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import { Schemas } from 'vs/base/common/network';
import { URI } from 'vs/base/common/uri';
import { EditorInputCapabilities, GroupIdentifier, IUntypedEditorInput, Verbosity } from 'vs/workbench/common/editor';
import { EditorInput } from 'vs/workbench/common/editor/editorInput';
import { IOverlayWebview } from 'vs/workbench/contrib/webview/browser/webview';
import { WebviewIconManager, WebviewIcons } from 'vs/workbench/contrib/webviewPanel/browser/webviewIconManager';
export class WebviewInput extends EditorInput {
public static typeId = 'workbench.editors.webviewInput';
public override get typeId(): string {
return WebviewInput.typeId;
}
public override get editorId(): string {
return this.viewType;
}
public override get capabilities(): EditorInputCapabilities {
return EditorInputCapabilities.Readonly | EditorInputCapabilities.Singleton;
}
private _name: string;
private _iconPath?: WebviewIcons;
private _group?: GroupIdentifier;
private _webview: IOverlayWebview;
private _hasTransfered = false;
get resource() {
return URI.from({
scheme: Schemas.webviewPanel,
path: `webview-panel/webview-${this.id}`
});
}
constructor(
public readonly id: string,
public readonly viewType: string,
name: string,
webview: IOverlayWebview,
private readonly _iconManager: WebviewIconManager,
) {
super();
this._name = name;
this._webview = webview;
}
override dispose() {
if (!this.isDisposed()) {
if (!this._hasTransfered) {
this._webview?.dispose();
}
}
super.dispose();
}
public override getName(): string {
return this._name;
}
public override getTitle(_verbosity?: Verbosity): string {
return this.getName();
}
public override getDescription(): string | undefined {
return undefined;
}
public setName(value: string): void {
this._name = value;
this._onDidChangeLabel.fire();
}
public get webview(): IOverlayWebview {
return this._webview;
}
public get extension() {
return this.webview.extension;
}
public get iconPath() {
return this._iconPath;
}
public set iconPath(value: WebviewIcons | undefined) {
this._iconPath = value;
this._iconManager.setIcons(this.id, value);
}
public override matches(other: EditorInput | IUntypedEditorInput): boolean {
return super.matches(other) || other === this;
}
public get group(): GroupIdentifier | undefined {
return this._group;
}
public updateGroup(group: GroupIdentifier): void {
this._group = group;
}
protected transfer(other: WebviewInput): WebviewInput | undefined {
if (this._hasTransfered) {
return undefined;
}
this._hasTransfered = true;
other._webview = this._webview;
return other;
}
}
| src/vs/workbench/contrib/webviewPanel/browser/webviewEditorInput.ts | 0 | https://github.com/microsoft/vscode/commit/f18b29e132039246caebd4c6b52fcff06265c04d | [
0.0001772593823261559,
0.00017335703887511045,
0.00016953339218162,
0.00017421820666640997,
0.000002187323161706445
] |
{
"id": 4,
"code_window": [
"\t}\n",
"\n",
"\tprivate onDidRemoveRepository(repository: ISCMRepository): void {\n",
"\t\tthis.logService.trace('SCMViewService#onDidRemoveRepository', getProviderStorageKey(repository.provider));\n",
"\n",
"\t\tif (!this.didFinishLoading) {\n",
"\t\t\tthis.eventuallyFinishLoading();\n",
"\t\t}\n",
"\n",
"\t\tconst index = this._visibleRepositories.indexOf(repository);\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [],
"file_path": "src/vs/workbench/contrib/scm/browser/scmViewService.ts",
"type": "replace",
"edit_start_line_idx": 181
} | [
{
"c": "FROM",
"t": "source.dockerfile keyword.other.special-method.dockerfile",
"r": {
"dark_plus": "keyword: #569CD6",
"light_plus": "keyword: #0000FF",
"dark_vs": "keyword: #569CD6",
"light_vs": "keyword: #0000FF",
"hc_black": "keyword: #569CD6"
}
},
{
"c": " ubuntu",
"t": "source.dockerfile",
"r": {
"dark_plus": "default: #D4D4D4",
"light_plus": "default: #000000",
"dark_vs": "default: #D4D4D4",
"light_vs": "default: #000000",
"hc_black": "default: #FFFFFF"
}
},
{
"c": "MAINTAINER",
"t": "source.dockerfile keyword.other.special-method.dockerfile",
"r": {
"dark_plus": "keyword: #569CD6",
"light_plus": "keyword: #0000FF",
"dark_vs": "keyword: #569CD6",
"light_vs": "keyword: #0000FF",
"hc_black": "keyword: #569CD6"
}
},
{
"c": " Kimbro Staken",
"t": "source.dockerfile",
"r": {
"dark_plus": "default: #D4D4D4",
"light_plus": "default: #000000",
"dark_vs": "default: #D4D4D4",
"light_vs": "default: #000000",
"hc_black": "default: #FFFFFF"
}
},
{
"c": "RUN",
"t": "source.dockerfile keyword.other.special-method.dockerfile",
"r": {
"dark_plus": "keyword: #569CD6",
"light_plus": "keyword: #0000FF",
"dark_vs": "keyword: #569CD6",
"light_vs": "keyword: #0000FF",
"hc_black": "keyword: #569CD6"
}
},
{
"c": " apt-get install -y software-properties-common python",
"t": "source.dockerfile",
"r": {
"dark_plus": "default: #D4D4D4",
"light_plus": "default: #000000",
"dark_vs": "default: #D4D4D4",
"light_vs": "default: #000000",
"hc_black": "default: #FFFFFF"
}
},
{
"c": "RUN",
"t": "source.dockerfile keyword.other.special-method.dockerfile",
"r": {
"dark_plus": "keyword: #569CD6",
"light_plus": "keyword: #0000FF",
"dark_vs": "keyword: #569CD6",
"light_vs": "keyword: #0000FF",
"hc_black": "keyword: #569CD6"
}
},
{
"c": " add-apt-repository ppa:chris-lea/node.js",
"t": "source.dockerfile",
"r": {
"dark_plus": "default: #D4D4D4",
"light_plus": "default: #000000",
"dark_vs": "default: #D4D4D4",
"light_vs": "default: #000000",
"hc_black": "default: #FFFFFF"
}
},
{
"c": "RUN",
"t": "source.dockerfile keyword.other.special-method.dockerfile",
"r": {
"dark_plus": "keyword: #569CD6",
"light_plus": "keyword: #0000FF",
"dark_vs": "keyword: #569CD6",
"light_vs": "keyword: #0000FF",
"hc_black": "keyword: #569CD6"
}
},
{
"c": " echo ",
"t": "source.dockerfile",
"r": {
"dark_plus": "default: #D4D4D4",
"light_plus": "default: #000000",
"dark_vs": "default: #D4D4D4",
"light_vs": "default: #000000",
"hc_black": "default: #FFFFFF"
}
},
{
"c": "\"deb http://us.archive.ubuntu.com/ubuntu/ precise universe\"",
"t": "source.dockerfile string.quoted.double.dockerfile",
"r": {
"dark_plus": "string: #CE9178",
"light_plus": "string: #A31515",
"dark_vs": "string: #CE9178",
"light_vs": "string: #A31515",
"hc_black": "string: #CE9178"
}
},
{
"c": " >> /etc/apt/sources.list",
"t": "source.dockerfile",
"r": {
"dark_plus": "default: #D4D4D4",
"light_plus": "default: #000000",
"dark_vs": "default: #D4D4D4",
"light_vs": "default: #000000",
"hc_black": "default: #FFFFFF"
}
},
{
"c": "RUN",
"t": "source.dockerfile keyword.other.special-method.dockerfile",
"r": {
"dark_plus": "keyword: #569CD6",
"light_plus": "keyword: #0000FF",
"dark_vs": "keyword: #569CD6",
"light_vs": "keyword: #0000FF",
"hc_black": "keyword: #569CD6"
}
},
{
"c": " apt-get update",
"t": "source.dockerfile",
"r": {
"dark_plus": "default: #D4D4D4",
"light_plus": "default: #000000",
"dark_vs": "default: #D4D4D4",
"light_vs": "default: #000000",
"hc_black": "default: #FFFFFF"
}
},
{
"c": "RUN",
"t": "source.dockerfile keyword.other.special-method.dockerfile",
"r": {
"dark_plus": "keyword: #569CD6",
"light_plus": "keyword: #0000FF",
"dark_vs": "keyword: #569CD6",
"light_vs": "keyword: #0000FF",
"hc_black": "keyword: #569CD6"
}
},
{
"c": " apt-get install -y nodejs",
"t": "source.dockerfile",
"r": {
"dark_plus": "default: #D4D4D4",
"light_plus": "default: #000000",
"dark_vs": "default: #D4D4D4",
"light_vs": "default: #000000",
"hc_black": "default: #FFFFFF"
}
},
{
"c": "#",
"t": "source.dockerfile comment.line.number-sign.dockerfile punctuation.definition.comment.dockerfile",
"r": {
"dark_plus": "comment: #6A9955",
"light_plus": "comment: #008000",
"dark_vs": "comment: #6A9955",
"light_vs": "comment: #008000",
"hc_black": "comment: #7CA668"
}
},
{
"c": "RUN apt-get install -y nodejs=0.6.12~dfsg1-1ubuntu1",
"t": "source.dockerfile comment.line.number-sign.dockerfile",
"r": {
"dark_plus": "comment: #6A9955",
"light_plus": "comment: #008000",
"dark_vs": "comment: #6A9955",
"light_vs": "comment: #008000",
"hc_black": "comment: #7CA668"
}
},
{
"c": "RUN",
"t": "source.dockerfile keyword.other.special-method.dockerfile",
"r": {
"dark_plus": "keyword: #569CD6",
"light_plus": "keyword: #0000FF",
"dark_vs": "keyword: #569CD6",
"light_vs": "keyword: #0000FF",
"hc_black": "keyword: #569CD6"
}
},
{
"c": " mkdir /var/www",
"t": "source.dockerfile",
"r": {
"dark_plus": "default: #D4D4D4",
"light_plus": "default: #000000",
"dark_vs": "default: #D4D4D4",
"light_vs": "default: #000000",
"hc_black": "default: #FFFFFF"
}
},
{
"c": "ADD",
"t": "source.dockerfile keyword.other.special-method.dockerfile",
"r": {
"dark_plus": "keyword: #569CD6",
"light_plus": "keyword: #0000FF",
"dark_vs": "keyword: #569CD6",
"light_vs": "keyword: #0000FF",
"hc_black": "keyword: #569CD6"
}
},
{
"c": " app.js /var/www/app.js",
"t": "source.dockerfile",
"r": {
"dark_plus": "default: #D4D4D4",
"light_plus": "default: #000000",
"dark_vs": "default: #D4D4D4",
"light_vs": "default: #000000",
"hc_black": "default: #FFFFFF"
}
},
{
"c": "CMD",
"t": "source.dockerfile keyword.other.special-method.dockerfile",
"r": {
"dark_plus": "keyword: #569CD6",
"light_plus": "keyword: #0000FF",
"dark_vs": "keyword: #569CD6",
"light_vs": "keyword: #0000FF",
"hc_black": "keyword: #569CD6"
}
},
{
"c": " [",
"t": "source.dockerfile",
"r": {
"dark_plus": "default: #D4D4D4",
"light_plus": "default: #000000",
"dark_vs": "default: #D4D4D4",
"light_vs": "default: #000000",
"hc_black": "default: #FFFFFF"
}
},
{
"c": "\"/usr/bin/node\"",
"t": "source.dockerfile string.quoted.double.dockerfile",
"r": {
"dark_plus": "string: #CE9178",
"light_plus": "string: #A31515",
"dark_vs": "string: #CE9178",
"light_vs": "string: #A31515",
"hc_black": "string: #CE9178"
}
},
{
"c": ", ",
"t": "source.dockerfile",
"r": {
"dark_plus": "default: #D4D4D4",
"light_plus": "default: #000000",
"dark_vs": "default: #D4D4D4",
"light_vs": "default: #000000",
"hc_black": "default: #FFFFFF"
}
},
{
"c": "\"/var/www/app.js\"",
"t": "source.dockerfile string.quoted.double.dockerfile",
"r": {
"dark_plus": "string: #CE9178",
"light_plus": "string: #A31515",
"dark_vs": "string: #CE9178",
"light_vs": "string: #A31515",
"hc_black": "string: #CE9178"
}
},
{
"c": "] ",
"t": "source.dockerfile",
"r": {
"dark_plus": "default: #D4D4D4",
"light_plus": "default: #000000",
"dark_vs": "default: #D4D4D4",
"light_vs": "default: #000000",
"hc_black": "default: #FFFFFF"
}
}
] | extensions/vscode-colorize-tests/test/colorize-results/Dockerfile.json | 0 | https://github.com/microsoft/vscode/commit/f18b29e132039246caebd4c6b52fcff06265c04d | [
0.00017809341079555452,
0.00017588023911230266,
0.000173942229594104,
0.00017592230869922787,
0.0000010307763886885368
] |
{
"id": 5,
"code_window": [
"\t}\n",
"\n",
"\t@debounce(2000)\n",
"\tprivate eventuallyFinishLoading(): void {\n",
"\t\tthis.logService.trace('SCMViewService#eventuallyFinishLoading');\n",
"\t\tthis.finishLoading();\n",
"\t}\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [],
"file_path": "src/vs/workbench/contrib/scm/browser/scmViewService.ts",
"type": "replace",
"edit_start_line_idx": 259
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import { DisposableStore } from 'vs/base/common/lifecycle';
import { Emitter, Event } from 'vs/base/common/event';
import { ISCMViewService, ISCMRepository, ISCMService, ISCMViewVisibleRepositoryChangeEvent, ISCMMenus, ISCMProvider } from 'vs/workbench/contrib/scm/common/scm';
import { Iterable } from 'vs/base/common/iterator';
import { IInstantiationService } from 'vs/platform/instantiation/common/instantiation';
import { SCMMenus } from 'vs/workbench/contrib/scm/browser/menus';
import { IStorageService, StorageScope, StorageTarget } from 'vs/platform/storage/common/storage';
import { debounce } from 'vs/base/common/decorators';
import { ILogService } from 'vs/platform/log/common/log';
function getProviderStorageKey(provider: ISCMProvider): string {
return `${provider.contextValue}:${provider.label}${provider.rootUri ? `:${provider.rootUri.toString()}` : ''}`;
}
export interface ISCMViewServiceState {
readonly all: string[];
readonly visible: number[];
}
export class SCMViewService implements ISCMViewService {
declare readonly _serviceBrand: undefined;
readonly menus: ISCMMenus;
private didFinishLoading: boolean = false;
private provisionalVisibleRepository: ISCMRepository | undefined;
private previousState: ISCMViewServiceState | undefined;
private disposables = new DisposableStore();
private _visibleRepositoriesSet = new Set<ISCMRepository>();
private _visibleRepositories: ISCMRepository[] = [];
get visibleRepositories(): ISCMRepository[] {
return this._visibleRepositories;
}
set visibleRepositories(visibleRepositories: ISCMRepository[]) {
const set = new Set(visibleRepositories);
const added = new Set<ISCMRepository>();
const removed = new Set<ISCMRepository>();
for (const repository of visibleRepositories) {
if (!this._visibleRepositoriesSet.has(repository)) {
added.add(repository);
}
}
for (const repository of this._visibleRepositories) {
if (!set.has(repository)) {
removed.add(repository);
}
}
if (added.size === 0 && removed.size === 0) {
return;
}
this._visibleRepositories = visibleRepositories;
this._visibleRepositoriesSet = set;
this._onDidSetVisibleRepositories.fire({ added, removed });
if (this._focusedRepository && removed.has(this._focusedRepository)) {
this.focus(this._visibleRepositories[0]);
}
}
private _onDidChangeRepositories = new Emitter<ISCMViewVisibleRepositoryChangeEvent>();
private _onDidSetVisibleRepositories = new Emitter<ISCMViewVisibleRepositoryChangeEvent>();
readonly onDidChangeVisibleRepositories = Event.any(
this._onDidSetVisibleRepositories.event,
Event.debounce(
this._onDidChangeRepositories.event,
(last, e) => {
if (!last) {
return e;
}
return {
added: Iterable.concat(last.added, e.added),
removed: Iterable.concat(last.removed, e.removed),
};
}, 0)
);
private _focusedRepository: ISCMRepository | undefined;
get focusedRepository(): ISCMRepository | undefined {
return this._focusedRepository;
}
private _onDidFocusRepository = new Emitter<ISCMRepository | undefined>();
readonly onDidFocusRepository = this._onDidFocusRepository.event;
constructor(
@ISCMService private readonly scmService: ISCMService,
@IInstantiationService instantiationService: IInstantiationService,
@IStorageService private readonly storageService: IStorageService,
@ILogService private readonly logService: ILogService
) {
this.menus = instantiationService.createInstance(SCMMenus);
scmService.onDidAddRepository(this.onDidAddRepository, this, this.disposables);
scmService.onDidRemoveRepository(this.onDidRemoveRepository, this, this.disposables);
for (const repository of scmService.repositories) {
this.onDidAddRepository(repository);
}
try {
this.previousState = JSON.parse(storageService.get('scm:view:visibleRepositories', StorageScope.WORKSPACE, ''));
this.eventuallyFinishLoading();
} catch {
// noop
}
storageService.onWillSaveState(this.onWillSaveState, this, this.disposables);
}
private onDidAddRepository(repository: ISCMRepository): void {
this.logService.trace('SCMViewService#onDidAddRepository', getProviderStorageKey(repository.provider));
if (!this.didFinishLoading) {
this.eventuallyFinishLoading();
}
let removed: Iterable<ISCMRepository> = Iterable.empty();
if (this.previousState) {
const index = this.previousState.all.indexOf(getProviderStorageKey(repository.provider));
if (index === -1) { // saw a repo we did not expect
this.logService.trace('SCMViewService#onDidAddRepository', 'This is a new repository, so we stop the heuristics');
const added: ISCMRepository[] = [];
for (const repo of this.scmService.repositories) { // all should be visible
if (!this._visibleRepositoriesSet.has(repo)) {
added.push(repository);
}
}
this._visibleRepositories = [...this.scmService.repositories];
this._visibleRepositoriesSet = new Set(this.scmService.repositories);
this._onDidChangeRepositories.fire({ added, removed: Iterable.empty() });
this.finishLoading();
return;
}
const visible = this.previousState.visible.indexOf(index) > -1;
if (!visible) {
if (this._visibleRepositories.length === 0) { // should make it visible, until other repos come along
this.provisionalVisibleRepository = repository;
} else {
return;
}
} else {
if (this.provisionalVisibleRepository) {
this._visibleRepositories = [];
this._visibleRepositoriesSet = new Set();
removed = [this.provisionalVisibleRepository];
this.provisionalVisibleRepository = undefined;
}
}
}
this._visibleRepositories.push(repository);
this._visibleRepositoriesSet.add(repository);
this._onDidChangeRepositories.fire({ added: [repository], removed });
if (!this._focusedRepository) {
this.focus(repository);
}
}
private onDidRemoveRepository(repository: ISCMRepository): void {
this.logService.trace('SCMViewService#onDidRemoveRepository', getProviderStorageKey(repository.provider));
if (!this.didFinishLoading) {
this.eventuallyFinishLoading();
}
const index = this._visibleRepositories.indexOf(repository);
if (index > -1) {
let added: Iterable<ISCMRepository> = Iterable.empty();
this._visibleRepositories.splice(index, 1);
this._visibleRepositoriesSet.delete(repository);
if (this._visibleRepositories.length === 0 && this.scmService.repositories.length > 0) {
const first = this.scmService.repositories[0];
this._visibleRepositories.push(first);
this._visibleRepositoriesSet.add(first);
added = [first];
}
this._onDidChangeRepositories.fire({ added, removed: [repository] });
}
if (this._focusedRepository === repository) {
this.focus(this._visibleRepositories[0]);
}
}
isVisible(repository: ISCMRepository): boolean {
return this._visibleRepositoriesSet.has(repository);
}
toggleVisibility(repository: ISCMRepository, visible?: boolean): void {
if (typeof visible === 'undefined') {
visible = !this.isVisible(repository);
} else if (this.isVisible(repository) === visible) {
return;
}
if (visible) {
this.visibleRepositories = [...this.visibleRepositories, repository];
} else {
const index = this.visibleRepositories.indexOf(repository);
if (index > -1) {
this.visibleRepositories = [
...this.visibleRepositories.slice(0, index),
...this.visibleRepositories.slice(index + 1)
];
}
}
}
focus(repository: ISCMRepository | undefined): void {
if (repository && !this.visibleRepositories.includes(repository)) {
return;
}
this._focusedRepository = repository;
this._onDidFocusRepository.fire(repository);
}
private onWillSaveState(): void {
if (!this.didFinishLoading) { // don't remember state, if the workbench didn't really finish loading
return;
}
const all = this.scmService.repositories.map(r => getProviderStorageKey(r.provider));
const visible = this.visibleRepositories.map(r => all.indexOf(getProviderStorageKey(r.provider)));
const raw = JSON.stringify({ all, visible });
this.storageService.store('scm:view:visibleRepositories', raw, StorageScope.WORKSPACE, StorageTarget.MACHINE);
}
@debounce(2000)
private eventuallyFinishLoading(): void {
this.logService.trace('SCMViewService#eventuallyFinishLoading');
this.finishLoading();
}
private finishLoading(): void {
if (this.didFinishLoading) {
return;
}
this.logService.trace('SCMViewService#finishLoading');
this.didFinishLoading = true;
this.previousState = undefined;
}
dispose(): void {
this.disposables.dispose();
this._onDidChangeRepositories.dispose();
this._onDidSetVisibleRepositories.dispose();
}
}
| src/vs/workbench/contrib/scm/browser/scmViewService.ts | 1 | https://github.com/microsoft/vscode/commit/f18b29e132039246caebd4c6b52fcff06265c04d | [
0.998683750629425,
0.16031385958194733,
0.00016357042477466166,
0.00017409329302608967,
0.34549641609191895
] |
{
"id": 5,
"code_window": [
"\t}\n",
"\n",
"\t@debounce(2000)\n",
"\tprivate eventuallyFinishLoading(): void {\n",
"\t\tthis.logService.trace('SCMViewService#eventuallyFinishLoading');\n",
"\t\tthis.finishLoading();\n",
"\t}\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [],
"file_path": "src/vs/workbench/contrib/scm/browser/scmViewService.ts",
"type": "replace",
"edit_start_line_idx": 259
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
'use strict';
var updateGrammar = require('vscode-grammar-updater');
updateGrammar.update('jeff-hykin/cpp-textmate-grammar', 'syntaxes/c.tmLanguage.json', './syntaxes/c.tmLanguage.json', undefined, 'master', 'source/languages/cpp/');
updateGrammar.update('jeff-hykin/cpp-textmate-grammar', 'syntaxes/cpp.tmLanguage.json', './syntaxes/cpp.tmLanguage.json', undefined, 'master', 'source/languages/cpp/');
updateGrammar.update('jeff-hykin/cpp-textmate-grammar', 'syntaxes/cpp.embedded.macro.tmLanguage.json', './syntaxes/cpp.embedded.macro.tmLanguage.json', undefined, 'master', 'source/languages/cpp/');
updateGrammar.update('NVIDIA/cuda-cpp-grammar', 'syntaxes/cuda-cpp.tmLanguage.json', './syntaxes/cuda-cpp.tmLanguage.json', undefined, 'master');
// `source.c.platform` which is still included by other grammars
updateGrammar.update('textmate/c.tmbundle', 'Syntaxes/Platform.tmLanguage', './syntaxes/platform.tmLanguage.json');
| extensions/cpp/build/update-grammars.js | 0 | https://github.com/microsoft/vscode/commit/f18b29e132039246caebd4c6b52fcff06265c04d | [
0.00017237225256394595,
0.00017075067444238812,
0.00016912909632083029,
0.00017075067444238812,
0.0000016215781215578318
] |
{
"id": 5,
"code_window": [
"\t}\n",
"\n",
"\t@debounce(2000)\n",
"\tprivate eventuallyFinishLoading(): void {\n",
"\t\tthis.logService.trace('SCMViewService#eventuallyFinishLoading');\n",
"\t\tthis.finishLoading();\n",
"\t}\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [],
"file_path": "src/vs/workbench/contrib/scm/browser/scmViewService.ts",
"type": "replace",
"edit_start_line_idx": 259
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import { URI } from 'vs/base/common/uri';
import { Event } from 'vs/base/common/event';
import { IDisposable } from 'vs/base/common/lifecycle';
import { ISaveOptions, IRevertOptions, SaveReason } from 'vs/workbench/common/editor';
import { ReadableStream } from 'vs/base/common/stream';
import { IBaseStatWithMetadata, IFileStatWithMetadata, IWriteFileOptions, FileOperationError, FileOperationResult, IReadFileStreamOptions } from 'vs/platform/files/common/files';
import { createDecorator } from 'vs/platform/instantiation/common/instantiation';
import { ITextEditorModel } from 'vs/editor/common/services/resolverService';
import { ITextBufferFactory, ITextModel, ITextSnapshot } from 'vs/editor/common/model';
import { VSBuffer, VSBufferReadable, VSBufferReadableStream } from 'vs/base/common/buffer';
import { areFunctions, isUndefinedOrNull } from 'vs/base/common/types';
import { IWorkingCopy } from 'vs/workbench/services/workingCopy/common/workingCopy';
import { IUntitledTextEditorModelManager } from 'vs/workbench/services/untitled/common/untitledTextEditorService';
import { CancellationToken } from 'vs/base/common/cancellation';
import { IProgress, IProgressStep } from 'vs/platform/progress/common/progress';
import { IFileOperationUndoRedoInfo } from 'vs/workbench/services/workingCopy/common/workingCopyFileService';
export const ITextFileService = createDecorator<ITextFileService>('textFileService');
export interface ITextFileService extends IDisposable {
readonly _serviceBrand: undefined;
/**
* Access to the manager of text file editor models providing further
* methods to work with them.
*/
readonly files: ITextFileEditorModelManager;
/**
* Access to the manager of untitled text editor models providing further
* methods to work with them.
*/
readonly untitled: IUntitledTextEditorModelManager;
/**
* Helper to determine encoding for resources.
*/
readonly encoding: IResourceEncodings;
/**
* A resource is dirty if it has unsaved changes or is an untitled file not yet saved.
*
* @param resource the resource to check for being dirty
*/
isDirty(resource: URI): boolean;
/**
* Saves the resource.
*
* @param resource the resource to save
* @param options optional save options
* @return Path of the saved resource or undefined if canceled.
*/
save(resource: URI, options?: ITextFileSaveOptions): Promise<URI | undefined>;
/**
* Saves the provided resource asking the user for a file name or using the provided one.
*
* @param resource the resource to save as.
* @param targetResource the optional target to save to.
* @param options optional save options
* @return Path of the saved resource or undefined if canceled.
*/
saveAs(resource: URI, targetResource?: URI, options?: ITextFileSaveAsOptions): Promise<URI | undefined>;
/**
* Reverts the provided resource.
*
* @param resource the resource of the file to revert.
* @param force to force revert even when the file is not dirty
*/
revert(resource: URI, options?: IRevertOptions): Promise<void>;
/**
* Read the contents of a file identified by the resource.
*/
read(resource: URI, options?: IReadTextFileOptions): Promise<ITextFileContent>;
/**
* Read the contents of a file identified by the resource as stream.
*/
readStream(resource: URI, options?: IReadTextFileOptions): Promise<ITextFileStreamContent>;
/**
* Update a file with given contents.
*/
write(resource: URI, value: string | ITextSnapshot, options?: IWriteTextFileOptions): Promise<IFileStatWithMetadata>;
/**
* Create files. If the file exists it will be overwritten with the contents if
* the options enable to overwrite.
*/
create(operations: { resource: URI, value?: string | ITextSnapshot, options?: { overwrite?: boolean } }[], undoInfo?: IFileOperationUndoRedoInfo): Promise<readonly IFileStatWithMetadata[]>;
/**
* Returns the readable that uses the appropriate encoding. This method should
* be used whenever a `string` or `ITextSnapshot` is being persisted to the
* file system.
*/
getEncodedReadable(resource: URI, value: ITextSnapshot, options?: IWriteTextFileOptions): Promise<VSBufferReadable>;
getEncodedReadable(resource: URI, value: string, options?: IWriteTextFileOptions): Promise<VSBuffer>;
getEncodedReadable(resource: URI, value?: ITextSnapshot, options?: IWriteTextFileOptions): Promise<VSBufferReadable | undefined>;
getEncodedReadable(resource: URI, value?: string, options?: IWriteTextFileOptions): Promise<VSBuffer | undefined>;
getEncodedReadable(resource: URI, value?: string | ITextSnapshot, options?: IWriteTextFileOptions): Promise<VSBuffer | VSBufferReadable | undefined>;
/**
* Returns a stream of strings that uses the appropriate encoding. This method should
* be used whenever a `VSBufferReadableStream` is being loaded from the file system.
*/
getDecodedStream(resource: URI, value: VSBufferReadableStream, options?: IReadTextFileEncodingOptions): Promise<ReadableStream<string>>;
}
export interface IReadTextFileEncodingOptions {
/**
* The optional encoding parameter allows to specify the desired encoding when resolving
* the contents of the file.
*/
readonly encoding?: string;
/**
* The optional guessEncoding parameter allows to guess encoding from content of the file.
*/
readonly autoGuessEncoding?: boolean;
}
export interface IReadTextFileOptions extends IReadTextFileEncodingOptions, IReadFileStreamOptions {
/**
* The optional acceptTextOnly parameter allows to fail this request early if the file
* contents are not textual.
*/
readonly acceptTextOnly?: boolean;
}
export interface IWriteTextFileOptions extends IWriteFileOptions {
/**
* The encoding to use when updating a file.
*/
readonly encoding?: string;
/**
* Whether to write to the file as elevated (admin) user. When setting this option a prompt will
* ask the user to authenticate as super user.
*/
readonly writeElevated?: boolean;
}
export const enum TextFileOperationResult {
FILE_IS_BINARY
}
export class TextFileOperationError extends FileOperationError {
static isTextFileOperationError(obj: unknown): obj is TextFileOperationError {
return obj instanceof Error && !isUndefinedOrNull((obj as TextFileOperationError).textFileOperationResult);
}
override readonly options?: IReadTextFileOptions & IWriteTextFileOptions;
constructor(
message: string,
public textFileOperationResult: TextFileOperationResult,
options?: IReadTextFileOptions & IWriteTextFileOptions
) {
super(message, FileOperationResult.FILE_OTHER_ERROR);
this.options = options;
}
}
export interface IResourceEncodings {
getPreferredWriteEncoding(resource: URI, preferredEncoding?: string): Promise<IResourceEncoding>;
}
export interface IResourceEncoding {
readonly encoding: string;
readonly hasBOM: boolean;
}
/**
* The save error handler can be installed on the text file editor model to install code that executes when save errors occur.
*/
export interface ISaveErrorHandler {
/**
* Called whenever a save fails.
*/
onSaveError(error: Error, model: ITextFileEditorModel): void;
}
/**
* States the text file editor model can be in.
*/
export const enum TextFileEditorModelState {
/**
* A model is saved.
*/
SAVED,
/**
* A model is dirty.
*/
DIRTY,
/**
* A model is currently being saved but this operation has not completed yet.
*/
PENDING_SAVE,
/**
* A model is in conflict mode when changes cannot be saved because the
* underlying file has changed. Models in conflict mode are always dirty.
*/
CONFLICT,
/**
* A model is in orphan state when the underlying file has been deleted.
*/
ORPHAN,
/**
* Any error that happens during a save that is not causing the CONFLICT state.
* Models in error mode are always dirty.
*/
ERROR
}
export const enum TextFileResolveReason {
EDITOR = 1,
REFERENCE = 2,
OTHER = 3
}
interface IBaseTextFileContent extends IBaseStatWithMetadata {
/**
* The encoding of the content if known.
*/
readonly encoding: string;
}
export interface ITextFileContent extends IBaseTextFileContent {
/**
* The content of a text file.
*/
readonly value: string;
}
export interface ITextFileStreamContent extends IBaseTextFileContent {
/**
* The line grouped content of a text file.
*/
readonly value: ITextBufferFactory;
}
export interface ITextFileEditorModelResolveOrCreateOptions {
/**
* Context why the model is being resolved or created.
*/
readonly reason?: TextFileResolveReason;
/**
* The language mode to use for the model text content.
*/
readonly mode?: string;
/**
* The encoding to use when resolving the model text content.
*/
readonly encoding?: string;
/**
* The contents to use for the model if known. If not
* provided, the contents will be retrieved from the
* underlying resource or backup if present.
*/
readonly contents?: ITextBufferFactory;
/**
* If the model was already resolved before, allows to trigger
* a reload of it to fetch the latest contents.
*/
readonly reload?: {
/**
* Controls whether the reload happens in the background
* or whether `resolve` will await the reload to happen.
*/
readonly async: boolean;
};
/**
* Allow to resolve a model even if we think it is a binary file.
*/
readonly allowBinary?: boolean;
}
export interface ITextFileSaveEvent {
readonly model: ITextFileEditorModel;
readonly reason: SaveReason;
}
export interface ITextFileResolveEvent {
readonly model: ITextFileEditorModel;
readonly reason: TextFileResolveReason;
}
export interface ITextFileSaveParticipant {
/**
* Participate in a save of a model. Allows to change the model
* before it is being saved to disk.
*/
participate(
model: ITextFileEditorModel,
context: { reason: SaveReason },
progress: IProgress<IProgressStep>,
token: CancellationToken
): Promise<void>;
}
export interface ITextFileEditorModelManager {
readonly onDidCreate: Event<ITextFileEditorModel>;
readonly onDidResolve: Event<ITextFileResolveEvent>;
readonly onDidChangeDirty: Event<ITextFileEditorModel>;
readonly onDidChangeReadonly: Event<ITextFileEditorModel>;
readonly onDidRemove: Event<URI>;
readonly onDidChangeOrphaned: Event<ITextFileEditorModel>;
readonly onDidChangeEncoding: Event<ITextFileEditorModel>;
readonly onDidSaveError: Event<ITextFileEditorModel>;
readonly onDidSave: Event<ITextFileSaveEvent>;
readonly onDidRevert: Event<ITextFileEditorModel>;
/**
* Access to all text file editor models in memory.
*/
readonly models: ITextFileEditorModel[];
/**
* Allows to configure the error handler that is called on save errors.
*/
saveErrorHandler: ISaveErrorHandler;
/**
* Returns the text file editor model for the provided resource
* or undefined if none.
*/
get(resource: URI): ITextFileEditorModel | undefined;
/**
* Allows to resolve a text file model from disk.
*/
resolve(resource: URI, options?: ITextFileEditorModelResolveOrCreateOptions): Promise<ITextFileEditorModel>;
/**
* Adds a participant for saving text file models.
*/
addSaveParticipant(participant: ITextFileSaveParticipant): IDisposable;
/**
* Runs the registered save participants on the provided model.
*/
runSaveParticipants(model: ITextFileEditorModel, context: { reason: SaveReason; }, token: CancellationToken): Promise<void>
/**
* Waits for the model to be ready to be disposed. There may be conditions
* under which the model cannot be disposed, e.g. when it is dirty. Once the
* promise is settled, it is safe to dispose the model.
*/
canDispose(model: ITextFileEditorModel): true | Promise<true>;
}
export interface ITextFileSaveOptions extends ISaveOptions {
/**
* Save the file with an attempt to unlock it.
*/
readonly writeUnlock?: boolean;
/**
* Save the file with elevated privileges.
*
* Note: This may not be supported in all environments.
*/
readonly writeElevated?: boolean;
/**
* Allows to write to a file even if it has been modified on disk.
*/
readonly ignoreModifiedSince?: boolean;
/**
* If set, will bubble up the error to the caller instead of handling it.
*/
readonly ignoreErrorHandler?: boolean;
}
export interface ITextFileSaveAsOptions extends ITextFileSaveOptions {
/**
* Optional URI to use as suggested file path to save as.
*/
readonly suggestedTarget?: URI;
}
export interface ITextFileResolveOptions {
/**
* The contents to use for the model if known. If not
* provided, the contents will be retrieved from the
* underlying resource or backup if present.
*/
readonly contents?: ITextBufferFactory;
/**
* Go to file bypassing any cache of the model if any.
*/
readonly forceReadFromFile?: boolean;
/**
* Allow to resolve a model even if we think it is a binary file.
*/
readonly allowBinary?: boolean;
/**
* Context why the model is being resolved.
*/
readonly reason?: TextFileResolveReason;
}
export const enum EncodingMode {
/**
* Instructs the encoding support to encode the object with the provided encoding
*/
Encode,
/**
* Instructs the encoding support to decode the object with the provided encoding
*/
Decode
}
export interface IEncodingSupport {
/**
* Gets the encoding of the object if known.
*/
getEncoding(): string | undefined;
/**
* Sets the encoding for the object for saving.
*/
setEncoding(encoding: string, mode: EncodingMode): Promise<void>;
}
export interface IModeSupport {
/**
* Sets the language mode of the object.
*/
setMode(mode: string, setExplicitly?: boolean): void;
}
export interface ITextFileEditorModel extends ITextEditorModel, IEncodingSupport, IModeSupport, IWorkingCopy {
readonly onDidChangeContent: Event<void>;
readonly onDidSaveError: Event<void>;
readonly onDidChangeOrphaned: Event<void>;
readonly onDidChangeReadonly: Event<void>;
readonly onDidChangeEncoding: Event<void>;
hasState(state: TextFileEditorModelState): boolean;
joinState(state: TextFileEditorModelState.PENDING_SAVE): Promise<void>;
updatePreferredEncoding(encoding: string | undefined): void;
save(options?: ITextFileSaveOptions): Promise<boolean>;
revert(options?: IRevertOptions): Promise<void>;
resolve(options?: ITextFileResolveOptions): Promise<void>;
isDirty(): this is IResolvedTextFileEditorModel;
getMode(): string | undefined;
isResolved(): this is IResolvedTextFileEditorModel;
}
export function isTextFileEditorModel(model: ITextEditorModel): model is ITextFileEditorModel {
const candidate = model as ITextFileEditorModel;
return areFunctions(candidate.setEncoding, candidate.getEncoding, candidate.save, candidate.revert, candidate.isDirty, candidate.getMode);
}
export interface IResolvedTextFileEditorModel extends ITextFileEditorModel {
readonly textEditorModel: ITextModel;
createSnapshot(): ITextSnapshot;
}
export function snapshotToString(snapshot: ITextSnapshot): string {
const chunks: string[] = [];
let chunk: string | null;
while (typeof (chunk = snapshot.read()) === 'string') {
chunks.push(chunk);
}
return chunks.join('');
}
export function stringToSnapshot(value: string): ITextSnapshot {
let done = false;
return {
read(): string | null {
if (!done) {
done = true;
return value;
}
return null;
}
};
}
export function toBufferOrReadable(value: string): VSBuffer;
export function toBufferOrReadable(value: ITextSnapshot): VSBufferReadable;
export function toBufferOrReadable(value: string | ITextSnapshot): VSBuffer | VSBufferReadable;
export function toBufferOrReadable(value: string | ITextSnapshot | undefined): VSBuffer | VSBufferReadable | undefined;
export function toBufferOrReadable(value: string | ITextSnapshot | undefined): VSBuffer | VSBufferReadable | undefined {
if (typeof value === 'undefined') {
return undefined;
}
if (typeof value === 'string') {
return VSBuffer.fromString(value);
}
return {
read: () => {
const chunk = value.read();
if (typeof chunk === 'string') {
return VSBuffer.fromString(chunk);
}
return null;
}
};
}
| src/vs/workbench/services/textfile/common/textfiles.ts | 0 | https://github.com/microsoft/vscode/commit/f18b29e132039246caebd4c6b52fcff06265c04d | [
0.0001792404509615153,
0.0001705073082121089,
0.0001632959902053699,
0.00017068046145141125,
0.0000035497905628290027
] |
{
"id": 5,
"code_window": [
"\t}\n",
"\n",
"\t@debounce(2000)\n",
"\tprivate eventuallyFinishLoading(): void {\n",
"\t\tthis.logService.trace('SCMViewService#eventuallyFinishLoading');\n",
"\t\tthis.finishLoading();\n",
"\t}\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [],
"file_path": "src/vs/workbench/contrib/scm/browser/scmViewService.ts",
"type": "replace",
"edit_start_line_idx": 259
} | #!/usr/bin/env bash
# This file is used to archive off a copy of any differences in the source tree into another location
# in the image. Once the codespace / container is up, this will be restored into its proper location.
set -e
SCRIPT_PATH="$(cd $(dirname "${BASH_SOURCE[0]}") && pwd)"
SOURCE_FOLDER="${1:-"."}"
CACHE_FOLDER="${2:-"/usr/local/etc/devcontainer-cache"}"
echo "[$(date)] Starting cache operation..."
cd "${SOURCE_FOLDER}"
echo "[$(date)] Determining diffs..."
find -L . -not -path "*/.git/*" -and -not -path "${SCRIPT_PATH}/*.manifest" -type f > "${SCRIPT_PATH}/after.manifest"
grep -Fxvf "${SCRIPT_PATH}/before.manifest" "${SCRIPT_PATH}/after.manifest" > "${SCRIPT_PATH}/cache.manifest"
echo "[$(date)] Archiving diffs..."
mkdir -p "${CACHE_FOLDER}"
tar -cf "${CACHE_FOLDER}/cache.tar" --totals --files-from "${SCRIPT_PATH}/cache.manifest"
echo "[$(date)] Done! $(du -h "${CACHE_FOLDER}/cache.tar")"
| .devcontainer/cache/cache-diff.sh | 0 | https://github.com/microsoft/vscode/commit/f18b29e132039246caebd4c6b52fcff06265c04d | [
0.00017966718587558717,
0.0001731917873257771,
0.00016827398212626576,
0.00017163420852739364,
0.000004779876235261327
] |
{
"id": 6,
"code_window": [
"\t\t\treturn;\n",
"\t\t}\n",
"\n",
"\t\tthis.logService.trace('SCMViewService#finishLoading');\n",
"\t\tthis.didFinishLoading = true;\n",
"\t\tthis.previousState = undefined;\n",
"\t}\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [],
"file_path": "src/vs/workbench/contrib/scm/browser/scmViewService.ts",
"type": "replace",
"edit_start_line_idx": 268
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import { DisposableStore } from 'vs/base/common/lifecycle';
import { Emitter, Event } from 'vs/base/common/event';
import { ISCMViewService, ISCMRepository, ISCMService, ISCMViewVisibleRepositoryChangeEvent, ISCMMenus, ISCMProvider } from 'vs/workbench/contrib/scm/common/scm';
import { Iterable } from 'vs/base/common/iterator';
import { IInstantiationService } from 'vs/platform/instantiation/common/instantiation';
import { SCMMenus } from 'vs/workbench/contrib/scm/browser/menus';
import { IStorageService, StorageScope, StorageTarget } from 'vs/platform/storage/common/storage';
import { debounce } from 'vs/base/common/decorators';
import { ILogService } from 'vs/platform/log/common/log';
function getProviderStorageKey(provider: ISCMProvider): string {
return `${provider.contextValue}:${provider.label}${provider.rootUri ? `:${provider.rootUri.toString()}` : ''}`;
}
export interface ISCMViewServiceState {
readonly all: string[];
readonly visible: number[];
}
export class SCMViewService implements ISCMViewService {
declare readonly _serviceBrand: undefined;
readonly menus: ISCMMenus;
private didFinishLoading: boolean = false;
private provisionalVisibleRepository: ISCMRepository | undefined;
private previousState: ISCMViewServiceState | undefined;
private disposables = new DisposableStore();
private _visibleRepositoriesSet = new Set<ISCMRepository>();
private _visibleRepositories: ISCMRepository[] = [];
get visibleRepositories(): ISCMRepository[] {
return this._visibleRepositories;
}
set visibleRepositories(visibleRepositories: ISCMRepository[]) {
const set = new Set(visibleRepositories);
const added = new Set<ISCMRepository>();
const removed = new Set<ISCMRepository>();
for (const repository of visibleRepositories) {
if (!this._visibleRepositoriesSet.has(repository)) {
added.add(repository);
}
}
for (const repository of this._visibleRepositories) {
if (!set.has(repository)) {
removed.add(repository);
}
}
if (added.size === 0 && removed.size === 0) {
return;
}
this._visibleRepositories = visibleRepositories;
this._visibleRepositoriesSet = set;
this._onDidSetVisibleRepositories.fire({ added, removed });
if (this._focusedRepository && removed.has(this._focusedRepository)) {
this.focus(this._visibleRepositories[0]);
}
}
private _onDidChangeRepositories = new Emitter<ISCMViewVisibleRepositoryChangeEvent>();
private _onDidSetVisibleRepositories = new Emitter<ISCMViewVisibleRepositoryChangeEvent>();
readonly onDidChangeVisibleRepositories = Event.any(
this._onDidSetVisibleRepositories.event,
Event.debounce(
this._onDidChangeRepositories.event,
(last, e) => {
if (!last) {
return e;
}
return {
added: Iterable.concat(last.added, e.added),
removed: Iterable.concat(last.removed, e.removed),
};
}, 0)
);
private _focusedRepository: ISCMRepository | undefined;
get focusedRepository(): ISCMRepository | undefined {
return this._focusedRepository;
}
private _onDidFocusRepository = new Emitter<ISCMRepository | undefined>();
readonly onDidFocusRepository = this._onDidFocusRepository.event;
constructor(
@ISCMService private readonly scmService: ISCMService,
@IInstantiationService instantiationService: IInstantiationService,
@IStorageService private readonly storageService: IStorageService,
@ILogService private readonly logService: ILogService
) {
this.menus = instantiationService.createInstance(SCMMenus);
scmService.onDidAddRepository(this.onDidAddRepository, this, this.disposables);
scmService.onDidRemoveRepository(this.onDidRemoveRepository, this, this.disposables);
for (const repository of scmService.repositories) {
this.onDidAddRepository(repository);
}
try {
this.previousState = JSON.parse(storageService.get('scm:view:visibleRepositories', StorageScope.WORKSPACE, ''));
this.eventuallyFinishLoading();
} catch {
// noop
}
storageService.onWillSaveState(this.onWillSaveState, this, this.disposables);
}
private onDidAddRepository(repository: ISCMRepository): void {
this.logService.trace('SCMViewService#onDidAddRepository', getProviderStorageKey(repository.provider));
if (!this.didFinishLoading) {
this.eventuallyFinishLoading();
}
let removed: Iterable<ISCMRepository> = Iterable.empty();
if (this.previousState) {
const index = this.previousState.all.indexOf(getProviderStorageKey(repository.provider));
if (index === -1) { // saw a repo we did not expect
this.logService.trace('SCMViewService#onDidAddRepository', 'This is a new repository, so we stop the heuristics');
const added: ISCMRepository[] = [];
for (const repo of this.scmService.repositories) { // all should be visible
if (!this._visibleRepositoriesSet.has(repo)) {
added.push(repository);
}
}
this._visibleRepositories = [...this.scmService.repositories];
this._visibleRepositoriesSet = new Set(this.scmService.repositories);
this._onDidChangeRepositories.fire({ added, removed: Iterable.empty() });
this.finishLoading();
return;
}
const visible = this.previousState.visible.indexOf(index) > -1;
if (!visible) {
if (this._visibleRepositories.length === 0) { // should make it visible, until other repos come along
this.provisionalVisibleRepository = repository;
} else {
return;
}
} else {
if (this.provisionalVisibleRepository) {
this._visibleRepositories = [];
this._visibleRepositoriesSet = new Set();
removed = [this.provisionalVisibleRepository];
this.provisionalVisibleRepository = undefined;
}
}
}
this._visibleRepositories.push(repository);
this._visibleRepositoriesSet.add(repository);
this._onDidChangeRepositories.fire({ added: [repository], removed });
if (!this._focusedRepository) {
this.focus(repository);
}
}
private onDidRemoveRepository(repository: ISCMRepository): void {
this.logService.trace('SCMViewService#onDidRemoveRepository', getProviderStorageKey(repository.provider));
if (!this.didFinishLoading) {
this.eventuallyFinishLoading();
}
const index = this._visibleRepositories.indexOf(repository);
if (index > -1) {
let added: Iterable<ISCMRepository> = Iterable.empty();
this._visibleRepositories.splice(index, 1);
this._visibleRepositoriesSet.delete(repository);
if (this._visibleRepositories.length === 0 && this.scmService.repositories.length > 0) {
const first = this.scmService.repositories[0];
this._visibleRepositories.push(first);
this._visibleRepositoriesSet.add(first);
added = [first];
}
this._onDidChangeRepositories.fire({ added, removed: [repository] });
}
if (this._focusedRepository === repository) {
this.focus(this._visibleRepositories[0]);
}
}
isVisible(repository: ISCMRepository): boolean {
return this._visibleRepositoriesSet.has(repository);
}
toggleVisibility(repository: ISCMRepository, visible?: boolean): void {
if (typeof visible === 'undefined') {
visible = !this.isVisible(repository);
} else if (this.isVisible(repository) === visible) {
return;
}
if (visible) {
this.visibleRepositories = [...this.visibleRepositories, repository];
} else {
const index = this.visibleRepositories.indexOf(repository);
if (index > -1) {
this.visibleRepositories = [
...this.visibleRepositories.slice(0, index),
...this.visibleRepositories.slice(index + 1)
];
}
}
}
focus(repository: ISCMRepository | undefined): void {
if (repository && !this.visibleRepositories.includes(repository)) {
return;
}
this._focusedRepository = repository;
this._onDidFocusRepository.fire(repository);
}
private onWillSaveState(): void {
if (!this.didFinishLoading) { // don't remember state, if the workbench didn't really finish loading
return;
}
const all = this.scmService.repositories.map(r => getProviderStorageKey(r.provider));
const visible = this.visibleRepositories.map(r => all.indexOf(getProviderStorageKey(r.provider)));
const raw = JSON.stringify({ all, visible });
this.storageService.store('scm:view:visibleRepositories', raw, StorageScope.WORKSPACE, StorageTarget.MACHINE);
}
@debounce(2000)
private eventuallyFinishLoading(): void {
this.logService.trace('SCMViewService#eventuallyFinishLoading');
this.finishLoading();
}
private finishLoading(): void {
if (this.didFinishLoading) {
return;
}
this.logService.trace('SCMViewService#finishLoading');
this.didFinishLoading = true;
this.previousState = undefined;
}
dispose(): void {
this.disposables.dispose();
this._onDidChangeRepositories.dispose();
this._onDidSetVisibleRepositories.dispose();
}
}
| src/vs/workbench/contrib/scm/browser/scmViewService.ts | 1 | https://github.com/microsoft/vscode/commit/f18b29e132039246caebd4c6b52fcff06265c04d | [
0.9962521195411682,
0.16233673691749573,
0.00016443582717329264,
0.0002868008450604975,
0.3485143184661865
] |
{
"id": 6,
"code_window": [
"\t\t\treturn;\n",
"\t\t}\n",
"\n",
"\t\tthis.logService.trace('SCMViewService#finishLoading');\n",
"\t\tthis.didFinishLoading = true;\n",
"\t\tthis.previousState = undefined;\n",
"\t}\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [],
"file_path": "src/vs/workbench/contrib/scm/browser/scmViewService.ts",
"type": "replace",
"edit_start_line_idx": 268
} | {
"extends": "../../tsconfig.base.json",
"compilerOptions": {
"outDir": "./out"
},
"include": [
"src/**/*"
]
}
| extensions/css-language-features/server/tsconfig.json | 0 | https://github.com/microsoft/vscode/commit/f18b29e132039246caebd4c6b52fcff06265c04d | [
0.00017206367920152843,
0.00017206367920152843,
0.00017206367920152843,
0.00017206367920152843,
0
] |
{
"id": 6,
"code_window": [
"\t\t\treturn;\n",
"\t\t}\n",
"\n",
"\t\tthis.logService.trace('SCMViewService#finishLoading');\n",
"\t\tthis.didFinishLoading = true;\n",
"\t\tthis.previousState = undefined;\n",
"\t}\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [],
"file_path": "src/vs/workbench/contrib/scm/browser/scmViewService.ts",
"type": "replace",
"edit_start_line_idx": 268
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import * as glob from 'vs/base/common/glob';
import { URI, UriComponents } from 'vs/base/common/uri';
import { CommandsRegistry } from 'vs/platform/commands/common/commands';
import { isDocumentExcludePattern, TransientCellMetadata, TransientDocumentMetadata } from 'vs/workbench/contrib/notebook/common/notebookCommon';
import { INotebookKernelService } from 'vs/workbench/contrib/notebook/common/notebookKernelService';
import { INotebookService } from 'vs/workbench/contrib/notebook/common/notebookService';
CommandsRegistry.registerCommand('_resolveNotebookContentProvider', (accessor, args): {
viewType: string;
displayName: string;
options: { transientOutputs: boolean; transientCellMetadata: TransientCellMetadata; transientDocumentMetadata: TransientDocumentMetadata; };
filenamePattern: (string | glob.IRelativePattern | { include: string | glob.IRelativePattern, exclude: string | glob.IRelativePattern; })[];
}[] => {
const notebookService = accessor.get<INotebookService>(INotebookService);
const contentProviders = notebookService.getContributedNotebookTypes();
return contentProviders.map(provider => {
const filenamePatterns = provider.selectors.map(selector => {
if (typeof selector === 'string') {
return selector;
}
if (glob.isRelativePattern(selector)) {
return selector;
}
if (isDocumentExcludePattern(selector)) {
return {
include: selector.include,
exclude: selector.exclude
};
}
return null;
}).filter(pattern => pattern !== null) as (string | glob.IRelativePattern | { include: string | glob.IRelativePattern, exclude: string | glob.IRelativePattern; })[];
return {
viewType: provider.id,
displayName: provider.displayName,
filenamePattern: filenamePatterns,
options: {
transientCellMetadata: provider.options.transientCellMetadata,
transientDocumentMetadata: provider.options.transientDocumentMetadata,
transientOutputs: provider.options.transientOutputs
}
};
});
});
CommandsRegistry.registerCommand('_resolveNotebookKernels', async (accessor, args: {
viewType: string;
uri: UriComponents;
}): Promise<{
id?: string;
label: string;
description?: string;
detail?: string;
isPreferred?: boolean;
preloads?: URI[];
}[]> => {
const notebookKernelService = accessor.get(INotebookKernelService);
const uri = URI.revive(args.uri as UriComponents);
const kernels = notebookKernelService.getMatchingKernel({ uri, viewType: args.viewType });
return kernels.all.map(provider => ({
id: provider.id,
label: provider.label,
kind: provider.kind,
description: provider.description,
detail: provider.detail,
isPreferred: false, // todo@jrieken,@rebornix
preloads: provider.preloadUris,
}));
});
| src/vs/workbench/contrib/notebook/browser/controller/apiActions.ts | 0 | https://github.com/microsoft/vscode/commit/f18b29e132039246caebd4c6b52fcff06265c04d | [
0.00017398220370523632,
0.00017111467604991049,
0.00016632257029414177,
0.00017143884906545281,
0.0000022689443994750036
] |
{
"id": 6,
"code_window": [
"\t\t\treturn;\n",
"\t\t}\n",
"\n",
"\t\tthis.logService.trace('SCMViewService#finishLoading');\n",
"\t\tthis.didFinishLoading = true;\n",
"\t\tthis.previousState = undefined;\n",
"\t}\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [],
"file_path": "src/vs/workbench/contrib/scm/browser/scmViewService.ts",
"type": "replace",
"edit_start_line_idx": 268
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import { localize } from 'vs/nls';
import { IWorkingCopyBackupService } from 'vs/workbench/services/workingCopy/common/workingCopyBackup';
import { IWorkbenchContribution } from 'vs/workbench/common/contributions';
import { IFilesConfigurationService, AutoSaveMode } from 'vs/workbench/services/filesConfiguration/common/filesConfigurationService';
import { IWorkingCopyService } from 'vs/workbench/services/workingCopy/common/workingCopyService';
import { IWorkingCopy, IWorkingCopyIdentifier, WorkingCopyCapabilities } from 'vs/workbench/services/workingCopy/common/workingCopy';
import { ILifecycleService, ShutdownReason } from 'vs/workbench/services/lifecycle/common/lifecycle';
import { ConfirmResult, IFileDialogService, IDialogService, getFileNamesMessage } from 'vs/platform/dialogs/common/dialogs';
import Severity from 'vs/base/common/severity';
import { WorkbenchState, IWorkspaceContextService } from 'vs/platform/workspace/common/workspace';
import { isMacintosh } from 'vs/base/common/platform';
import { HotExitConfiguration } from 'vs/platform/files/common/files';
import { INativeHostService } from 'vs/platform/native/electron-sandbox/native';
import { WorkingCopyBackupTracker } from 'vs/workbench/services/workingCopy/common/workingCopyBackupTracker';
import { ILogService } from 'vs/platform/log/common/log';
import { IEditorService } from 'vs/workbench/services/editor/common/editorService';
import { SaveReason } from 'vs/workbench/common/editor';
import { IEnvironmentService } from 'vs/platform/environment/common/environment';
import { CancellationToken, CancellationTokenSource } from 'vs/base/common/cancellation';
import { IProgressService, ProgressLocation } from 'vs/platform/progress/common/progress';
import { Promises, raceCancellation } from 'vs/base/common/async';
import { IWorkingCopyEditorService } from 'vs/workbench/services/workingCopy/common/workingCopyEditorService';
import { IEditorGroupsService } from 'vs/workbench/services/editor/common/editorGroupsService';
export class NativeWorkingCopyBackupTracker extends WorkingCopyBackupTracker implements IWorkbenchContribution {
constructor(
@IWorkingCopyBackupService workingCopyBackupService: IWorkingCopyBackupService,
@IFilesConfigurationService filesConfigurationService: IFilesConfigurationService,
@IWorkingCopyService workingCopyService: IWorkingCopyService,
@ILifecycleService lifecycleService: ILifecycleService,
@IFileDialogService private readonly fileDialogService: IFileDialogService,
@IDialogService private readonly dialogService: IDialogService,
@IWorkspaceContextService private readonly contextService: IWorkspaceContextService,
@INativeHostService private readonly nativeHostService: INativeHostService,
@ILogService logService: ILogService,
@IEnvironmentService private readonly environmentService: IEnvironmentService,
@IProgressService private readonly progressService: IProgressService,
@IWorkingCopyEditorService workingCopyEditorService: IWorkingCopyEditorService,
@IEditorService editorService: IEditorService,
@IEditorGroupsService editorGroupService: IEditorGroupsService
) {
super(workingCopyBackupService, workingCopyService, logService, lifecycleService, filesConfigurationService, workingCopyEditorService, editorService, editorGroupService);
}
protected onBeforeShutdown(reason: ShutdownReason): boolean | Promise<boolean> {
// Dirty working copies need treatment on shutdown
const dirtyWorkingCopies = this.workingCopyService.dirtyWorkingCopies;
if (dirtyWorkingCopies.length) {
return this.onBeforeShutdownWithDirty(reason, dirtyWorkingCopies);
}
// No dirty working copies
return this.onBeforeShutdownWithoutDirty();
}
protected async onBeforeShutdownWithDirty(reason: ShutdownReason, dirtyWorkingCopies: readonly IWorkingCopy[]): Promise<boolean> {
// If auto save is enabled, save all non-untitled working copies
// and then check again for dirty copies
if (this.filesConfigurationService.getAutoSaveMode() !== AutoSaveMode.OFF) {
// Save all dirty working copies
try {
await this.doSaveAllBeforeShutdown(false /* not untitled */, SaveReason.AUTO);
} catch (error) {
this.logService.error(`[backup tracker] error saving dirty working copies: ${error}`); // guard against misbehaving saves, we handle remaining dirty below
}
// If we still have dirty working copies, we either have untitled ones or working copies that cannot be saved
const remainingDirtyWorkingCopies = this.workingCopyService.dirtyWorkingCopies;
if (remainingDirtyWorkingCopies.length) {
return this.handleDirtyBeforeShutdown(remainingDirtyWorkingCopies, reason);
}
return false; // no veto (there are no remaining dirty working copies)
}
// Auto save is not enabled
return this.handleDirtyBeforeShutdown(dirtyWorkingCopies, reason);
}
private async handleDirtyBeforeShutdown(dirtyWorkingCopies: readonly IWorkingCopy[], reason: ShutdownReason): Promise<boolean> {
// Trigger backup if configured
let backups: IWorkingCopy[] = [];
let backupError: Error | undefined = undefined;
if (this.filesConfigurationService.isHotExitEnabled) {
try {
const backupResult = await this.backupBeforeShutdown(dirtyWorkingCopies, reason);
backups = backupResult.backups;
backupError = backupResult.error;
if (backups.length === dirtyWorkingCopies.length) {
return false; // no veto (backup was successful for all working copies)
}
} catch (error) {
backupError = error;
}
}
const remainingDirtyWorkingCopies = dirtyWorkingCopies.filter(workingCopy => !backups.includes(workingCopy));
// We ran a backup but received an error that we show to the user
if (backupError) {
if (this.environmentService.isExtensionDevelopment) {
this.logService.error(`[backup tracker] error creating backups: ${backupError}`);
return false; // do not block shutdown during extension development (https://github.com/microsoft/vscode/issues/115028)
}
this.showErrorDialog(localize('backupTrackerBackupFailed', "The following editors with unsaved changes could not be saved to the back up location."), remainingDirtyWorkingCopies, backupError);
return true; // veto (the backup failed)
}
// Since a backup did not happen, we have to confirm for
// the working copies that did not successfully backup
try {
return await this.confirmBeforeShutdown(remainingDirtyWorkingCopies);
} catch (error) {
if (this.environmentService.isExtensionDevelopment) {
this.logService.error(`[backup tracker] error saving or reverting dirty working copies: ${error}`);
return false; // do not block shutdown during extension development (https://github.com/microsoft/vscode/issues/115028)
}
this.showErrorDialog(localize('backupTrackerConfirmFailed', "The following editors with unsaved changes could not be saved or reverted."), remainingDirtyWorkingCopies, error);
return true; // veto (save or revert failed)
}
}
private showErrorDialog(msg: string, workingCopies: readonly IWorkingCopy[], error?: Error): void {
const dirtyWorkingCopies = workingCopies.filter(workingCopy => workingCopy.isDirty());
const advice = localize('backupErrorDetails', "Try saving or reverting the editors with unsaved changes first and then try again.");
const detail = dirtyWorkingCopies.length
? getFileNamesMessage(dirtyWorkingCopies.map(x => x.name)) + '\n' + advice
: advice;
this.dialogService.show(Severity.Error, msg, undefined, { detail });
this.logService.error(error ? `[backup tracker] ${msg}: ${error}` : `[backup tracker] ${msg}`);
}
private async backupBeforeShutdown(dirtyWorkingCopies: readonly IWorkingCopy[], reason: ShutdownReason): Promise<{ backups: IWorkingCopy[], error?: Error }> {
// 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;
if (this.environmentService.isExtensionDevelopment) {
doBackup = true; // always backup closing extension development window without asking to speed up debugging
} else {
switch (reason) {
case ShutdownReason.CLOSE:
if (this.contextService.getWorkbenchState() !== WorkbenchState.EMPTY && this.filesConfigurationService.hotExitConfiguration === HotExitConfiguration.ON_EXIT_AND_WINDOW_CLOSE) {
doBackup = true; // backup if a folder is open and onExitAndWindowClose is configured
} else if (await this.nativeHostService.getWindowCount() > 1 || 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.filesConfigurationService.hotExitConfiguration === 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 { backups: [] };
}
return this.doBackupBeforeShutdown(dirtyWorkingCopies);
}
private async doBackupBeforeShutdown(dirtyWorkingCopies: readonly IWorkingCopy[]): Promise<{ backups: IWorkingCopy[], error?: Error }> {
const backups: IWorkingCopy[] = [];
let error: Error | undefined = undefined;
await this.withProgressAndCancellation(async token => {
// Perform a backup of all dirty working copies unless a backup already exists
try {
await Promises.settled(dirtyWorkingCopies.map(async workingCopy => {
const contentVersion = this.getContentVersion(workingCopy);
// Backup exists
if (this.workingCopyBackupService.hasBackupSync(workingCopy, contentVersion)) {
backups.push(workingCopy);
}
// Backup does not exist
else {
const backup = await workingCopy.backup(token);
await this.workingCopyBackupService.backup(workingCopy, backup.content, contentVersion, backup.meta, token);
backups.push(workingCopy);
}
}));
} catch (backupError) {
error = backupError;
}
},
localize('backupBeforeShutdownMessage', "Backing up editors with unsaved changes is taking longer than expected..."),
localize('backupBeforeShutdownDetail', "Click 'Cancel' to stop waiting and to save or revert editors with unsaved changes.")
);
return { backups, error };
}
private async confirmBeforeShutdown(dirtyWorkingCopies: IWorkingCopy[]): Promise<boolean> {
// Save
const confirm = await this.fileDialogService.showSaveConfirm(dirtyWorkingCopies.map(workingCopy => workingCopy.name));
if (confirm === ConfirmResult.SAVE) {
const dirtyCountBeforeSave = this.workingCopyService.dirtyCount;
try {
await this.doSaveAllBeforeShutdown(dirtyWorkingCopies, SaveReason.EXPLICIT);
} catch (error) {
this.logService.error(`[backup tracker] error saving dirty working copies: ${error}`); // guard against misbehaving saves, we handle remaining dirty below
}
const savedWorkingCopies = dirtyCountBeforeSave - this.workingCopyService.dirtyCount;
if (savedWorkingCopies < dirtyWorkingCopies.length) {
return true; // veto (save failed or was canceled)
}
return this.noVeto(dirtyWorkingCopies); // no veto (dirty saved)
}
// Don't Save
else if (confirm === ConfirmResult.DONT_SAVE) {
try {
await this.doRevertAllBeforeShutdown(dirtyWorkingCopies);
} catch (error) {
this.logService.error(`[backup tracker] error reverting dirty working copies: ${error}`); // do not block the shutdown on errors from revert
}
return this.noVeto(dirtyWorkingCopies); // no veto (dirty reverted)
}
// Cancel
return true; // veto (user canceled)
}
private doSaveAllBeforeShutdown(dirtyWorkingCopies: IWorkingCopy[], reason: SaveReason): Promise<void>;
private doSaveAllBeforeShutdown(includeUntitled: boolean, reason: SaveReason): Promise<void>;
private doSaveAllBeforeShutdown(arg1: IWorkingCopy[] | boolean, reason: SaveReason): Promise<void> {
const dirtyWorkingCopies = Array.isArray(arg1) ? arg1 : this.workingCopyService.dirtyWorkingCopies.filter(workingCopy => {
if (arg1 === false && (workingCopy.capabilities & WorkingCopyCapabilities.Untitled)) {
return false; // skip untitled unless explicitly included
}
return true;
});
return this.withProgressAndCancellation(async () => {
// Skip save participants on shutdown for performance reasons
const saveOptions = { skipSaveParticipants: true, reason };
// First save through the editor service if we save all to benefit
// from some extras like switching to untitled dirty editors before saving.
let result: boolean | undefined = undefined;
if (typeof arg1 === 'boolean' || dirtyWorkingCopies.length === this.workingCopyService.dirtyCount) {
result = await this.editorService.saveAll({ includeUntitled: typeof arg1 === 'boolean' ? arg1 : true, ...saveOptions });
}
// If we still have dirty working copies, save those directly
// unless the save was not successful (e.g. cancelled)
if (result !== false) {
await Promises.settled(dirtyWorkingCopies.map(workingCopy => workingCopy.isDirty() ? workingCopy.save(saveOptions) : Promise.resolve(true)));
}
}, localize('saveBeforeShutdown', "Saving editors with unsaved changes is taking longer than expected..."));
}
private doRevertAllBeforeShutdown(dirtyWorkingCopies: IWorkingCopy[]): Promise<void> {
return this.withProgressAndCancellation(async () => {
// Soft revert is good enough on shutdown
const revertOptions = { soft: true };
// First revert through the editor service if we revert all
if (dirtyWorkingCopies.length === this.workingCopyService.dirtyCount) {
await this.editorService.revertAll(revertOptions);
}
// If we still have dirty working copies, revert those directly
// unless the revert operation was not successful (e.g. cancelled)
await Promises.settled(dirtyWorkingCopies.map(workingCopy => workingCopy.isDirty() ? workingCopy.revert(revertOptions) : Promise.resolve()));
}, localize('revertBeforeShutdown', "Reverting editors with unsaved changes is taking longer than expected..."));
}
private withProgressAndCancellation(promiseFactory: (token: CancellationToken) => Promise<void>, title: string, detail?: string): Promise<void> {
const cts = new CancellationTokenSource();
return this.progressService.withProgress({
location: ProgressLocation.Dialog, // use a dialog to prevent the user from making any more changes now (https://github.com/microsoft/vscode/issues/122774)
cancellable: true, // allow to cancel (https://github.com/microsoft/vscode/issues/112278)
delay: 800, // delay notification so that it only appears when operation takes a long time
title,
detail
}, () => raceCancellation(promiseFactory(cts.token), cts.token), () => cts.dispose(true));
}
private async noVeto(backupsToDiscard: IWorkingCopyIdentifier[]): Promise<boolean> {
// Discard backups from working copies the
// user either saved or reverted
await this.discardBackupsBeforeShutdown(backupsToDiscard);
return false; // no veto (no dirty)
}
private async onBeforeShutdownWithoutDirty(): Promise<boolean> {
// We are about to shutdown without dirty editors
// and will discard any backups that are still
// around that have not been handled depending
// on the window state.
//
// Empty window: discard even unrestored backups to
// prevent empty windows from restoring that cannot
// be closed (workaround for not having implemented
// https://github.com/microsoft/vscode/issues/127163
// and a fix for what users have reported in issue
// https://github.com/microsoft/vscode/issues/126725)
//
// Workspace/Folder window: do not discard unrestored
// backups to give a chance to restore them in the
// future. Since we do not restore workspace/folder
// windows with backups, this is fine.
await this.discardBackupsBeforeShutdown({ except: this.contextService.getWorkbenchState() === WorkbenchState.EMPTY ? [] : Array.from(this.unrestoredBackups) });
return false; // no veto (no dirty)
}
private discardBackupsBeforeShutdown(backupsToDiscard: IWorkingCopyIdentifier[]): Promise<void>;
private discardBackupsBeforeShutdown(backupsToKeep: { except: IWorkingCopyIdentifier[] }): Promise<void>;
private async discardBackupsBeforeShutdown(arg1: IWorkingCopyIdentifier[] | { except: IWorkingCopyIdentifier[] }): Promise<void> {
// We never discard any backups before we are ready
// and have resolved all backups that exist. This
// is important to not loose backups that have not
// been handled.
if (!this.isReady) {
return;
}
// When we shutdown either with no dirty working copies left
// or with some handled, we start to discard these backups
// to free them up. This helps to get rid of stale backups
// as reported in https://github.com/microsoft/vscode/issues/92962
//
// However, we never want to discard backups that we know
// were not restored in the session.
try {
if (Array.isArray(arg1)) {
await Promises.settled(arg1.map(workingCopy => this.workingCopyBackupService.discardBackup(workingCopy)));
} else {
await this.workingCopyBackupService.discardBackups(arg1);
}
} catch (error) {
this.logService.error(`[backup tracker] error discarding backups: ${error}`);
}
}
}
| src/vs/workbench/services/workingCopy/electron-sandbox/workingCopyBackupTracker.ts | 0 | https://github.com/microsoft/vscode/commit/f18b29e132039246caebd4c6b52fcff06265c04d | [
0.00017550996562931687,
0.0001680815767031163,
0.00016368024807889014,
0.00016787057393230498,
0.0000030476346637442475
] |
{
"id": 0,
"code_window": [
" // return null as there is no metadata where an input could be declared.\n",
" if (!decorator) {\n",
" return null;\n",
" }\n",
"\n",
" const decoratorCall = decorator.node.expression as ts.CallExpression;\n",
"\n",
" // In case the decorator does define any metadata, there is no metadata\n",
" // where inputs could be declared. This is an edge case because there\n",
" // always needs to be an object literal, but in case there isn't we just\n",
" // want to skip the invalid decorator and return null.\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" const decoratorCall = decorator.node.expression;\n"
],
"file_path": "packages/core/schematics/migrations/static-queries/angular/directive_inputs.ts",
"type": "replace",
"edit_start_line_idx": 64
} | /**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
import * as ts from 'typescript';
import {getCallDecoratorImport} from './typescript/decorators';
export interface NgDecorator {
name: string;
node: ts.Decorator;
}
/**
* Gets all decorators which are imported from an Angular package (e.g. "@angular/core")
* from a list of decorators.
*/
export function getAngularDecorators(
typeChecker: ts.TypeChecker, decorators: ReadonlyArray<ts.Decorator>): NgDecorator[] {
return decorators.map(node => ({node, importData: getCallDecoratorImport(typeChecker, node)}))
.filter(({importData}) => importData && importData.importModule.startsWith('@angular/'))
.map(({node, importData}) => ({node, name: importData !.name}));
}
| packages/core/schematics/utils/ng_decorators.ts | 1 | https://github.com/angular/angular/commit/15eb1e0ce1ce7fbd7a833cef3f76c53297f7e24f | [
0.0006810075719840825,
0.0003616556932684034,
0.00017256020510103554,
0.00023139920085668564,
0.0002270899130962789
] |
{
"id": 0,
"code_window": [
" // return null as there is no metadata where an input could be declared.\n",
" if (!decorator) {\n",
" return null;\n",
" }\n",
"\n",
" const decoratorCall = decorator.node.expression as ts.CallExpression;\n",
"\n",
" // In case the decorator does define any metadata, there is no metadata\n",
" // where inputs could be declared. This is an edge case because there\n",
" // always needs to be an object literal, but in case there isn't we just\n",
" // want to skip the invalid decorator and return null.\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" const decoratorCall = decorator.node.expression;\n"
],
"file_path": "packages/core/schematics/migrations/static-queries/angular/directive_inputs.ts",
"type": "replace",
"edit_start_line_idx": 64
} | /**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
// THIS CODE IS GENERATED - DO NOT MODIFY
// See angular/tools/gulp-tasks/cldr/extract.js
const u = undefined;
function plural(n: number): number {
return 5;
}
export default [
'kde', [['Muhi', 'Chilo'], u, u], u,
[
['2', '3', '4', '5', '6', '7', '1'], ['Ll2', 'Ll3', 'Ll4', 'Ll5', 'Ll6', 'Ll7', 'Ll1'],
[
'Liduva lyapili', 'Liduva lyatatu', 'Liduva lyanchechi', 'Liduva lyannyano',
'Liduva lyannyano na linji', 'Liduva lyannyano na mavili', 'Liduva litandi'
],
['Ll2', 'Ll3', 'Ll4', 'Ll5', 'Ll6', 'Ll7', 'Ll1']
],
u,
[
['J', 'F', 'M', 'A', 'M', 'J', 'J', 'A', 'S', 'O', 'N', 'D'],
['Jan', 'Feb', 'Mac', 'Apr', 'Mei', 'Jun', 'Jul', 'Ago', 'Sep', 'Okt', 'Nov', 'Des'],
[
'Mwedi Ntandi', 'Mwedi wa Pili', 'Mwedi wa Tatu', 'Mwedi wa Nchechi', 'Mwedi wa Nnyano',
'Mwedi wa Nnyano na Umo', 'Mwedi wa Nnyano na Mivili', 'Mwedi wa Nnyano na Mitatu',
'Mwedi wa Nnyano na Nchechi', 'Mwedi wa Nnyano na Nnyano', 'Mwedi wa Nnyano na Nnyano na U',
'Mwedi wa Nnyano na Nnyano na M'
]
],
u, [['AY', 'NY'], u, ['Akanapawa Yesu', 'Nankuida Yesu']], 1, [6, 0],
['dd/MM/y', 'd MMM y', 'd MMMM y', 'EEEE, d MMMM y'],
['HH:mm', 'HH:mm:ss', 'HH:mm:ss z', 'HH:mm:ss zzzz'], ['{1} {0}', u, u, u],
['.', ',', ';', '%', '+', '-', 'E', '×', '‰', '∞', 'NaN', ':'],
['#,##0.###', '#,##0%', '¤#,##0.00', '#E0'], 'TSh', 'Shilingi ya Tanzania',
{'JPY': ['JP¥', '¥'], 'TZS': ['TSh'], 'USD': ['US$', '$']}, plural
];
| packages/common/locales/kde.ts | 0 | https://github.com/angular/angular/commit/15eb1e0ce1ce7fbd7a833cef3f76c53297f7e24f | [
0.00017793710867408663,
0.00017371989088132977,
0.00017115927767008543,
0.00017311377450823784,
0.0000024449034299323102
] |
{
"id": 0,
"code_window": [
" // return null as there is no metadata where an input could be declared.\n",
" if (!decorator) {\n",
" return null;\n",
" }\n",
"\n",
" const decoratorCall = decorator.node.expression as ts.CallExpression;\n",
"\n",
" // In case the decorator does define any metadata, there is no metadata\n",
" // where inputs could be declared. This is an edge case because there\n",
" // always needs to be an object literal, but in case there isn't we just\n",
" // want to skip the invalid decorator and return null.\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" const decoratorCall = decorator.node.expression;\n"
],
"file_path": "packages/core/schematics/migrations/static-queries/angular/directive_inputs.ts",
"type": "replace",
"edit_start_line_idx": 64
} | <!doctype html>
<html>
<title>Zippy Angular</title>
<body>
<zippy-app>
Loading...
</zippy-app>
</body>
</html>
| modules/playground/src/zippy_component/index.html | 0 | https://github.com/angular/angular/commit/15eb1e0ce1ce7fbd7a833cef3f76c53297f7e24f | [
0.00017173783271573484,
0.00017173783271573484,
0.00017173783271573484,
0.00017173783271573484,
0
] |
{
"id": 0,
"code_window": [
" // return null as there is no metadata where an input could be declared.\n",
" if (!decorator) {\n",
" return null;\n",
" }\n",
"\n",
" const decoratorCall = decorator.node.expression as ts.CallExpression;\n",
"\n",
" // In case the decorator does define any metadata, there is no metadata\n",
" // where inputs could be declared. This is an edge case because there\n",
" // always needs to be an object literal, but in case there isn't we just\n",
" // want to skip the invalid decorator and return null.\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" const decoratorCall = decorator.node.expression;\n"
],
"file_path": "packages/core/schematics/migrations/static-queries/angular/directive_inputs.ts",
"type": "replace",
"edit_start_line_idx": 64
} | /**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
// THIS CODE IS GENERATED - DO NOT MODIFY
// See angular/tools/gulp-tasks/cldr/extract.js
const u = undefined;
function plural(n: number): number {
return 5;
}
export default [
'twq', [['Subbaahi', 'Zaarikay b'], u, u], u,
[
['H', 'T', 'T', 'L', 'L', 'L', 'S'], ['Alh', 'Ati', 'Ata', 'Ala', 'Alm', 'Alz', 'Asi'],
['Alhadi', 'Atinni', 'Atalaata', 'Alarba', 'Alhamiisa', 'Alzuma', 'Asibti'],
['Alh', 'Ati', 'Ata', 'Ala', 'Alm', 'Alz', 'Asi']
],
u,
[
['Ž', 'F', 'M', 'A', 'M', 'Ž', 'Ž', 'U', 'S', 'O', 'N', 'D'],
['Žan', 'Fee', 'Mar', 'Awi', 'Me', 'Žuw', 'Žuy', 'Ut', 'Sek', 'Okt', 'Noo', 'Dee'],
[
'Žanwiye', 'Feewiriye', 'Marsi', 'Awiril', 'Me', 'Žuweŋ', 'Žuyye', 'Ut', 'Sektanbur',
'Oktoobur', 'Noowanbur', 'Deesanbur'
]
],
u, [['IJ', 'IZ'], u, ['Isaa jine', 'Isaa zamanoo']], 1, [6, 0],
['d/M/y', 'd MMM y', 'd MMMM y', 'EEEE d MMMM y'],
['HH:mm', 'HH:mm:ss', 'HH:mm:ss z', 'HH:mm:ss zzzz'], ['{1} {0}', u, u, u],
['.', ' ', ';', '%', '+', '-', 'E', '×', '‰', '∞', 'NaN', ':'],
['#,##0.###', '#,##0%', '#,##0.00¤', '#E0'], 'CFA', 'CFA Fraŋ (BCEAO)',
{'JPY': ['JP¥', '¥'], 'USD': ['US$', '$']}, plural
];
| packages/common/locales/twq.ts | 0 | https://github.com/angular/angular/commit/15eb1e0ce1ce7fbd7a833cef3f76c53297f7e24f | [
0.00017489735910203308,
0.0001734185789246112,
0.00017188707715831697,
0.00017300619219895452,
0.0000011897162721652421
] |
{
"id": 1,
"code_window": [
" * determined timing. The updated decorator call expression node will be returned.\n",
" */\n",
"export function getTransformedQueryCallExpr(\n",
" query: NgQueryDefinition, timing: QueryTiming): ts.CallExpression|null {\n",
" const queryExpr = query.decorator.node.expression as ts.CallExpression;\n",
" const queryArguments = queryExpr.arguments;\n",
" const timingPropertyAssignment = ts.createPropertyAssignment(\n",
" 'static', timing === QueryTiming.STATIC ? ts.createTrue() : ts.createFalse());\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" const queryExpr = query.decorator.node.expression;\n"
],
"file_path": "packages/core/schematics/migrations/static-queries/transform.ts",
"type": "replace",
"edit_start_line_idx": 18
} | /**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
import * as ts from 'typescript';
import {getCallDecoratorImport} from './typescript/decorators';
export interface NgDecorator {
name: string;
node: ts.Decorator;
}
/**
* Gets all decorators which are imported from an Angular package (e.g. "@angular/core")
* from a list of decorators.
*/
export function getAngularDecorators(
typeChecker: ts.TypeChecker, decorators: ReadonlyArray<ts.Decorator>): NgDecorator[] {
return decorators.map(node => ({node, importData: getCallDecoratorImport(typeChecker, node)}))
.filter(({importData}) => importData && importData.importModule.startsWith('@angular/'))
.map(({node, importData}) => ({node, name: importData !.name}));
}
| packages/core/schematics/utils/ng_decorators.ts | 1 | https://github.com/angular/angular/commit/15eb1e0ce1ce7fbd7a833cef3f76c53297f7e24f | [
0.0024888478219509125,
0.000977878225967288,
0.00017046448192559183,
0.0002743225486483425,
0.0010692577343434095
] |
{
"id": 1,
"code_window": [
" * determined timing. The updated decorator call expression node will be returned.\n",
" */\n",
"export function getTransformedQueryCallExpr(\n",
" query: NgQueryDefinition, timing: QueryTiming): ts.CallExpression|null {\n",
" const queryExpr = query.decorator.node.expression as ts.CallExpression;\n",
" const queryArguments = queryExpr.arguments;\n",
" const timingPropertyAssignment = ts.createPropertyAssignment(\n",
" 'static', timing === QueryTiming.STATIC ? ts.createTrue() : ts.createFalse());\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" const queryExpr = query.decorator.node.expression;\n"
],
"file_path": "packages/core/schematics/migrations/static-queries/transform.ts",
"type": "replace",
"edit_start_line_idx": 18
} | # Authoring Schematics
You can create your own schematics to operate on Angular projects.
Library developers typically package schematics with their libraries in order to integrate them with the Angular CLI.
You can also create stand-alone schematics to manipulate the files and constructs in Angular applications as a way of customizing them for your development environment and making them conform to your standards and constraints.
Schematics can be chained, running other schematics to perform complex operations.
Manipulating the code in an application has the potential to be both very powerful and correspondingly dangerous.
For example, creating a file that already exists would be an error, and if it was applied immediately, it would discard all the other changes applied so far.
The Angular Schematics tooling guards against side effects and errors by creating a virtual file system.
A schematic describes a pipeline of transformations that can be applied to the virtual file system.
When a schematic runs, the transformations are recorded in memory, and only applied in the real file system once they're confirmed to be valid.
## Schematics concepts
The public API for schematics defines classes that represent the basic concepts.
* The virtual file system is represented by a `Tree`. The `Tree` data structure contains a *base* (a set of files that already exists) and a *staging area* (a list of changes to be applied to the base).
When making modifications, you don't actually change the base, but add those modifications to the staging area.
* A `Rule` object defines a function that takes a `Tree`, applies transformations, and returns a new `Tree`. The main file for a schematic, `index.ts`, defines a set of rules that implement the schematic's logic.
* A transformation is represented by an `Action`. There are four action types: `Create`, `Rename`, `Overwrite`, and `Delete`.
* Each schematic runs in a context, represented by a `SchematicContext` object.
The context object passed into a rule provides access to utility functions and metadata that the schematic may need to work with, including a logging API to help with debugging.
The context also defines a *merge strategy* that determines how changes are merged from the staged tree into the base tree. A change can be accepted or ignored, or throw an exception.
### Defining rules and actions
When you create a new blank schematic with the [Schematics CLI](#cli), the generated entry function is a *rule factory*.
A `RuleFactory`object defines a higher-order function that creates a `Rule`.
<code-example language="TypeScript" linenums="false">
import { Rule, SchematicContext, Tree } from '@angular-devkit/schematics';
// You don't have to export the function as default.
// You can also have more than one rule factory per file.
export function helloWorld(_options: any): Rule {
return (tree: Tree, _context: SchematicContext) => {
return tree;
};
}
</code-example>
Your rules can make changes to your projects by calling external tools and implementing logic.
You need a rule, for example, to define how a template in the schematic is to be merged into the hosting project.
Rules can make use of utilities provided with the `@schematics/angular` package. Look for helper functions for working with modules, dependencies, TypeScript, AST, JSON, Angular CLI workspaces and projects, and more.
<code-example language="none" linenums="false">
import {
JsonAstObject,
JsonObject,
JsonValue,
Path,
normalize,
parseJsonAst,
strings,
} from '@angular-devkit/core';
</code-example>
### Defining input options with a schema and interfaces
Rules can collect option values from the caller and inject them into templates.
The options available to your rules, with their allowed values and defaults, are defined in the schematic's JSON schema file, `<schematic>/schema.json`.
You can define variable or enumerated data types for the schema using TypeScript interfaces.
You can see examples of schema files for the Angular CLI command schematics in [`@schematics/angular`](https://github.com/angular/angular-cli/blob/7.0.x/packages/schematics/angular/application/schema.json).
{@a cli}
## Schematics CLI
Schematics come with their own command-line tool.
Using Node 6.9 or above, install the Schematics command line tool globally:
<code-example language="bash" linenums="false">
npm install -g @angular-devkit/schematics-cli
</code-example>
This installs the `schematics` executable, which you can use to create a new schematics collection in its own project folder, add a new schematic to an existing collection, or extend an existing schematic.
In the following sections, we will create a new schematics collection using the CLI in order to introduce the files and file structure, and some of the basic concepts.
The most common use of schematics, however, is to integrate an Angular library with the Angular CLI.
You can do this by creating the schematic files directly within the library project in an Angular workspace, without using the Schematics CLI.
See [Schematics for Libraries](guide/schematics-for-libraries).
### Creating a schematics collection
The following command creates a new schematic named `hello-world` in a new project folder of the same name.
<code-example language="bash" linenums="false">
schematics blank --name=hello-world
</code-example>
The `blank` schematic is provided by the Schematics CLI. The command creates a new project folder (the root folder for the collection) and an initial named schematic in the collection.
Go to the collection folder, install your npm dependencies, and open your new collection in your favorite editor to see the generated files. For example, if you are using VSCode:
<code-example language="bash" linenums="false">
cd hello-world
npm install
npm run build
code .
</code-example>
The initial schematic gets the same name as the project folder, and is generated in `src/hello-world`.
You can add related schematics to this collection, and modify the generated skeleton code to define your schematic's functionality.
Each schematic name must be unique within the collection.
### Running a schematic
Use the `schematics` command to run a named schematic.
Provide the path to the project folder, the schematic name, and any mandatory options, in the following format.
<code-example language="bash" linenums="false">
schematics <path-to-schematics-project>:<schematics-name> --<required-option>=<value>
</code-example>
The path can be absolute or relative to the current working directory where the command is executed.
For example, to run the schematic we just generated (which has no required options), use the following command.
<code-example language="bash" linenums="false">
schematics .:hello-world
</code-example>
### Adding a schematic to a collection
To add a schematic to an existing collection, use the same command you use to start a new schematics project, but run the command inside the project folder.
<code-example language="bash" linenums="false">
cd hello-world
schematics blank --name=goodbye-world
</code-example>
The command generates the new named schematic inside your collection, with a main `index.ts` file and its associated test spec.
It also adds the name, description, and factory function for the new schematic to the collection's schema in the `collection.json` file.
## Collection contents
The top level of the root project folder for a collection contains configuration files, a `node_modules` folder, and a `src/` folder.
The `src/` folder contains subfolders for named schematics in the collection, and a schema, `collection.json`, which describes the collected schematics.
Each schematic is created with a name, description, and factory function.
<code-example language="none" linenums="false">
{
"$schema":
"../node_modules/@angular-devkit/schematics/collection-schema.json",
"schematics": {
"hello-world": {
"description": "A blank schematic.",
"factory": "./hello-world/index#helloWorld"
}
}
}
</code-example>
* The `$schema` property specifies the schema that the CLI uses for validation.
* The `schematics` property lists named schematics that belong to this collection.
Each schematic has a plain-text description, and points to the generated entry function in the main file.
* The `factory` property points to the generated entry function. In this example, you invoke the `hello-world` schematic by calling the `helloWorld()` factory function.
* The optional `schema` property points to a JSON schema file that defines the command-line options available to the schematic.
* The optional `aliases` array specifies one or more strings that can be used to invoke the schematic.
For example, the schematic for the Angular CLI “generate” command has an alias “g”, allowing you to use the command `ng g`.
### Named schematics
When you use the Schematics CLI to create a blank schematics project, the new blank schematic is the first member of the collection, and has the same name as the collection.
When you add a new named schematic to this collection, it is automatically added to the `collection.json` schema.
In addition to the name and description, each schematic has a `factory` property that identifies the schematic’s entry point.
In the example, you invoke the schematic's defined functionality by calling the `helloWorld()` function in the main file, `hello-world/index.ts`.
<figure>
<img src="generated/images/guide/schematics/collection-files.gif" alt="overview">
</figure>
Each named schematic in the collection has the following main parts.
| | |
| :------------- | :-------------------------------------------|
| `index.ts` | Code that defines the transformation logic for a named schematic. |
| `schema.json` | Schematic variable definition. |
| `schema.d.ts` | Schematic variables. |
| `files/` | Optional component/template files to replicate. |
It is possible for a schematic to provide all of its logic in the `index.ts` file, without additional templates.
You can create dynamic schematics for Angular, however, by providing components and templates in the `files/` folder, like those in standalone Angular projects.
The logic in the index file configures these templates by defining rules that inject data and modify variables.
| aio/content/guide/schematics-authoring.md | 0 | https://github.com/angular/angular/commit/15eb1e0ce1ce7fbd7a833cef3f76c53297f7e24f | [
0.00017658375145401806,
0.0001703441666904837,
0.00016353985120076686,
0.0001708490017335862,
0.000003536835720296949
] |
{
"id": 1,
"code_window": [
" * determined timing. The updated decorator call expression node will be returned.\n",
" */\n",
"export function getTransformedQueryCallExpr(\n",
" query: NgQueryDefinition, timing: QueryTiming): ts.CallExpression|null {\n",
" const queryExpr = query.decorator.node.expression as ts.CallExpression;\n",
" const queryArguments = queryExpr.arguments;\n",
" const timingPropertyAssignment = ts.createPropertyAssignment(\n",
" 'static', timing === QueryTiming.STATIC ? ts.createTrue() : ts.createFalse());\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" const queryExpr = query.decorator.node.expression;\n"
],
"file_path": "packages/core/schematics/migrations/static-queries/transform.ts",
"type": "replace",
"edit_start_line_idx": 18
} | /**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
// THIS CODE IS GENERATED - DO NOT MODIFY
// See angular/tools/gulp-tasks/cldr/extract.js
const u = undefined;
function plural(n: number): number {
let i = Math.floor(Math.abs(n));
if (i === 0 || i === 1) return 1;
return 5;
}
export default [
'fr-VU', [['AM', 'PM'], u, u], u,
[
['D', 'L', 'M', 'M', 'J', 'V', 'S'], ['dim.', 'lun.', 'mar.', 'mer.', 'jeu.', 'ven.', 'sam.'],
['dimanche', 'lundi', 'mardi', 'mercredi', 'jeudi', 'vendredi', 'samedi'],
['di', 'lu', 'ma', 'me', 'je', 've', 'sa']
],
u,
[
['J', 'F', 'M', 'A', 'M', 'J', 'J', 'A', 'S', 'O', 'N', 'D'],
[
'janv.', 'févr.', 'mars', 'avr.', 'mai', 'juin', 'juil.', 'août', 'sept.', 'oct.', 'nov.',
'déc.'
],
[
'janvier', 'février', 'mars', 'avril', 'mai', 'juin', 'juillet', 'août', 'septembre',
'octobre', 'novembre', 'décembre'
]
],
u, [['av. J.-C.', 'ap. J.-C.'], u, ['avant Jésus-Christ', 'après Jésus-Christ']], 1, [6, 0],
['dd/MM/y', 'd MMM y', 'd MMMM y', 'EEEE d MMMM y'],
['h:mm a', 'h:mm:ss a', 'h:mm:ss a z', 'h:mm:ss a zzzz'], ['{1} {0}', '{1} \'à\' {0}', u, u],
[',', ' ', ';', '%', '+', '-', 'E', '×', '‰', '∞', 'NaN', ':'],
['#,##0.###', '#,##0 %', '#,##0.00 ¤', '#E0'], 'VT', 'vatu vanuatuan', {
'ARS': ['$AR', '$'],
'AUD': ['$AU', '$'],
'BEF': ['FB'],
'BMD': ['$BM', '$'],
'BND': ['$BN', '$'],
'BSD': ['$BS', '$'],
'BZD': ['$BZ', '$'],
'CAD': ['$CA', '$'],
'CLP': ['$CL', '$'],
'CNY': [u, '¥'],
'COP': ['$CO', '$'],
'CYP': ['£CY'],
'EGP': [u, '£E'],
'FJD': ['$FJ', '$'],
'FKP': ['£FK', '£'],
'FRF': ['F'],
'GBP': ['£GB', '£'],
'GIP': ['£GI', '£'],
'HKD': [u, '$'],
'IEP': ['£IE'],
'ILP': ['£IL'],
'ITL': ['₤IT'],
'JPY': [u, '¥'],
'KMF': [u, 'FC'],
'LBP': ['£LB', '£L'],
'MTP': ['£MT'],
'MXN': ['$MX', '$'],
'NAD': ['$NA', '$'],
'NIO': [u, '$C'],
'NZD': ['$NZ', '$'],
'RHD': ['$RH'],
'RON': [u, 'L'],
'RWF': [u, 'FR'],
'SBD': ['$SB', '$'],
'SGD': ['$SG', '$'],
'SRD': ['$SR', '$'],
'TTD': ['$TT', '$'],
'TWD': [u, 'NT$'],
'USD': ['$US', '$'],
'UYU': ['$UY', '$'],
'VUV': ['VT'],
'WST': ['WS$'],
'XCD': [u, '$'],
'XPF': ['FCFP'],
'ZMW': [u, 'Kw']
},
plural
];
| packages/common/locales/fr-VU.ts | 0 | https://github.com/angular/angular/commit/15eb1e0ce1ce7fbd7a833cef3f76c53297f7e24f | [
0.00017578295955900103,
0.00017446145648136735,
0.00017199675494339317,
0.00017506489530205727,
0.0000013356368526729057
] |
{
"id": 1,
"code_window": [
" * determined timing. The updated decorator call expression node will be returned.\n",
" */\n",
"export function getTransformedQueryCallExpr(\n",
" query: NgQueryDefinition, timing: QueryTiming): ts.CallExpression|null {\n",
" const queryExpr = query.decorator.node.expression as ts.CallExpression;\n",
" const queryArguments = queryExpr.arguments;\n",
" const timingPropertyAssignment = ts.createPropertyAssignment(\n",
" 'static', timing === QueryTiming.STATIC ? ts.createTrue() : ts.createFalse());\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" const queryExpr = query.decorator.node.expression;\n"
],
"file_path": "packages/core/schematics/migrations/static-queries/transform.ts",
"type": "replace",
"edit_start_line_idx": 18
} | import { Component } from '@angular/core';
@Component({
selector: 'sg-app',
templateUrl: './app.component.html'
})
export class AppComponent { }
| aio/content/examples/styleguide/src/06-01/app/app.component.ts | 0 | https://github.com/angular/angular/commit/15eb1e0ce1ce7fbd7a833cef3f76c53297f7e24f | [
0.00017254358681384474,
0.00017254358681384474,
0.00017254358681384474,
0.00017254358681384474,
0
] |
{
"id": 2,
"code_window": [
" */\n",
"\n",
"import * as ts from 'typescript';\n",
"import {getCallDecoratorImport} from './typescript/decorators';\n",
"\n",
"export interface NgDecorator {\n",
" name: string;\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"add",
"keep",
"keep"
],
"after_edit": [
"export type CallExpressionDecorator = ts.Decorator & {\n",
" expression: ts.CallExpression;\n",
"}\n",
"\n"
],
"file_path": "packages/core/schematics/utils/ng_decorators.ts",
"type": "add",
"edit_start_line_idx": 11
} | /**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
import * as ts from 'typescript';
import {getCallDecoratorImport} from './typescript/decorators';
export interface NgDecorator {
name: string;
node: ts.Decorator;
}
/**
* Gets all decorators which are imported from an Angular package (e.g. "@angular/core")
* from a list of decorators.
*/
export function getAngularDecorators(
typeChecker: ts.TypeChecker, decorators: ReadonlyArray<ts.Decorator>): NgDecorator[] {
return decorators.map(node => ({node, importData: getCallDecoratorImport(typeChecker, node)}))
.filter(({importData}) => importData && importData.importModule.startsWith('@angular/'))
.map(({node, importData}) => ({node, name: importData !.name}));
}
| packages/core/schematics/utils/ng_decorators.ts | 1 | https://github.com/angular/angular/commit/15eb1e0ce1ce7fbd7a833cef3f76c53297f7e24f | [
0.9975019097328186,
0.5522472262382507,
0.001083902083337307,
0.6581557393074036,
0.4136219322681427
] |
{
"id": 2,
"code_window": [
" */\n",
"\n",
"import * as ts from 'typescript';\n",
"import {getCallDecoratorImport} from './typescript/decorators';\n",
"\n",
"export interface NgDecorator {\n",
" name: string;\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"add",
"keep",
"keep"
],
"after_edit": [
"export type CallExpressionDecorator = ts.Decorator & {\n",
" expression: ts.CallExpression;\n",
"}\n",
"\n"
],
"file_path": "packages/core/schematics/utils/ng_decorators.ts",
"type": "add",
"edit_start_line_idx": 11
} | <?xml version="1.0" encoding="UTF-8"?>
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
{%- for url in doc.urls %}
<url>
<loc>https://angular.io/{$ url $}</loc>
</url>{% endfor %}
</urlset> | aio/tools/transforms/templates/sitemap.template.xml | 0 | https://github.com/angular/angular/commit/15eb1e0ce1ce7fbd7a833cef3f76c53297f7e24f | [
0.00016722311556804925,
0.00016722311556804925,
0.00016722311556804925,
0.00016722311556804925,
0
] |
{
"id": 2,
"code_window": [
" */\n",
"\n",
"import * as ts from 'typescript';\n",
"import {getCallDecoratorImport} from './typescript/decorators';\n",
"\n",
"export interface NgDecorator {\n",
" name: string;\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"add",
"keep",
"keep"
],
"after_edit": [
"export type CallExpressionDecorator = ts.Decorator & {\n",
" expression: ts.CallExpression;\n",
"}\n",
"\n"
],
"file_path": "packages/core/schematics/utils/ng_decorators.ts",
"type": "add",
"edit_start_line_idx": 11
} | export declare function downgradeComponent(info: {
component: Type<any>;
downgradedModule?: string;
propagateDigest?: boolean;
/** @deprecated */ inputs?: string[];
/** @deprecated */ outputs?: string[];
/** @deprecated */ selectors?: string[];
}): any;
export declare function downgradeInjectable(token: any, downgradedModule?: string): Function;
export declare function downgradeModule<T>(moduleFactoryOrBootstrapFn: NgModuleFactory<T> | ((extraProviders: StaticProvider[]) => Promise<NgModuleRef<T>>)): string;
export declare function getAngularJSGlobal(): any;
/** @deprecated */
export declare function getAngularLib(): any;
export declare function setAngularJSGlobal(ng: any): void;
/** @deprecated */
export declare function setAngularLib(ng: any): void;
export declare class UpgradeComponent implements OnInit, OnChanges, DoCheck, OnDestroy {
constructor(name: string, elementRef: ElementRef, injector: Injector);
ngDoCheck(): void;
ngOnChanges(changes: SimpleChanges): void;
ngOnDestroy(): void;
ngOnInit(): void;
}
export declare class UpgradeModule {
$injector: any;
injector: Injector;
ngZone: NgZone;
constructor(
injector: Injector,
ngZone: NgZone);
bootstrap(element: Element, modules?: string[], config?: any): void;
}
export declare const VERSION: Version;
| tools/public_api_guard/upgrade/static.d.ts | 0 | https://github.com/angular/angular/commit/15eb1e0ce1ce7fbd7a833cef3f76c53297f7e24f | [
0.0006839444977231324,
0.0002786266850307584,
0.00016662116104271263,
0.00017818377818912268,
0.00020295176364015788
] |
{
"id": 2,
"code_window": [
" */\n",
"\n",
"import * as ts from 'typescript';\n",
"import {getCallDecoratorImport} from './typescript/decorators';\n",
"\n",
"export interface NgDecorator {\n",
" name: string;\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"add",
"keep",
"keep"
],
"after_edit": [
"export type CallExpressionDecorator = ts.Decorator & {\n",
" expression: ts.CallExpression;\n",
"}\n",
"\n"
],
"file_path": "packages/core/schematics/utils/ng_decorators.ts",
"type": "add",
"edit_start_line_idx": 11
} | [] | tools/symbol-extractor/symbol_extractor_spec/empty_iife.json | 0 | https://github.com/angular/angular/commit/15eb1e0ce1ce7fbd7a833cef3f76c53297f7e24f | [
0.0001795690623112023,
0.0001795690623112023,
0.0001795690623112023,
0.0001795690623112023,
0
] |
{
"id": 3,
"code_window": [
"export interface NgDecorator {\n",
" name: string;\n",
" node: ts.Decorator;\n",
"}\n",
"\n",
"/**\n",
" * Gets all decorators which are imported from an Angular package (e.g. \"@angular/core\")\n",
" * from a list of decorators.\n"
],
"labels": [
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" node: CallExpressionDecorator;\n"
],
"file_path": "packages/core/schematics/utils/ng_decorators.ts",
"type": "replace",
"edit_start_line_idx": 13
} | /**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
import * as ts from 'typescript';
import {getCallDecoratorImport} from './typescript/decorators';
export interface NgDecorator {
name: string;
node: ts.Decorator;
}
/**
* Gets all decorators which are imported from an Angular package (e.g. "@angular/core")
* from a list of decorators.
*/
export function getAngularDecorators(
typeChecker: ts.TypeChecker, decorators: ReadonlyArray<ts.Decorator>): NgDecorator[] {
return decorators.map(node => ({node, importData: getCallDecoratorImport(typeChecker, node)}))
.filter(({importData}) => importData && importData.importModule.startsWith('@angular/'))
.map(({node, importData}) => ({node, name: importData !.name}));
}
| packages/core/schematics/utils/ng_decorators.ts | 1 | https://github.com/angular/angular/commit/15eb1e0ce1ce7fbd7a833cef3f76c53297f7e24f | [
0.7783697247505188,
0.2621484100818634,
0.00016616072389297187,
0.007909325882792473,
0.36503729224205017
] |
{
"id": 3,
"code_window": [
"export interface NgDecorator {\n",
" name: string;\n",
" node: ts.Decorator;\n",
"}\n",
"\n",
"/**\n",
" * Gets all decorators which are imported from an Angular package (e.g. \"@angular/core\")\n",
" * from a list of decorators.\n"
],
"labels": [
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" node: CallExpressionDecorator;\n"
],
"file_path": "packages/core/schematics/utils/ng_decorators.ts",
"type": "replace",
"edit_start_line_idx": 13
} | const { mergeProperties, mapObject, parseAttributes, renderAttributes } = require('./utils');
describe('utils', () => {
describe('mapObject', () => {
it('creates a new object', () => {
const testObj = { a: 1 };
const mappedObj = mapObject(testObj, (key, value) => value);
expect(mappedObj).toEqual(testObj);
expect(mappedObj).not.toBe(testObj);
});
it('maps the values via the mapper function', () => {
const testObj = { a: 1, b: 2 };
const mappedObj = mapObject(testObj, (key, value) => value * 2);
expect(mappedObj).toEqual({ a: 2, b: 4 });
});
});
describe('parseAttributes', () => {
it('should parse empty string', () => {
const attrs = parseAttributes('');
expect(attrs).toEqual({ });
});
it('should parse blank string', () => {
const attrs = parseAttributes(' ');
expect(attrs).toEqual({ });
});
it('should parse double quoted attributes', () => {
const attrs = parseAttributes('a="one" b="two"');
expect(attrs).toEqual({ a: 'one', b: 'two' });
});
it('should parse empty quoted attributes', () => {
const attrs = parseAttributes('a="" b="two"');
expect(attrs).toEqual({ a: '', b: 'two' });
});
it('should parse single quoted attributes', () => {
const attrs = parseAttributes('a=\'one\' b=\'two\'');
expect(attrs).toEqual({ a: 'one', b: 'two' });
});
it('should ignore whitespace', () => {
const attrs = parseAttributes(' a = "one" b = "two" ');
expect(attrs).toEqual({ a: 'one', b: 'two' });
});
it('should parse attributes with quotes within quotes', () => {
const attrs = parseAttributes('a=\'o"n"e\' b="t\'w\'o"');
expect(attrs).toEqual({ a: 'o"n"e', b: 't\'w\'o' });
});
it('should parse attributes with spaces in their values', () => {
const attrs = parseAttributes('a="one and two" b="three and four"');
expect(attrs).toEqual({ a: 'one and two', b: 'three and four' });
});
it('should parse empty attributes', () => {
const attrs = parseAttributes('a b="two"');
expect(attrs).toEqual({ a: true, b: 'two' });
});
it('should parse unquoted attributes', () => {
const attrs = parseAttributes('a=one b=two');
expect(attrs).toEqual({ a: 'one', b: 'two' });
});
it('should complain if a quoted attribute is not closed', () => {
expect(() => parseAttributes('a="" b="two')).toThrowError(
'Unterminated quoted attribute value in `a="" b="two`. Starting at 8. Expected a " but got "end of string".'
);
});
});
describe('renderAttributes', () => {
it('should convert key-value map to a strong that can be used in HTML', () => {
expect(renderAttributes({ foo: 'bar', moo: 'car' })).toEqual(' foo="bar" moo="car"');
});
it('should handle boolean values', () => {
expect(renderAttributes({ foo: 'bar', loo: true, moo: false }))
.toEqual(' foo="bar" loo');
});
it('should escape double quotes inside the value', () => {
expect(renderAttributes({ foo: 'bar "car"' })).toEqual(' foo="bar "car""');
});
it('should not escape single quotes inside the value', () => {
expect(renderAttributes({ foo: 'bar \'car\'' })).toEqual(' foo="bar \'car\'"');
});
it('should handle an empty object', () => {
expect(renderAttributes({ })).toEqual('');
});
});
describe('mergeProperties', () => {
it('should write specified properties from the source to the target', () => {
const source = { a: 1, b: 2, c: 3 };
const target = { };
mergeProperties(target, source, ['a', 'b']);
expect(target).toEqual({ a: 1, b: 2 });
});
it('should not overwrite target properties that are not specified', () => {
const source = { a: 1, b: 2, c: 3 };
const target = { b: 10 };
mergeProperties(target, source, ['a']);
expect(target).toEqual({ a: 1, b: 10 });
});
it('should not overwrite target properties that are specified but do not exist in the source', () => {
const source = { a: 1 };
const target = { b: 10 };
mergeProperties(target, source, ['a', 'b']);
expect(target).toEqual({ a: 1, b: 10 });
});
it('should overwrite target properties even if they are `undefined` in the source', () => {
const source = { a: undefined };
const target = { a: 10 };
mergeProperties(target, source, ['a']);
expect(target).toEqual({ a: undefined });
});
});
});
| aio/tools/transforms/helpers/utils.spec.js | 0 | https://github.com/angular/angular/commit/15eb1e0ce1ce7fbd7a833cef3f76c53297f7e24f | [
0.000171637162566185,
0.00016921255155466497,
0.0001674083323450759,
0.00016891137056518346,
0.000001322474986409361
] |
{
"id": 3,
"code_window": [
"export interface NgDecorator {\n",
" name: string;\n",
" node: ts.Decorator;\n",
"}\n",
"\n",
"/**\n",
" * Gets all decorators which are imported from an Angular package (e.g. \"@angular/core\")\n",
" * from a list of decorators.\n"
],
"labels": [
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" node: CallExpressionDecorator;\n"
],
"file_path": "packages/core/schematics/utils/ng_decorators.ts",
"type": "replace",
"edit_start_line_idx": 13
} | import { Injectable } from '@angular/core';
@Injectable({ providedIn: 'root' })
export class MessageService {
messages: string[] = [];
add(message: string) {
this.messages.push(message);
}
clear() {
this.messages = [];
}
}
| aio/content/examples/toh-pt5/src/app/message.service.ts | 0 | https://github.com/angular/angular/commit/15eb1e0ce1ce7fbd7a833cef3f76c53297f7e24f | [
0.00017191919323522598,
0.00017060741083696485,
0.0001692956138867885,
0.00017060741083696485,
0.000001311789674218744
] |
{
"id": 3,
"code_window": [
"export interface NgDecorator {\n",
" name: string;\n",
" node: ts.Decorator;\n",
"}\n",
"\n",
"/**\n",
" * Gets all decorators which are imported from an Angular package (e.g. \"@angular/core\")\n",
" * from a list of decorators.\n"
],
"labels": [
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" node: CallExpressionDecorator;\n"
],
"file_path": "packages/core/schematics/utils/ng_decorators.ts",
"type": "replace",
"edit_start_line_idx": 13
} | export declare class ActivatedRoute {
readonly children: ActivatedRoute[];
component: Type<any> | string | null;
data: Observable<Data>;
readonly firstChild: ActivatedRoute | null;
fragment: Observable<string>;
outlet: string;
readonly paramMap: Observable<ParamMap>;
params: Observable<Params>;
readonly parent: ActivatedRoute | null;
readonly pathFromRoot: ActivatedRoute[];
readonly queryParamMap: Observable<ParamMap>;
queryParams: Observable<Params>;
readonly root: ActivatedRoute;
readonly routeConfig: Route | null;
snapshot: ActivatedRouteSnapshot;
url: Observable<UrlSegment[]>;
toString(): string;
}
export declare class ActivatedRouteSnapshot {
readonly children: ActivatedRouteSnapshot[];
component: Type<any> | string | null;
data: Data;
readonly firstChild: ActivatedRouteSnapshot | null;
fragment: string;
outlet: string;
readonly paramMap: ParamMap;
params: Params;
readonly parent: ActivatedRouteSnapshot | null;
readonly pathFromRoot: ActivatedRouteSnapshot[];
readonly queryParamMap: ParamMap;
queryParams: Params;
readonly root: ActivatedRouteSnapshot;
readonly routeConfig: Route | null;
url: UrlSegment[];
toString(): string;
}
export declare class ActivationEnd {
snapshot: ActivatedRouteSnapshot;
constructor(
snapshot: ActivatedRouteSnapshot);
toString(): string;
}
export declare class ActivationStart {
snapshot: ActivatedRouteSnapshot;
constructor(
snapshot: ActivatedRouteSnapshot);
toString(): string;
}
export interface CanActivate {
canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<boolean | UrlTree> | Promise<boolean | UrlTree> | boolean | UrlTree;
}
export interface CanActivateChild {
canActivateChild(childRoute: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<boolean | UrlTree> | Promise<boolean | UrlTree> | boolean | UrlTree;
}
export interface CanDeactivate<T> {
canDeactivate(component: T, currentRoute: ActivatedRouteSnapshot, currentState: RouterStateSnapshot, nextState?: RouterStateSnapshot): Observable<boolean | UrlTree> | Promise<boolean | UrlTree> | boolean | UrlTree;
}
export interface CanLoad {
canLoad(route: Route, segments: UrlSegment[]): Observable<boolean> | Promise<boolean> | boolean;
}
export declare class ChildActivationEnd {
snapshot: ActivatedRouteSnapshot;
constructor(
snapshot: ActivatedRouteSnapshot);
toString(): string;
}
export declare class ChildActivationStart {
snapshot: ActivatedRouteSnapshot;
constructor(
snapshot: ActivatedRouteSnapshot);
toString(): string;
}
export declare class ChildrenOutletContexts {
getContext(childName: string): OutletContext | null;
getOrCreateContext(childName: string): OutletContext;
onChildOutletCreated(childName: string, outlet: RouterOutlet): void;
onChildOutletDestroyed(childName: string): void;
onOutletDeactivated(): Map<string, OutletContext>;
onOutletReAttached(contexts: Map<string, OutletContext>): void;
}
export declare function convertToParamMap(params: Params): ParamMap;
export declare type Data = {
[name: string]: any;
};
export declare class DefaultUrlSerializer implements UrlSerializer {
parse(url: string): UrlTree;
serialize(tree: UrlTree): string;
}
export declare type DetachedRouteHandle = {};
export declare type Event = RouterEvent | RouteConfigLoadStart | RouteConfigLoadEnd | ChildActivationStart | ChildActivationEnd | ActivationStart | ActivationEnd | Scroll;
export interface ExtraOptions {
anchorScrolling?: 'disabled' | 'enabled';
enableTracing?: boolean;
errorHandler?: ErrorHandler;
initialNavigation?: InitialNavigation;
malformedUriErrorHandler?: (error: URIError, urlSerializer: UrlSerializer, url: string) => UrlTree;
onSameUrlNavigation?: 'reload' | 'ignore';
paramsInheritanceStrategy?: 'emptyOnly' | 'always';
preloadingStrategy?: any;
relativeLinkResolution?: 'legacy' | 'corrected';
scrollOffset?: [number, number] | (() => [number, number]);
scrollPositionRestoration?: 'disabled' | 'enabled' | 'top';
urlUpdateStrategy?: 'deferred' | 'eager';
useHash?: boolean;
}
export declare class GuardsCheckEnd extends RouterEvent {
shouldActivate: boolean;
state: RouterStateSnapshot;
urlAfterRedirects: string;
constructor(
id: number,
url: string,
urlAfterRedirects: string,
state: RouterStateSnapshot,
shouldActivate: boolean);
toString(): string;
}
export declare class GuardsCheckStart extends RouterEvent {
state: RouterStateSnapshot;
urlAfterRedirects: string;
constructor(
id: number,
url: string,
urlAfterRedirects: string,
state: RouterStateSnapshot);
toString(): string;
}
export declare type LoadChildren = string | LoadChildrenCallback;
export declare type LoadChildrenCallback = () => Type<any> | NgModuleFactory<any> | Promise<NgModuleFactory<any>> | Promise<Type<any>> | Observable<Type<any>>;
export declare type Navigation = {
id: number;
initialUrl: string | UrlTree;
extractedUrl: UrlTree;
finalUrl?: UrlTree;
trigger: 'imperative' | 'popstate' | 'hashchange';
extras: NavigationExtras;
previousNavigation: Navigation | null;
};
export declare class NavigationCancel extends RouterEvent {
reason: string;
constructor(
id: number,
url: string,
reason: string);
toString(): string;
}
export declare class NavigationEnd extends RouterEvent {
urlAfterRedirects: string;
constructor(
id: number,
url: string,
urlAfterRedirects: string);
toString(): string;
}
export declare class NavigationError extends RouterEvent {
error: any;
constructor(
id: number,
url: string,
error: any);
toString(): string;
}
export interface NavigationExtras {
fragment?: string;
preserveFragment?: boolean;
/** @deprecated */ preserveQueryParams?: boolean;
queryParams?: Params | null;
queryParamsHandling?: QueryParamsHandling | null;
relativeTo?: ActivatedRoute | null;
replaceUrl?: boolean;
skipLocationChange?: boolean;
state?: {
[k: string]: any;
};
}
export declare class NavigationStart extends RouterEvent {
navigationTrigger?: 'imperative' | 'popstate' | 'hashchange';
restoredState?: {
[k: string]: any;
navigationId: number;
} | null;
constructor(
id: number,
url: string,
navigationTrigger?: 'imperative' | 'popstate' | 'hashchange',
restoredState?: {
[k: string]: any;
navigationId: number;
} | null);
toString(): string;
}
export declare class NoPreloading implements PreloadingStrategy {
preload(route: Route, fn: () => Observable<any>): Observable<any>;
}
export declare class OutletContext {
attachRef: ComponentRef<any> | null;
children: ChildrenOutletContexts;
outlet: RouterOutlet | null;
resolver: ComponentFactoryResolver | null;
route: ActivatedRoute | null;
}
export interface ParamMap {
readonly keys: string[];
get(name: string): string | null;
getAll(name: string): string[];
has(name: string): boolean;
}
export declare type Params = {
[key: string]: any;
};
export declare class PreloadAllModules implements PreloadingStrategy {
preload(route: Route, fn: () => Observable<any>): Observable<any>;
}
export declare abstract class PreloadingStrategy {
abstract preload(route: Route, fn: () => Observable<any>): Observable<any>;
}
export declare const PRIMARY_OUTLET = "primary";
export declare function provideRoutes(routes: Routes): any;
export interface Resolve<T> {
resolve(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<T> | Promise<T> | T;
}
export declare type ResolveData = {
[name: string]: any;
};
export declare class ResolveEnd extends RouterEvent {
state: RouterStateSnapshot;
urlAfterRedirects: string;
constructor(
id: number,
url: string,
urlAfterRedirects: string,
state: RouterStateSnapshot);
toString(): string;
}
export declare class ResolveStart extends RouterEvent {
state: RouterStateSnapshot;
urlAfterRedirects: string;
constructor(
id: number,
url: string,
urlAfterRedirects: string,
state: RouterStateSnapshot);
toString(): string;
}
export interface Route {
canActivate?: any[];
canActivateChild?: any[];
canDeactivate?: any[];
canLoad?: any[];
children?: Routes;
component?: Type<any>;
data?: Data;
loadChildren?: LoadChildren;
matcher?: UrlMatcher;
outlet?: string;
path?: string;
pathMatch?: string;
redirectTo?: string;
resolve?: ResolveData;
runGuardsAndResolvers?: RunGuardsAndResolvers;
}
export declare class RouteConfigLoadEnd {
route: Route;
constructor(
route: Route);
toString(): string;
}
export declare class RouteConfigLoadStart {
route: Route;
constructor(
route: Route);
toString(): string;
}
export declare class Router {
config: Routes;
errorHandler: ErrorHandler;
readonly events: Observable<Event>;
malformedUriErrorHandler: (error: URIError, urlSerializer: UrlSerializer, url: string) => UrlTree;
navigated: boolean;
onSameUrlNavigation: 'reload' | 'ignore';
paramsInheritanceStrategy: 'emptyOnly' | 'always';
relativeLinkResolution: 'legacy' | 'corrected';
routeReuseStrategy: RouteReuseStrategy;
readonly routerState: RouterState;
readonly url: string;
urlHandlingStrategy: UrlHandlingStrategy;
urlUpdateStrategy: 'deferred' | 'eager';
constructor(rootComponentType: Type<any> | null, urlSerializer: UrlSerializer, rootContexts: ChildrenOutletContexts, location: Location, injector: Injector, loader: NgModuleFactoryLoader, compiler: Compiler, config: Routes);
createUrlTree(commands: any[], navigationExtras?: NavigationExtras): UrlTree;
dispose(): void;
getCurrentNavigation(): Navigation | null;
initialNavigation(): void;
isActive(url: string | UrlTree, exact: boolean): boolean;
navigate(commands: any[], extras?: NavigationExtras): Promise<boolean>;
navigateByUrl(url: string | UrlTree, extras?: NavigationExtras): Promise<boolean>;
ngOnDestroy(): void;
parseUrl(url: string): UrlTree;
resetConfig(config: Routes): void;
serializeUrl(url: UrlTree): string;
setUpLocationChangeListener(): void;
}
export declare const ROUTER_CONFIGURATION: InjectionToken<ExtraOptions>;
export declare const ROUTER_INITIALIZER: InjectionToken<(compRef: ComponentRef<any>) => void>;
export declare abstract class RouteReuseStrategy {
abstract retrieve(route: ActivatedRouteSnapshot): DetachedRouteHandle | null;
abstract shouldAttach(route: ActivatedRouteSnapshot): boolean;
abstract shouldDetach(route: ActivatedRouteSnapshot): boolean;
abstract shouldReuseRoute(future: ActivatedRouteSnapshot, curr: ActivatedRouteSnapshot): boolean;
abstract store(route: ActivatedRouteSnapshot, handle: DetachedRouteHandle | null): void;
}
export declare class RouterEvent {
id: number;
url: string;
constructor(
id: number,
url: string);
}
export declare class RouterLink {
fragment: string;
preserveFragment: boolean;
/** @deprecated */ preserveQueryParams: boolean;
queryParams: {
[k: string]: any;
};
queryParamsHandling: QueryParamsHandling;
replaceUrl: boolean;
routerLink: any[] | string;
skipLocationChange: boolean;
state?: {
[k: string]: any;
};
readonly urlTree: UrlTree;
constructor(router: Router, route: ActivatedRoute, tabIndex: string, renderer: Renderer2, el: ElementRef);
onClick(): boolean;
}
export declare class RouterLinkActive implements OnChanges, OnDestroy, AfterContentInit {
readonly isActive: boolean;
links: QueryList<RouterLink>;
linksWithHrefs: QueryList<RouterLinkWithHref>;
routerLinkActive: string[] | string;
routerLinkActiveOptions: {
exact: boolean;
};
constructor(router: Router, element: ElementRef, renderer: Renderer2, link?: RouterLink | undefined, linkWithHref?: RouterLinkWithHref | undefined);
ngAfterContentInit(): void;
ngOnChanges(changes: SimpleChanges): void;
ngOnDestroy(): void;
}
export declare class RouterLinkWithHref implements OnChanges, OnDestroy {
fragment: string;
href: string;
preserveFragment: boolean;
preserveQueryParams: boolean;
queryParams: {
[k: string]: any;
};
queryParamsHandling: QueryParamsHandling;
replaceUrl: boolean;
routerLink: any[] | string;
skipLocationChange: boolean;
state?: {
[k: string]: any;
};
target: string;
readonly urlTree: UrlTree;
constructor(router: Router, route: ActivatedRoute, locationStrategy: LocationStrategy);
ngOnChanges(changes: {}): any;
ngOnDestroy(): any;
onClick(button: number, ctrlKey: boolean, metaKey: boolean, shiftKey: boolean): boolean;
}
export declare class RouterModule {
constructor(guard: any, router: Router);
static forChild(routes: Routes): ModuleWithProviders<RouterModule>;
static forRoot(routes: Routes, config?: ExtraOptions): ModuleWithProviders<RouterModule>;
}
export declare class RouterOutlet implements OnDestroy, OnInit {
activateEvents: EventEmitter<any>;
readonly activatedRoute: ActivatedRoute;
readonly activatedRouteData: Data;
readonly component: Object;
deactivateEvents: EventEmitter<any>;
readonly isActivated: boolean;
constructor(parentContexts: ChildrenOutletContexts, location: ViewContainerRef, resolver: ComponentFactoryResolver, name: string, changeDetector: ChangeDetectorRef);
activateWith(activatedRoute: ActivatedRoute, resolver: ComponentFactoryResolver | null): void;
attach(ref: ComponentRef<any>, activatedRoute: ActivatedRoute): void;
deactivate(): void;
detach(): ComponentRef<any>;
ngOnDestroy(): void;
ngOnInit(): void;
}
export declare class RouterPreloader implements OnDestroy {
constructor(router: Router, moduleLoader: NgModuleFactoryLoader, compiler: Compiler, injector: Injector, preloadingStrategy: PreloadingStrategy);
ngOnDestroy(): void;
preload(): Observable<any>;
setUpPreloading(): void;
}
export declare class RouterState extends Tree<ActivatedRoute> {
snapshot: RouterStateSnapshot;
toString(): string;
}
export declare class RouterStateSnapshot extends Tree<ActivatedRouteSnapshot> {
url: string;
toString(): string;
}
export declare type Routes = Route[];
export declare const ROUTES: InjectionToken<Route[][]>;
export declare class RoutesRecognized extends RouterEvent {
state: RouterStateSnapshot;
urlAfterRedirects: string;
constructor(
id: number,
url: string,
urlAfterRedirects: string,
state: RouterStateSnapshot);
toString(): string;
}
export declare type RunGuardsAndResolvers = 'pathParamsChange' | 'pathParamsOrQueryParamsChange' | 'paramsChange' | 'paramsOrQueryParamsChange' | 'always' | ((from: ActivatedRouteSnapshot, to: ActivatedRouteSnapshot) => boolean);
export declare class Scroll {
readonly anchor: string | null;
readonly position: [number, number] | null;
readonly routerEvent: NavigationEnd;
constructor(
routerEvent: NavigationEnd,
position: [number, number] | null,
anchor: string | null);
toString(): string;
}
export declare abstract class UrlHandlingStrategy {
abstract extract(url: UrlTree): UrlTree;
abstract merge(newUrlPart: UrlTree, rawUrl: UrlTree): UrlTree;
abstract shouldProcessUrl(url: UrlTree): boolean;
}
export declare type UrlMatcher = (segments: UrlSegment[], group: UrlSegmentGroup, route: Route) => UrlMatchResult;
export declare type UrlMatchResult = {
consumed: UrlSegment[];
posParams?: {
[name: string]: UrlSegment;
};
};
export declare class UrlSegment {
readonly parameterMap: ParamMap;
parameters: {
[name: string]: string;
};
path: string;
constructor(
path: string,
parameters: {
[name: string]: string;
});
toString(): string;
}
export declare class UrlSegmentGroup {
children: {
[key: string]: UrlSegmentGroup;
};
readonly numberOfChildren: number;
parent: UrlSegmentGroup | null;
segments: UrlSegment[];
constructor(
segments: UrlSegment[],
children: {
[key: string]: UrlSegmentGroup;
});
hasChildren(): boolean;
toString(): string;
}
export declare abstract class UrlSerializer {
abstract parse(url: string): UrlTree;
abstract serialize(tree: UrlTree): string;
}
export declare class UrlTree {
fragment: string | null;
readonly queryParamMap: ParamMap;
queryParams: Params;
root: UrlSegmentGroup;
toString(): string;
}
export declare const VERSION: Version;
| tools/public_api_guard/router/router.d.ts | 0 | https://github.com/angular/angular/commit/15eb1e0ce1ce7fbd7a833cef3f76c53297f7e24f | [
0.0009130308171734214,
0.00018685287795960903,
0.00016548321582376957,
0.00016985507681965828,
0.00010062443470815197
] |
{
"id": 4,
"code_window": [
" */\n",
"export function getAngularDecorators(\n",
" typeChecker: ts.TypeChecker, decorators: ReadonlyArray<ts.Decorator>): NgDecorator[] {\n",
" return decorators.map(node => ({node, importData: getCallDecoratorImport(typeChecker, node)}))\n",
" .filter(({importData}) => importData && importData.importModule.startsWith('@angular/'))\n",
" .map(({node, importData}) => ({node, name: importData !.name}));\n",
"}"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep"
],
"after_edit": [
" .map(\n",
" ({node, importData}) =>\n",
" ({node: node as CallExpressionDecorator, name: importData !.name}));\n"
],
"file_path": "packages/core/schematics/utils/ng_decorators.ts",
"type": "replace",
"edit_start_line_idx": 24
} | /**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
import * as ts from 'typescript';
import {getCallDecoratorImport} from './typescript/decorators';
export interface NgDecorator {
name: string;
node: ts.Decorator;
}
/**
* Gets all decorators which are imported from an Angular package (e.g. "@angular/core")
* from a list of decorators.
*/
export function getAngularDecorators(
typeChecker: ts.TypeChecker, decorators: ReadonlyArray<ts.Decorator>): NgDecorator[] {
return decorators.map(node => ({node, importData: getCallDecoratorImport(typeChecker, node)}))
.filter(({importData}) => importData && importData.importModule.startsWith('@angular/'))
.map(({node, importData}) => ({node, name: importData !.name}));
}
| packages/core/schematics/utils/ng_decorators.ts | 1 | https://github.com/angular/angular/commit/15eb1e0ce1ce7fbd7a833cef3f76c53297f7e24f | [
0.9842231869697571,
0.3285408914089203,
0.00016443096683360636,
0.001235038973391056,
0.4636376202106476
] |
{
"id": 4,
"code_window": [
" */\n",
"export function getAngularDecorators(\n",
" typeChecker: ts.TypeChecker, decorators: ReadonlyArray<ts.Decorator>): NgDecorator[] {\n",
" return decorators.map(node => ({node, importData: getCallDecoratorImport(typeChecker, node)}))\n",
" .filter(({importData}) => importData && importData.importModule.startsWith('@angular/'))\n",
" .map(({node, importData}) => ({node, name: importData !.name}));\n",
"}"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep"
],
"after_edit": [
" .map(\n",
" ({node, importData}) =>\n",
" ({node: node as CallExpressionDecorator, name: importData !.name}));\n"
],
"file_path": "packages/core/schematics/utils/ng_decorators.ts",
"type": "replace",
"edit_start_line_idx": 24
} | import { Component } from '@angular/core';
// #docregion component
@Component({
selector: 'app-banner',
template: '<h1>{{title}}</h1>',
styles: ['h1 { color: green; font-size: 350%}']
})
export class BannerComponent {
title = 'Test Tour of Heroes';
}
// #enddocregion component
| aio/content/examples/testing/src/app/banner/banner.component.ts | 0 | https://github.com/angular/angular/commit/15eb1e0ce1ce7fbd7a833cef3f76c53297f7e24f | [
0.00017310997645836323,
0.000171607403899543,
0.00017010483134072274,
0.000171607403899543,
0.0000015025725588202477
] |
{
"id": 4,
"code_window": [
" */\n",
"export function getAngularDecorators(\n",
" typeChecker: ts.TypeChecker, decorators: ReadonlyArray<ts.Decorator>): NgDecorator[] {\n",
" return decorators.map(node => ({node, importData: getCallDecoratorImport(typeChecker, node)}))\n",
" .filter(({importData}) => importData && importData.importModule.startsWith('@angular/'))\n",
" .map(({node, importData}) => ({node, name: importData !.name}));\n",
"}"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep"
],
"after_edit": [
" .map(\n",
" ({node, importData}) =>\n",
" ({node: node as CallExpressionDecorator, name: importData !.name}));\n"
],
"file_path": "packages/core/schematics/utils/ng_decorators.ts",
"type": "replace",
"edit_start_line_idx": 24
} | /**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
// THIS CODE IS GENERATED - DO NOT MODIFY
// See angular/tools/gulp-tasks/cldr/extract.js
const u = undefined;
function plural(n: number): number {
let i = Math.floor(Math.abs(n)), v = n.toString().replace(/^[^.]*\.?/, '').length;
if (i === 1 && v === 0) return 1;
return 5;
}
export default [
'en-TV', [['a', 'p'], ['AM', 'PM'], u], [['AM', 'PM'], u, u],
[
['S', 'M', 'T', 'W', 'T', 'F', 'S'], ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'],
['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'],
['Su', 'Mo', 'Tu', 'We', 'Th', 'Fr', 'Sa']
],
u,
[
['J', 'F', 'M', 'A', 'M', 'J', 'J', 'A', 'S', 'O', 'N', 'D'],
['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'],
[
'January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September',
'October', 'November', 'December'
]
],
u, [['B', 'A'], ['BC', 'AD'], ['Before Christ', 'Anno Domini']], 1, [6, 0],
['dd/MM/y', 'd MMM y', 'd MMMM y', 'EEEE, d MMMM y'],
['HH:mm', 'HH:mm:ss', 'HH:mm:ss z', 'HH:mm:ss zzzz'], ['{1}, {0}', u, '{1} \'at\' {0}', u],
['.', ',', ';', '%', '+', '-', 'E', '×', '‰', '∞', 'NaN', ':'],
['#,##0.###', '#,##0%', '¤#,##0.00', '#E0'], '$', 'Australian Dollar',
{'AUD': ['$'], 'JPY': ['JP¥', '¥'], 'USD': ['US$', '$']}, plural
];
| packages/common/locales/en-TV.ts | 0 | https://github.com/angular/angular/commit/15eb1e0ce1ce7fbd7a833cef3f76c53297f7e24f | [
0.00017718841263558716,
0.00017460252274759114,
0.00017229665536433458,
0.00017507972370367497,
0.0000017323471865893225
] |
{
"id": 4,
"code_window": [
" */\n",
"export function getAngularDecorators(\n",
" typeChecker: ts.TypeChecker, decorators: ReadonlyArray<ts.Decorator>): NgDecorator[] {\n",
" return decorators.map(node => ({node, importData: getCallDecoratorImport(typeChecker, node)}))\n",
" .filter(({importData}) => importData && importData.importModule.startsWith('@angular/'))\n",
" .map(({node, importData}) => ({node, name: importData !.name}));\n",
"}"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep"
],
"after_edit": [
" .map(\n",
" ({node, importData}) =>\n",
" ({node: node as CallExpressionDecorator, name: importData !.name}));\n"
],
"file_path": "packages/core/schematics/utils/ng_decorators.ts",
"type": "replace",
"edit_start_line_idx": 24
} | // #docplaster
// #docregion
import { Component } from '@angular/core';
import { Config, ConfigService } from './config.service';
import { MessageService } from '../message.service';
@Component({
selector: 'app-config',
templateUrl: './config.component.html',
providers: [ ConfigService ],
styles: ['.error {color: red;}']
})
export class ConfigComponent {
error: any;
headers: string[];
// #docregion v2
config: Config;
// #enddocregion v2
constructor(private configService: ConfigService) {}
clear() {
this.config = undefined;
this.error = undefined;
this.headers = undefined;
}
// #docregion v1, v2, v3
showConfig() {
this.configService.getConfig()
// #enddocregion v1, v2
.subscribe(
(data: Config) => this.config = { ...data }, // success path
error => this.error = error // error path
);
}
// #enddocregion v3
showConfig_v1() {
this.configService.getConfig_1()
// #docregion v1, v1_callback
.subscribe((data: Config) => this.config = {
heroesUrl: data['heroesUrl'],
textfile: data['textfile']
});
// #enddocregion v1_callback
}
// #enddocregion v1
showConfig_v2() {
this.configService.getConfig()
// #docregion v2, v2_callback
// clone the data object, using its known Config shape
.subscribe((data: Config) => this.config = { ...data });
// #enddocregion v2_callback
}
// #enddocregion v2
// #docregion showConfigResponse
showConfigResponse() {
this.configService.getConfigResponse()
// resp is of type `HttpResponse<Config>`
.subscribe(resp => {
// display its headers
const keys = resp.headers.keys();
this.headers = keys.map(key =>
`${key}: ${resp.headers.get(key)}`);
// access the body directly, which is typed as `Config`.
this.config = { ... resp.body };
});
}
// #enddocregion showConfigResponse
makeError() {
this.configService.makeIntentionalError().subscribe(null, error => this.error = error );
}
}
// #enddocregion
| aio/content/examples/http/src/app/config/config.component.ts | 0 | https://github.com/angular/angular/commit/15eb1e0ce1ce7fbd7a833cef3f76c53297f7e24f | [
0.00017788652621675283,
0.0001763476466294378,
0.0001731700758682564,
0.00017682064208202064,
0.0000014413020608117222
] |
{
"id": 0,
"code_window": [
"\t\tthis.createMatches();\n",
"\t\tthis.registerListeners();\n",
"\t}\n",
"\n",
"\tprivate createMatches(): void {\n",
"\t\tlet model = this.modelService ? this.modelService.getModel(this._resource) : null;\n",
"\t\tif (model) {\n",
"\t\t\tthis.bindModel(model);\n",
"\t\t\tthis.updateMatches();\n",
"\t\t} else {\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\tlet model = this.modelService.getModel(this._resource);\n"
],
"file_path": "src/vs/workbench/parts/search/common/searchModel.ts",
"type": "replace",
"edit_start_line_idx": 110
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
'use strict';
import * as assert from 'assert';
import * as sinon from 'sinon';
import { TestInstantiationService } from 'vs/test/utils/instantiationTestUtils';
import { DeferredPPromise } from 'vs/test/utils/promiseTestUtils';
import { PPromise } from 'vs/base/common/winjs.base';
import { nullEvent } from 'vs/base/common/timer';
import { SearchModel } from 'vs/workbench/parts/search/common/searchModel';
import URI from 'vs/base/common/uri';
import {IFileMatch, ILineMatch} from 'vs/platform/search/common/search';
import { ITelemetryService } from 'vs/platform/telemetry/common/telemetry';
import { ISearchService, ISearchComplete, ISearchProgressItem } from 'vs/platform/search/common/search';
import { Range } from 'vs/editor/common/core/range';
suite('SearchModel', () => {
let instantiationService: TestInstantiationService;
let restoreStubs;
setup(() => {
restoreStubs= [];
instantiationService= new TestInstantiationService();
instantiationService.stub(ITelemetryService);
});
teardown(() => {
restoreStubs.forEach(element => {
element.restore();
});
});
test('Search Model: Search adds to results', function () {
let results= [aRawMatch('file://c:/1', aLineMatch('preview 1', 1, [[1, 3], [4, 7]])), aRawMatch('file://c:/2', aLineMatch('preview 2'))];
instantiationService.stub(ISearchService, 'search', PPromise.as({results: results}));
let testObject= instantiationService.createInstance(SearchModel);
testObject.search({contentPattern: {pattern: 'somestring'}, type: 1});
let actual= testObject.searchResult.matches();
assert.equal(2, actual.length);
assert.equal('file://c:/1', actual[0].resource().toString());
let actuaMatches= actual[0].matches();
assert.equal(2, actuaMatches.length);
assert.equal('preview 1', actuaMatches[0].text());
assert.ok(new Range(2, 2, 2, 5).equalsRange(actuaMatches[0].range()));
assert.equal('preview 1', actuaMatches[1].text());
assert.ok(new Range(2, 5, 2, 12).equalsRange(actuaMatches[1].range()));
actuaMatches= actual[1].matches();
assert.equal(1, actuaMatches.length);
assert.equal('preview 2', actuaMatches[0].text());
assert.ok(new Range(2, 1, 2, 2).equalsRange(actuaMatches[0].range()));
});
test('Search Model: Search adds to results during progress', function (done) {
let results= [aRawMatch('file://c:/1', aLineMatch('preview 1', 1, [[1, 3], [4, 7]])), aRawMatch('file://c:/2', aLineMatch('preview 2'))];
let promise= new DeferredPPromise<ISearchComplete, ISearchProgressItem>();
instantiationService.stub(ISearchService, 'search', promise);
let testObject= instantiationService.createInstance(SearchModel);
let result= testObject.search({contentPattern: {pattern: 'somestring'}, type: 1});
promise.progress(results[0]);
promise.progress(results[1]);
promise.complete({results: []});
result.done(() => {
let actual= testObject.searchResult.matches();
assert.equal(2, actual.length);
assert.equal('file://c:/1', actual[0].resource().toString());
let actuaMatches= actual[0].matches();
assert.equal(2, actuaMatches.length);
assert.equal('preview 1', actuaMatches[0].text());
assert.ok(new Range(2, 2, 2, 5).equalsRange(actuaMatches[0].range()));
assert.equal('preview 1', actuaMatches[1].text());
assert.ok(new Range(2, 5, 2, 12).equalsRange(actuaMatches[1].range()));
actuaMatches= actual[1].matches();
assert.equal(1, actuaMatches.length);
assert.equal('preview 2', actuaMatches[0].text());
assert.ok(new Range(2, 1, 2, 2).equalsRange(actuaMatches[0].range()));
done();
});
});
test('Search Model: Search reports telemetry on search completed', function () {
let target= instantiationService.spy(ITelemetryService, 'publicLog');
let results= [aRawMatch('file://c:/1', aLineMatch('preview 1', 1, [[1, 3], [4, 7]])), aRawMatch('file://c:/2', aLineMatch('preview 2'))];
instantiationService.stub(ISearchService, 'search', PPromise.as({results: results}));
let testObject= instantiationService.createInstance(SearchModel);
testObject.search({contentPattern: {pattern: 'somestring'}, type: 1});
assert.ok(target.calledOnce);
assert.deepEqual(['searchResultsShown', {count: 3, fileCount: 2}], target.args[0]);
});
test('Search Model: Search reports timed telemetry on search when progress is not called', function () {
let target2= sinon.spy();
stub(nullEvent, 'stop', target2);
let target1= sinon.stub().returns(nullEvent);
instantiationService.stub(ITelemetryService, 'timedPublicLog', target1);
instantiationService.stub(ISearchService, 'search', PPromise.as({results: []}));
let testObject= instantiationService.createInstance(SearchModel);
testObject.search({contentPattern: {pattern: 'somestring'}, type: 1});
assert.ok(target1.calledTwice);
assert.ok(target1.calledWith('searchResultsFirstRender'));
assert.ok(target1.calledWith('searchResultsFinished'));
assert.ok(target2.calledThrice);
});
test('Search Model: Search reports timed telemetry on search when progress is called', function (done) {
let target2= sinon.spy();
stub(nullEvent, 'stop', target2);
let target1= sinon.stub().returns(nullEvent);
instantiationService.stub(ITelemetryService, 'timedPublicLog', target1);
let promise= new DeferredPPromise<ISearchComplete, ISearchProgressItem>();
instantiationService.stub(ISearchService, 'search', promise);
let testObject= instantiationService.createInstance(SearchModel);
let result= testObject.search({contentPattern: {pattern: 'somestring'}, type: 1});
promise.progress(aRawMatch('file://c:/1', aLineMatch('some preview')));
promise.complete({results: []});
result.done(() => {
assert.ok(target1.calledTwice);
assert.ok(target1.calledWith('searchResultsFirstRender'));
assert.ok(target1.calledWith('searchResultsFinished'));
assert.equal(4, target2.callCount);
done();
});
});
test('Search Model: Search reports timed telemetry on search when error is called', function (done) {
let target2= sinon.spy();
stub(nullEvent, 'stop', target2);
let target1= sinon.stub().returns(nullEvent);
instantiationService.stub(ITelemetryService, 'timedPublicLog', target1);
let promise= new DeferredPPromise<ISearchComplete, ISearchProgressItem>();
instantiationService.stub(ISearchService, 'search', promise);
let testObject= instantiationService.createInstance(SearchModel);
let result= testObject.search({contentPattern: {pattern: 'somestring'}, type: 1});
promise.error('error');
result.done(() => {}, () => {
assert.ok(target1.calledTwice);
assert.ok(target1.calledWith('searchResultsFirstRender'));
assert.ok(target1.calledWith('searchResultsFinished'));
assert.ok(target2.calledThrice);
done();
});
});
test('Search Model: Search reports timed telemetry on search when error is cancelled error', function (done) {
let target2= sinon.spy();
stub(nullEvent, 'stop', target2);
let target1= sinon.stub().returns(nullEvent);
instantiationService.stub(ITelemetryService, 'timedPublicLog', target1);
let promise= new DeferredPPromise<ISearchComplete, ISearchProgressItem>();
instantiationService.stub(ISearchService, 'search', promise);
let testObject= instantiationService.createInstance(SearchModel);
let result= testObject.search({contentPattern: {pattern: 'somestring'}, type: 1});
promise.cancel();
result.done(() => {}, () => {
assert.ok(target1.calledTwice);
assert.ok(target1.calledWith('searchResultsFirstRender'));
assert.ok(target1.calledWith('searchResultsFinished'));
assert.ok(target2.calledThrice);
done();
});
});
test('Search Model: Search results are cleared during search', function () {
let results= [aRawMatch('file://c:/1', aLineMatch('preview 1', 1, [[1, 3], [4, 7]])), aRawMatch('file://c:/2', aLineMatch('preview 2'))];
instantiationService.stub(ISearchService, 'search', PPromise.as({results: results}));
let testObject:SearchModel= instantiationService.createInstance(SearchModel);
testObject.search({contentPattern: {pattern: 'somestring'}, type: 1});
assert.ok(!testObject.searchResult.isEmpty());
instantiationService.stub(ISearchService, 'search', new DeferredPPromise<ISearchComplete, ISearchProgressItem>());
testObject.search({contentPattern: {pattern: 'somestring'}, type: 1});
assert.ok(testObject.searchResult.isEmpty());
});
test('Search Model: Previous search is cancelled when new search is called', function () {
let target= sinon.spy();
instantiationService.stub(ISearchService, 'search', new DeferredPPromise((c, e, p) => {}, target));
let testObject:SearchModel= instantiationService.createInstance(SearchModel);
testObject.search({contentPattern: {pattern: 'somestring'}, type: 1});
instantiationService.stub(ISearchService, 'search', new DeferredPPromise<ISearchComplete, ISearchProgressItem>());
testObject.search({contentPattern: {pattern: 'somestring'}, type: 1});
assert.ok(target.calledOnce);
});
test('Search Model: isReplaceActive return false if no replace text is set', function () {
let testObject:SearchModel= instantiationService.createInstance(SearchModel);
assert.ok(!testObject.isReplaceActive());
});
test('Search Model: isReplaceActive return false if replace text is set to null', function () {
let testObject:SearchModel= instantiationService.createInstance(SearchModel);
testObject.replaceText= null;
assert.ok(!testObject.isReplaceActive());
});
test('Search Model: isReplaceActive return false if replace text is set to undefined', function () {
let testObject:SearchModel= instantiationService.createInstance(SearchModel);
testObject.replaceText= void 0;
assert.ok(!testObject.isReplaceActive());
});
test('Search Model: isReplaceActive return true if replace text is set to empty string', function () {
let testObject:SearchModel= instantiationService.createInstance(SearchModel);
testObject.replaceText= '';
assert.ok(testObject.isReplaceActive());
});
test('Search Model: isReplaceActive return true if replace text is set to non empty string', function () {
let testObject:SearchModel= instantiationService.createInstance(SearchModel);
testObject.replaceText= 'some value';
assert.ok(testObject.isReplaceActive());
});
test('Search Model: hasReplaceText return false if no replace text is set', function () {
let testObject:SearchModel= instantiationService.createInstance(SearchModel);
assert.ok(!testObject.hasReplaceText());
});
test('Search Model: hasReplaceText return false if replace text is set to null', function () {
let testObject:SearchModel= instantiationService.createInstance(SearchModel);
testObject.replaceText= null;
assert.ok(!testObject.hasReplaceText());
});
test('Search Model: hasReplaceText return false if replace text is set to undefined', function () {
let testObject:SearchModel= instantiationService.createInstance(SearchModel);
testObject.replaceText= void 0;
assert.ok(!testObject.hasReplaceText());
});
test('Search Model: hasReplaceText return false if replace text is set to empty string', function () {
let testObject:SearchModel= instantiationService.createInstance(SearchModel);
testObject.replaceText= '';
assert.ok(!testObject.hasReplaceText());
});
test('Search Model: hasReplaceText return true if replace text is set to non empty string', function () {
let testObject:SearchModel= instantiationService.createInstance(SearchModel);
testObject.replaceText= 'some value';
assert.ok(testObject.hasReplaceText());
});
function aRawMatch(resource: string, ...lineMatches: ILineMatch[]): IFileMatch {
return { resource: URI.parse(resource), lineMatches };
}
function aLineMatch(preview: string, lineNumber: number = 1, offsetAndLengths: number[][] = [[0, 1]]): ILineMatch {
return { preview, lineNumber, offsetAndLengths };
}
function stub(arg1, arg2, arg3) : sinon.SinonStub {
const stub= sinon.stub(arg1, arg2, arg3);
restoreStubs.push(stub);
return stub;
}
}); | src/vs/workbench/parts/search/test/common/searchModel.test.ts | 1 | https://github.com/microsoft/vscode/commit/e12eb3dc06b131a8c00fbe61c77ae98311f103e9 | [
0.08951809257268906,
0.003077253233641386,
0.00016361627785954624,
0.0001707333722151816,
0.015782399103045464
] |
{
"id": 0,
"code_window": [
"\t\tthis.createMatches();\n",
"\t\tthis.registerListeners();\n",
"\t}\n",
"\n",
"\tprivate createMatches(): void {\n",
"\t\tlet model = this.modelService ? this.modelService.getModel(this._resource) : null;\n",
"\t\tif (model) {\n",
"\t\t\tthis.bindModel(model);\n",
"\t\t\tthis.updateMatches();\n",
"\t\t} else {\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\tlet model = this.modelService.getModel(this._resource);\n"
],
"file_path": "src/vs/workbench/parts/search/common/searchModel.ts",
"type": "replace",
"edit_start_line_idx": 110
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
// Do not edit this file. It is machine generated.
{
"extensions": "拡張機能"
} | i18n/jpn/src/vs/platform/extensionManagement/common/extensionManagement.i18n.json | 0 | https://github.com/microsoft/vscode/commit/e12eb3dc06b131a8c00fbe61c77ae98311f103e9 | [
0.00017861822561826557,
0.00017861822561826557,
0.00017861822561826557,
0.00017861822561826557,
0
] |
{
"id": 0,
"code_window": [
"\t\tthis.createMatches();\n",
"\t\tthis.registerListeners();\n",
"\t}\n",
"\n",
"\tprivate createMatches(): void {\n",
"\t\tlet model = this.modelService ? this.modelService.getModel(this._resource) : null;\n",
"\t\tif (model) {\n",
"\t\t\tthis.bindModel(model);\n",
"\t\t\tthis.updateMatches();\n",
"\t\t} else {\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\tlet model = this.modelService.getModel(this._resource);\n"
],
"file_path": "src/vs/workbench/parts/search/common/searchModel.ts",
"type": "replace",
"edit_start_line_idx": 110
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
'use strict';
import 'vs/css!./gotoLine';
import * as nls from 'vs/nls';
import {IContext, QuickOpenEntry, QuickOpenModel} from 'vs/base/parts/quickopen/browser/quickOpenModel';
import {IAutoFocus, Mode} from 'vs/base/parts/quickopen/common/quickOpen';
import * as editorCommon from 'vs/editor/common/editorCommon';
import {ICodeEditor, IDiffEditor} from 'vs/editor/browser/editorBrowser';
import {BaseEditorQuickOpenAction, IDecorator} from './editorQuickOpen';
interface ParseResult {
position: editorCommon.IPosition;
isValid: boolean;
label: string;
}
export class GotoLineEntry extends QuickOpenEntry {
private _parseResult: ParseResult;
private decorator: IDecorator;
private editor: editorCommon.IEditor;
constructor(line: string, editor: editorCommon.IEditor, decorator: IDecorator) {
super();
this.editor = editor;
this.decorator = decorator;
this._parseResult = this._parseInput(line);
}
private _parseInput(line: string): ParseResult {
let numbers = line.split(',').map(part => parseInt(part, 10)).filter(part => !isNaN(part)),
position: editorCommon.IPosition;
if (numbers.length === 0) {
position = { lineNumber: -1, column: -1 };
} else if (numbers.length === 1) {
position = { lineNumber: numbers[0], column: 1 };
} else {
position = { lineNumber: numbers[0], column: numbers[1] };
}
let editorType = (<ICodeEditor>this.editor).getEditorType(),
model: editorCommon.IModel;
switch (editorType) {
case editorCommon.EditorType.IDiffEditor:
model = (<IDiffEditor>this.editor).getModel().modified;
break;
case editorCommon.EditorType.ICodeEditor:
model = (<ICodeEditor>this.editor).getModel();
break;
default:
throw new Error();
}
let isValid = model.validatePosition(position).equals(position),
label: string;
if (isValid) {
if (position.column && position.column > 1) {
label = nls.localize('gotoLineLabelValidLineAndColumn', "Go to line {0} and column {1}", position.lineNumber, position.column);
} else {
label = nls.localize('gotoLineLabelValidLine', "Go to line {0}", position.lineNumber, position.column);
}
} else if (position.lineNumber < 1 || position.lineNumber > model.getLineCount()) {
label = nls.localize('gotoLineLabelEmptyWithLineLimit', "Type a line number between 1 and {0} to navigate to", model.getLineCount());
} else {
label = nls.localize('gotoLineLabelEmptyWithLineAndColumnLimit', "Type a column between 1 and {0} to navigate to", model.getLineMaxColumn(position.lineNumber));
}
return {
position: position,
isValid: isValid,
label: label
};
}
public getLabel(): string {
return this._parseResult.label;
}
public getAriaLabel(): string {
return nls.localize('gotoLineAriaLabel', "Go to line {0}", this._parseResult.label);
}
public run(mode: Mode, context: IContext): boolean {
if (mode === Mode.OPEN) {
return this.runOpen();
}
return this.runPreview();
}
public runOpen(): boolean {
// No-op if range is not valid
if (!this._parseResult.isValid) {
return false;
}
// Apply selection and focus
let range = this.toSelection();
(<ICodeEditor>this.editor).setSelection(range);
(<ICodeEditor>this.editor).revealRangeInCenter(range);
this.editor.focus();
return true;
}
public runPreview(): boolean {
// No-op if range is not valid
if (!this._parseResult.isValid) {
this.decorator.clearDecorations();
return false;
}
// Select Line Position
let range = this.toSelection();
this.editor.revealRangeInCenter(range);
// Decorate if possible
this.decorator.decorateLine(range, this.editor);
return false;
}
private toSelection(): editorCommon.IRange {
return {
startLineNumber: this._parseResult.position.lineNumber,
startColumn: this._parseResult.position.column,
endLineNumber: this._parseResult.position.lineNumber,
endColumn: this._parseResult.position.column
};
}
}
export class GotoLineAction extends BaseEditorQuickOpenAction {
public static ID = 'editor.action.gotoLine';
constructor(descriptor: editorCommon.IEditorActionDescriptorData, editor: editorCommon.ICommonCodeEditor) {
super(descriptor, editor, nls.localize('GotoLineAction.label', "Go to Line..."));
}
_getModel(value: string): QuickOpenModel {
return new QuickOpenModel([new GotoLineEntry(value, this.editor, this)]);
}
_getAutoFocus(searchValue: string): IAutoFocus {
return {
autoFocusFirstEntry: searchValue.length > 0
};
}
_getInputAriaLabel(): string {
return nls.localize('gotoLineActionInput', "Type a line number, followed by an optional colon and a column number to navigate to");
}
} | src/vs/editor/contrib/quickOpen/browser/gotoLine.ts | 0 | https://github.com/microsoft/vscode/commit/e12eb3dc06b131a8c00fbe61c77ae98311f103e9 | [
0.9446811676025391,
0.07977290451526642,
0.0001676244573900476,
0.00017434838810004294,
0.23637078702449799
] |
{
"id": 0,
"code_window": [
"\t\tthis.createMatches();\n",
"\t\tthis.registerListeners();\n",
"\t}\n",
"\n",
"\tprivate createMatches(): void {\n",
"\t\tlet model = this.modelService ? this.modelService.getModel(this._resource) : null;\n",
"\t\tif (model) {\n",
"\t\t\tthis.bindModel(model);\n",
"\t\t\tthis.updateMatches();\n",
"\t\t} else {\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\tlet model = this.modelService.getModel(this._resource);\n"
],
"file_path": "src/vs/workbench/parts/search/common/searchModel.ts",
"type": "replace",
"edit_start_line_idx": 110
} | <?xml version="1.0" encoding="utf-8"?>
<!-- Generator: Adobe Illustrator 19.1.0, SVG Export Plug-In . SVG Version: 6.00 Build 0) -->
<svg version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px"
viewBox="0 0 10.3 10" style="enable-background:new 0 0 10.3 10;" xml:space="preserve">
<style type="text/css">
.st0{display:none;}
.st1{display:inline;opacity:0.2;fill:#ED1C24;}
.st2{display:inline;opacity:0.43;fill:#39B54A;}
.st3{fill:#353535;}
.st4{fill:#FFFFFF;}
.st5{display:inline;opacity:0.8;fill:#353535;}
.st6{display:inline;}
.st7{display:inline;opacity:0.8;fill:#321F5A;}
.st8{opacity:0.15;fill:#353535;}
.st9{display:inline;opacity:0.34;}
.st10{fill:#070909;}
.st11{fill:#333333;}
.st12{fill:#7551A0;}
.st13{fill:#D2D2D2;}
.st14{fill:#E6E7E8;}
.st15{fill:#3076BC;}
.st16{display:none;fill:#3076BC;}
.st17{display:inline;fill:#321F5A;}
.st18{fill:#FF8E00;}
.st19{display:none;fill:none;stroke:#BCBEC0;stroke-miterlimit:10;}
.st20{opacity:0.52;}
.st21{fill:none;stroke:#BE1E2D;stroke-miterlimit:10;}
.st22{fill:#BE1E2D;}
.st23{display:none;opacity:0.2;}
.st24{display:inline;opacity:0.2;}
.st25{fill:#656565;}
.st26{fill:#D1D3D4;}
.st27{fill:#EEEEEE;}
.st28{display:none;fill-rule:evenodd;clip-rule:evenodd;fill:#F4F4F4;}
.st29{fill:#505150;}
.st30{display:none;fill:#BFD8E8;}
.st31{fill:#224096;}
.st32{fill:#17244E;}
.st33{display:inline;fill:#353535;}
.st34{display:none;fill:#F1F2F2;}
.st35{fill:#009444;}
.st36{fill:none;stroke:#505150;stroke-miterlimit:10;}
.st37{fill:#B9D532;}
.st38{fill:none;stroke:#D9D9D8;stroke-width:0.72;stroke-linejoin:round;stroke-miterlimit:10;}
.st39{fill:none;stroke:#D2D2D2;stroke-miterlimit:10;}
.st40{display:inline;fill:#333333;}
.st41{display:inline;fill:#7551A0;}
.st42{display:inline;fill:#D2D2D2;}
.st43{fill-rule:evenodd;clip-rule:evenodd;fill:#EEEEEE;}
.st44{fill:#321F5A;}
.st45{fill:none;stroke:#BCBEC0;stroke-miterlimit:10;}
.st46{opacity:0.53;fill:#FFFFFF;}
.st47{fill:none;stroke:#ED1C24;stroke-miterlimit:10;}
.st48{fill:#ED1C24;}
.st49{display:inline;opacity:0.1;fill:#E71E27;}
.st50{display:inline;opacity:0.3;}
.st51{fill:#E71E27;}
.st52{display:inline;opacity:0.2;fill:#E71E27;}
.st53{display:inline;fill:none;stroke:#ED1C24;stroke-miterlimit:10;}
.st54{fill:none;stroke:#2E3192;stroke-miterlimit:10;}
.st55{fill:#2E3192;}
.st56{fill:none;stroke:#FFF200;stroke-miterlimit:10;}
.st57{fill:#FFF200;}
</style>
<g id="grids">
</g>
<g id="Layer_2" class="st0">
</g>
<g id="home">
</g>
<g id="VSOdetails">
<g id="overview2">
</g>
</g>
<g id="reviews">
</g>
<g id="QA_2">
</g>
<g id="CARDS-RL">
<g>
<g>
<path class="st18" d="M8,9.8c-0.1,0-0.2,0-0.2-0.1L5.2,7.8L2.6,9.7c-0.1,0.1-0.3,0.1-0.5,0C1.9,9.6,1.9,9.4,1.9,9.2l1-3.1
L0.3,4.3C0.2,4.2,0.1,4,0.2,3.8c0.1-0.2,0.2-0.3,0.4-0.3h3.2l1-3.1C4.8,0.3,5,0.2,5.2,0.2c0.2,0,0.3,0.1,0.4,0.3l1,3.1h3.2
c0.2,0,0.3,0.1,0.4,0.3c0.1,0.2,0,0.3-0.1,0.5L7.4,6.2l1,3.1c0.1,0.2,0,0.3-0.1,0.5C8.2,9.7,8.1,9.8,8,9.8z"/>
</g>
</g>
</g>
<g id="sticky">
</g>
<g id="REDLINES" class="st0">
</g>
</svg>
| src/vs/workbench/parts/extensions/electron-browser/media/FullStarLight.svg | 0 | https://github.com/microsoft/vscode/commit/e12eb3dc06b131a8c00fbe61c77ae98311f103e9 | [
0.0001788568333722651,
0.00017514063802082092,
0.00016862171469256282,
0.00017598806880414486,
0.0000027669495921145426
] |
{
"id": 1,
"code_window": [
"\t\t\t});\n",
"\t\t}\n",
"\t}\n",
"\n",
"\tprivate registerListeners(): void {\n",
"\t\tif (this.modelService) {\n",
"\t\t\tthis._register(this.modelService.onModelAdded((model: IModel) => {\n",
"\t\t\t\tif (model.uri.toString() === this._resource.toString()) {\n",
"\t\t\t\t\tthis.bindModel(model);\n",
"\t\t\t\t}\n",
"\t\t\t}));\n",
"\t\t}\n",
"\t}\n",
"\n",
"\tprivate bindModel(model: IModel): void {\n",
"\t\tthis._model= model;\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\tthis._register(this.modelService.onModelAdded((model: IModel) => {\n",
"\t\t\tif (model.uri.toString() === this._resource.toString()) {\n",
"\t\t\t\tthis.bindModel(model);\n",
"\t\t\t}\n",
"\t\t}));\n"
],
"file_path": "src/vs/workbench/parts/search/common/searchModel.ts",
"type": "replace",
"edit_start_line_idx": 125
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
'use strict';
import * as assert from 'assert';
import uri from 'vs/base/common/uri';
import {Match, FileMatch, SearchResult} from 'vs/workbench/parts/search/common/searchModel';
import { TestInstantiationService } from 'vs/test/utils/instantiationTestUtils';
import {SearchSorter, SearchDataSource} from 'vs/workbench/parts/search/browser/searchResultsView';
import {IFileMatch, ILineMatch} from 'vs/platform/search/common/search';
function aFileMatch(path: string, searchResult?: SearchResult, ...lineMatches: ILineMatch[]): FileMatch {
let rawMatch: IFileMatch= {
resource: uri.file('C:\\' + path),
lineMatches: lineMatches
};
return new FileMatch(null, searchResult, rawMatch, null, null);
}
suite('Search - Viewlet', () => {
let instantiation: TestInstantiationService;
setup(() => {
instantiation = new TestInstantiationService();
});
test('Data Source', function () {
let ds = new SearchDataSource();
let result = instantiation.createInstance(SearchResult, null);
result.add([{
resource: uri.parse('file:///c:/foo'),
lineMatches: [{ lineNumber: 1, preview: 'bar', offsetAndLengths: [[0, 1]] }]
}]);
let fileMatch = result.matches()[0];
let lineMatch = fileMatch.matches()[0];
assert.equal(ds.getId(null, result), 'root');
assert.equal(ds.getId(null, fileMatch), 'file:///c%3A/foo');
assert.equal(ds.getId(null, lineMatch), 'file:///c%3A/foo>1>0');
assert(!ds.hasChildren(null, 'foo'));
assert(ds.hasChildren(null, result));
assert(ds.hasChildren(null, fileMatch));
assert(!ds.hasChildren(null, lineMatch));
});
test('Sorter', function () {
let fileMatch1 = aFileMatch('C:\\foo');
let fileMatch2 = aFileMatch('C:\\with\\path');
let fileMatch3 = aFileMatch('C:\\with\\path\\foo');
let lineMatch1 = new Match(fileMatch1, 'bar', 1, 1, 1);
let lineMatch2 = new Match(fileMatch1, 'bar', 2, 1, 1);
let lineMatch3 = new Match(fileMatch1, 'bar', 2, 1, 1);
let s = new SearchSorter();
assert(s.compare(null, fileMatch1, fileMatch2) < 0);
assert(s.compare(null, fileMatch2, fileMatch1) > 0);
assert(s.compare(null, fileMatch1, fileMatch1) === 0);
assert(s.compare(null, fileMatch2, fileMatch3) < 0);
assert(s.compare(null, lineMatch1, lineMatch2) < 0);
assert(s.compare(null, lineMatch2, lineMatch1) > 0);
assert(s.compare(null, lineMatch2, lineMatch3) === 0);
});
}); | src/vs/workbench/parts/search/test/browser/searchViewlet.test.ts | 1 | https://github.com/microsoft/vscode/commit/e12eb3dc06b131a8c00fbe61c77ae98311f103e9 | [
0.0001776304270606488,
0.0001751588424667716,
0.0001713366073090583,
0.00017597698024474084,
0.000002118121301464271
] |
{
"id": 1,
"code_window": [
"\t\t\t});\n",
"\t\t}\n",
"\t}\n",
"\n",
"\tprivate registerListeners(): void {\n",
"\t\tif (this.modelService) {\n",
"\t\t\tthis._register(this.modelService.onModelAdded((model: IModel) => {\n",
"\t\t\t\tif (model.uri.toString() === this._resource.toString()) {\n",
"\t\t\t\t\tthis.bindModel(model);\n",
"\t\t\t\t}\n",
"\t\t\t}));\n",
"\t\t}\n",
"\t}\n",
"\n",
"\tprivate bindModel(model: IModel): void {\n",
"\t\tthis._model= model;\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\tthis._register(this.modelService.onModelAdded((model: IModel) => {\n",
"\t\t\tif (model.uri.toString() === this._resource.toString()) {\n",
"\t\t\t\tthis.bindModel(model);\n",
"\t\t\t}\n",
"\t\t}));\n"
],
"file_path": "src/vs/workbench/parts/search/common/searchModel.ts",
"type": "replace",
"edit_start_line_idx": 125
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
// Do not edit this file. It is machine generated.
{
"meta.titleReference": " - Riferimenti di {0}",
"references.action.label": "Trova tutti i riferimenti",
"references.action.name": "Trova tutti i riferimenti"
} | i18n/ita/src/vs/editor/contrib/referenceSearch/browser/referenceSearch.i18n.json | 0 | https://github.com/microsoft/vscode/commit/e12eb3dc06b131a8c00fbe61c77ae98311f103e9 | [
0.00017608019697945565,
0.00017383077647536993,
0.0001715813559712842,
0.00017383077647536993,
0.0000022494205040857196
] |
{
"id": 1,
"code_window": [
"\t\t\t});\n",
"\t\t}\n",
"\t}\n",
"\n",
"\tprivate registerListeners(): void {\n",
"\t\tif (this.modelService) {\n",
"\t\t\tthis._register(this.modelService.onModelAdded((model: IModel) => {\n",
"\t\t\t\tif (model.uri.toString() === this._resource.toString()) {\n",
"\t\t\t\t\tthis.bindModel(model);\n",
"\t\t\t\t}\n",
"\t\t\t}));\n",
"\t\t}\n",
"\t}\n",
"\n",
"\tprivate bindModel(model: IModel): void {\n",
"\t\tthis._model= model;\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\tthis._register(this.modelService.onModelAdded((model: IModel) => {\n",
"\t\t\tif (model.uri.toString() === this._resource.toString()) {\n",
"\t\t\t\tthis.bindModel(model);\n",
"\t\t\t}\n",
"\t\t}));\n"
],
"file_path": "src/vs/workbench/parts/search/common/searchModel.ts",
"type": "replace",
"edit_start_line_idx": 125
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
// Do not edit this file. It is machine generated.
{
"alreadyCheckedOut": "{0} 분기는 이미 현재 분기입니다.",
"branchAriaLabel": "{0}, git 분기",
"checkoutBranch": "{0}의 분기",
"checkoutRemoteBranch": "{0}에서 원격 분기",
"checkoutTag": "{0}의 태그",
"createBranch": "분기 {0} 만들기",
"noBranches": "다른 분기 없음",
"notValidBranchName": "유효한 분기 이름을 제공하세요.",
"refAriaLabel": "{0}, git"
} | i18n/kor/src/vs/workbench/parts/git/browser/gitQuickOpen.i18n.json | 0 | https://github.com/microsoft/vscode/commit/e12eb3dc06b131a8c00fbe61c77ae98311f103e9 | [
0.00017431264859624207,
0.00017340961494483054,
0.00017250656674150378,
0.00017340961494483054,
9.030409273691475e-7
] |
{
"id": 1,
"code_window": [
"\t\t\t});\n",
"\t\t}\n",
"\t}\n",
"\n",
"\tprivate registerListeners(): void {\n",
"\t\tif (this.modelService) {\n",
"\t\t\tthis._register(this.modelService.onModelAdded((model: IModel) => {\n",
"\t\t\t\tif (model.uri.toString() === this._resource.toString()) {\n",
"\t\t\t\t\tthis.bindModel(model);\n",
"\t\t\t\t}\n",
"\t\t\t}));\n",
"\t\t}\n",
"\t}\n",
"\n",
"\tprivate bindModel(model: IModel): void {\n",
"\t\tthis._model= model;\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\tthis._register(this.modelService.onModelAdded((model: IModel) => {\n",
"\t\t\tif (model.uri.toString() === this._resource.toString()) {\n",
"\t\t\t\tthis.bindModel(model);\n",
"\t\t\t}\n",
"\t\t}));\n"
],
"file_path": "src/vs/workbench/parts/search/common/searchModel.ts",
"type": "replace",
"edit_start_line_idx": 125
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
// Do not edit this file. It is machine generated.
{
"associations": "言語に対するファイルの関連付け (例 \"*.extension\": \"html\") を構成します。これらの関連付けは、インストールされている言語の既定の関連付けより優先されます。",
"autoReveal": "エクスプローラーでファイルを開くとき、自動的にファイルの内容を表示するかどうかを制御します。",
"autoSave": "ダーティ ファイルの自動保存を制御します。有効な値: \"{0}\"、\"{1}\"、\"{2}\"。\"{3}\" に設定すると、\"files.autoSaveDelay\" で遅延を構成できます。",
"autoSaveDelay": "ダーティ ファイルの自動保存の遅延をミリ秒単位で制御します。\"files.autoSave\" が \"{0}\" に設定されている場合のみ適用されます",
"binaryFileEditor": "バイナリ ファイル エディター",
"dynamicHeight": "開いているエディターのセクションの高さを要素の数に合わせて動的に調整するかどうかを制御します。",
"encoding": "ファイルの読み取り/書き込みで使用する既定の文字セット エンコーディング。",
"eol": "既定の改行文字。",
"exclude": "ファイルとフォルダーを除外するための glob パターンを構成します。",
"explore": "エクスプローラー",
"explorerConfigurationTitle": "ファイル エクスプローラー構成",
"files.exclude.boolean": "ファイル パスの照合基準となる glob パターン。これを true または false に設定すると、パターンがそれぞれ有効/無効になります。",
"files.exclude.when": "一致するファイルの兄弟をさらにチェックします。一致するファイル名の変数として $(basename) を使用します。",
"filesConfigurationTitle": "ファイル構成",
"openEditorsVisible": "[開いているエディター] ウィンドウに表示されているエディターの数。0 に設定するとウィンドウが非表示になります。",
"showExplorerViewlet": "エクスプローラーを表示",
"textFileEditor": "テキスト ファイル エディター",
"trimTrailingWhitespace": "有効にすると、ファイルの保存時に末尾の空白をトリミングします。",
"view": "表示",
"watcherExclude": "ファイル モニタリングから除外するファイル パスの glob パターンを構成します。この設定を変更すると、再起動が必要になります。始動時に Code が消費する CPU 時間が多い場合は、大規模なフォルダーを除外して初期ロードを減らせます。"
} | i18n/jpn/src/vs/workbench/parts/files/browser/files.contribution.i18n.json | 0 | https://github.com/microsoft/vscode/commit/e12eb3dc06b131a8c00fbe61c77ae98311f103e9 | [
0.00017736775043886155,
0.00016858929302543402,
0.00016406839131377637,
0.00016433173732366413,
0.0000062082376643957105
] |
{
"id": 2,
"code_window": [
"import {Match, FileMatch, SearchResult} from 'vs/workbench/parts/search/common/searchModel';\n",
"import { TestInstantiationService } from 'vs/test/utils/instantiationTestUtils';\n",
"import {SearchSorter, SearchDataSource} from 'vs/workbench/parts/search/browser/searchResultsView';\n",
"import {IFileMatch, ILineMatch} from 'vs/platform/search/common/search';\n",
"\n",
"function aFileMatch(path: string, searchResult?: SearchResult, ...lineMatches: ILineMatch[]): FileMatch {\n",
"\tlet rawMatch: IFileMatch= {\n",
"\t\tresource: uri.file('C:\\\\' + path),\n",
"\t\tlineMatches: lineMatches\n",
"\t};\n",
"\treturn new FileMatch(null, searchResult, rawMatch, null, null);\n",
"}\n",
"\n",
"suite('Search - Viewlet', () => {\n",
"\tlet instantiation: TestInstantiationService;\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"import { createMockModelService } from 'vs/test/utils/servicesTestUtils';\n",
"import { IModelService } from 'vs/editor/common/services/modelService';\n"
],
"file_path": "src/vs/workbench/parts/search/test/browser/searchViewlet.test.ts",
"type": "replace",
"edit_start_line_idx": 12
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
'use strict';
import * as assert from 'assert';
import * as sinon from 'sinon';
import { TestInstantiationService } from 'vs/test/utils/instantiationTestUtils';
import { Match, FileMatch, SearchResult, SearchModel } from 'vs/workbench/parts/search/common/searchModel';
import URI from 'vs/base/common/uri';
import {IFileMatch, ILineMatch} from 'vs/platform/search/common/search';
import { ITelemetryService } from 'vs/platform/telemetry/common/telemetry';
import { Range } from 'vs/editor/common/core/range';
suite('SearchResult', () => {
let instantiationService: TestInstantiationService;
setup(() => {
instantiationService= new TestInstantiationService();
instantiationService.stub(ITelemetryService);
});
test('Line Match', function () {
let fileMatch = aFileMatch('folder\\file.txt');
let lineMatch = new Match(fileMatch, 'foo bar', 1, 0, 3);
assert.equal(lineMatch.text(), 'foo bar');
assert.equal(lineMatch.range().startLineNumber, 2);
assert.equal(lineMatch.range().endLineNumber, 2);
assert.equal(lineMatch.range().startColumn, 1);
assert.equal(lineMatch.range().endColumn, 4);
});
test('Line Match - Remove', function () {
let fileMatch = aFileMatch('folder\\file.txt', null, ...[{
preview: 'foo bar',
lineNumber: 1,
offsetAndLengths: [[0, 3]]
}]);
let lineMatch = fileMatch.matches()[0];
fileMatch.remove(lineMatch);
assert.equal(fileMatch.matches().length, 0);
});
test('File Match', function () {
let fileMatch = aFileMatch('folder\\file.txt');
assert.equal(fileMatch.matches(), 0);
assert.equal(fileMatch.resource().toString(), 'file:///c%3A/folder/file.txt');
assert.equal(fileMatch.name(), 'file.txt');
fileMatch = aFileMatch('file.txt');
assert.equal(fileMatch.matches(), 0);
assert.equal(fileMatch.resource().toString(), 'file:///c%3A/file.txt');
assert.equal(fileMatch.name(), 'file.txt');
});
test('Alle Drei Zusammen', function () {
let searchResult = instantiationService.createInstance(SearchResult, null);
let fileMatch = aFileMatch('far\\boo', searchResult);
let lineMatch = new Match(fileMatch, 'foo bar', 1, 0, 3);
assert(lineMatch.parent() === fileMatch);
assert(fileMatch.parent() === searchResult);
});
test('Search Result: Adding a raw match will add a file match with line matches', function () {
let testObject = aSearchResult();
let target= [aRawMatch('file://c:/', aLineMatch('preview 1', 1, [[1, 3], [4, 7]]), aLineMatch('preview 2'))];
testObject.add(target);
assert.equal(3, testObject.count());
let actual= testObject.matches();
assert.equal(1, actual.length);
assert.equal('file://c:/', actual[0].resource().toString());
let actuaMatches= actual[0].matches();
assert.equal(3, actuaMatches.length);
assert.equal('preview 1', actuaMatches[0].text());
assert.ok(new Range(2, 2, 2, 5).equalsRange(actuaMatches[0].range()));
assert.equal('preview 1', actuaMatches[1].text());
assert.ok(new Range(2, 5, 2, 12).equalsRange(actuaMatches[1].range()));
assert.equal('preview 2', actuaMatches[2].text());
assert.ok(new Range(2, 1, 2, 2).equalsRange(actuaMatches[2].range()));
});
test('Search Result: Adding multiple raw matches', function () {
let testObject = aSearchResult();
let target= [aRawMatch('file://c:/1', aLineMatch('preview 1', 1, [[1, 3], [4, 7]])), aRawMatch('file://c:/2', aLineMatch('preview 2'))];
testObject.add(target);
assert.equal(3, testObject.count());
let actual= testObject.matches();
assert.equal(2, actual.length);
assert.equal('file://c:/1', actual[0].resource().toString());
let actuaMatches= actual[0].matches();
assert.equal(2, actuaMatches.length);
assert.equal('preview 1', actuaMatches[0].text());
assert.ok(new Range(2, 2, 2, 5).equalsRange(actuaMatches[0].range()));
assert.equal('preview 1', actuaMatches[1].text());
assert.ok(new Range(2, 5, 2, 12).equalsRange(actuaMatches[1].range()));
actuaMatches= actual[1].matches();
assert.equal(1, actuaMatches.length);
assert.equal('preview 2', actuaMatches[0].text());
assert.ok(new Range(2, 1, 2, 2).equalsRange(actuaMatches[0].range()));
});
test('Search Result: Dispose disposes matches', function () {
let target1= sinon.spy();
let target2= sinon.spy();
let testObject = aSearchResult();
testObject.add([aRawMatch('file://c:/1', aLineMatch('preview 1')), aRawMatch('file://c:/2', aLineMatch('preview 2'))]);
testObject.matches()[0].onDispose(target1);
testObject.matches()[1].onDispose(target2);
testObject.dispose();
assert.ok(testObject.isEmpty());
assert.ok(target1.calledOnce);
assert.ok(target2.calledOnce);
});
test('Search Result: Removing all line matches and adding back will add file back to result', function () {
let testObject = aSearchResult();
testObject.add([aRawMatch('file://c:/1', aLineMatch('preview 1'))]);
let target= testObject.matches()[0];
let matchToRemove= target.matches()[0];
target.remove(matchToRemove);
assert.ok(testObject.isEmpty());
target.add(matchToRemove, true);
assert.equal(1, testObject.fileCount());
assert.equal(target, testObject.matches()[0]);
});
//// ----- utils
//function lineHasDecorations(model: editor.IModel, lineNumber: number, decorations: { start: number; end: number; }[]): void {
// let lineDecorations:typeof decorations = [];
// let decs = model.getLineDecorations(lineNumber);
// for (let i = 0, len = decs.length; i < len; i++) {
// lineDecorations.push({
// start: decs[i].range.startColumn,
// end: decs[i].range.endColumn
// });
// }
// assert.deepEqual(lineDecorations, decorations);
//}
//
//function lineHasNoDecoration(model: editor.IModel, lineNumber: number): void {
// lineHasDecorations(model, lineNumber, []);
//}
//
//function lineHasDecoration(model: editor.IModel, lineNumber: number, start: number, end: number): void {
// lineHasDecorations(model, lineNumber, [{
// start: start,
// end: end
// }]);
//}
//// ----- end utils
//
//test('Model Highlights', function () {
//
// let fileMatch = instantiation.createInstance(FileMatch, null, toUri('folder\\file.txt'));
// fileMatch.add(new Match(fileMatch, 'line2', 1, 0, 2));
// fileMatch.connect();
// lineHasDecoration(oneModel, 2, 1, 3);
//});
//
//test('Dispose', function () {
//
// let fileMatch = instantiation.createInstance(FileMatch, null, toUri('folder\\file.txt'));
// fileMatch.add(new Match(fileMatch, 'line2', 1, 0, 2));
// fileMatch.connect();
// lineHasDecoration(oneModel, 2, 1, 3);
//
// fileMatch.dispose();
// lineHasNoDecoration(oneModel, 2);
//});
function aFileMatch(path: string, searchResult?: SearchResult, ...lineMatches: ILineMatch[]): FileMatch {
let rawMatch: IFileMatch = {
resource: URI.file('C:\\' + path),
lineMatches: lineMatches
};
return new FileMatch(null, searchResult, rawMatch, null, null);
}
function aSearchResult(): SearchResult {
let searchModel = instantiationService.createInstance(SearchModel);
return searchModel.searchResult;
}
function aRawMatch(resource: string, ...lineMatches: ILineMatch[]): IFileMatch {
return { resource: URI.parse(resource), lineMatches };
}
function aLineMatch(preview: string, lineNumber: number = 1, offsetAndLengths: number[][] = [[0, 1]]): ILineMatch {
return { preview, lineNumber, offsetAndLengths };
}
}); | src/vs/workbench/parts/search/test/common/searchResult.test.ts | 1 | https://github.com/microsoft/vscode/commit/e12eb3dc06b131a8c00fbe61c77ae98311f103e9 | [
0.998581051826477,
0.27503812313079834,
0.00016891234554350376,
0.00024813791969791055,
0.4349028468132019
] |
{
"id": 2,
"code_window": [
"import {Match, FileMatch, SearchResult} from 'vs/workbench/parts/search/common/searchModel';\n",
"import { TestInstantiationService } from 'vs/test/utils/instantiationTestUtils';\n",
"import {SearchSorter, SearchDataSource} from 'vs/workbench/parts/search/browser/searchResultsView';\n",
"import {IFileMatch, ILineMatch} from 'vs/platform/search/common/search';\n",
"\n",
"function aFileMatch(path: string, searchResult?: SearchResult, ...lineMatches: ILineMatch[]): FileMatch {\n",
"\tlet rawMatch: IFileMatch= {\n",
"\t\tresource: uri.file('C:\\\\' + path),\n",
"\t\tlineMatches: lineMatches\n",
"\t};\n",
"\treturn new FileMatch(null, searchResult, rawMatch, null, null);\n",
"}\n",
"\n",
"suite('Search - Viewlet', () => {\n",
"\tlet instantiation: TestInstantiationService;\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"import { createMockModelService } from 'vs/test/utils/servicesTestUtils';\n",
"import { IModelService } from 'vs/editor/common/services/modelService';\n"
],
"file_path": "src/vs/workbench/parts/search/test/browser/searchViewlet.test.ts",
"type": "replace",
"edit_start_line_idx": 12
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
'use strict';
import workbenchExt = require('vs/workbench/common/contributions');
import paths = require('vs/base/common/paths');
import async = require('vs/base/common/async');
import winjs = require('vs/base/common/winjs.base');
import extfs = require('vs/base/node/extfs');
import lifecycle = require('vs/base/common/lifecycle');
import tmsnippets = require('vs/editor/node/textMate/TMSnippets');
import {IFileService} from 'vs/platform/files/common/files';
import {ILifecycleService} from 'vs/platform/lifecycle/common/lifecycle';
import {IWorkspaceContextService} from 'vs/platform/workspace/common/workspace';
import fs = require('fs');
export class SnippetsTracker implements workbenchExt.IWorkbenchContribution {
private static FILE_WATCH_DELAY = 200;
private snippetFolder: string;
private toDispose: lifecycle.IDisposable[];
private watcher: fs.FSWatcher;
private fileWatchDelayer:async.ThrottledDelayer<void>;
constructor(
@IFileService private fileService: IFileService,
@ILifecycleService private lifecycleService: ILifecycleService,
@IWorkspaceContextService contextService: IWorkspaceContextService
) {
this.snippetFolder = paths.join(contextService.getConfiguration().env.appSettingsHome, 'snippets');
this.toDispose = [];
this.fileWatchDelayer = new async.ThrottledDelayer<void>(SnippetsTracker.FILE_WATCH_DELAY);
if (!fs.existsSync(this.snippetFolder)) {
fs.mkdirSync(this.snippetFolder);
}
this.scanUserSnippets().then(_ => {
this.registerListeners();
});
}
private registerListeners(): void {
var scheduler = new async.RunOnceScheduler(() => {
this.scanUserSnippets();
}, 500);
this.toDispose.push(scheduler);
try {
this.watcher = fs.watch(this.snippetFolder); // will be persistent but not recursive
this.watcher.on('change', (eventType: string) => {
if (eventType === 'delete') {
this.unregisterListener();
return;
}
scheduler.schedule();
});
} catch (error) {
// the path might not exist anymore, ignore this error and return
}
this.lifecycleService.onShutdown(this.dispose, this);
}
private scanUserSnippets() : winjs.Promise {
return readFilesInDir(this.snippetFolder, /\.json$/).then(snippetFiles => {
return winjs.TPromise.join(snippetFiles.map(snippetFile => {
var modeId = snippetFile.replace(/\.json$/, '').toLowerCase();
var snippetPath = paths.join(this.snippetFolder, snippetFile);
return tmsnippets.snippetUpdated(modeId, snippetPath);
}));
});
}
private unregisterListener(): void {
if (this.watcher) {
this.watcher.close();
this.watcher = null;
}
}
public getId(): string {
return 'vs.snippets.snippetsTracker';
}
public dispose(): void {
this.unregisterListener();
this.toDispose = lifecycle.dispose(this.toDispose);
}
}
function readDir(path: string): winjs.TPromise<string[]> {
return new winjs.TPromise<string[]>((c, e, p) => {
extfs.readdir(path,(err, files) => {
if (err) {
return e(err);
}
c(files);
});
});
}
function fileExists(path: string): winjs.TPromise<boolean> {
return new winjs.TPromise<boolean>((c, e, p) => {
fs.stat(path,(err, stats) => {
if (err) {
return c(false);
}
if (stats.isFile()) {
return c(true);
}
c(false);
});
});
}
function readFilesInDir(dirPath: string, namePattern:RegExp = null): winjs.TPromise<string[]> {
return readDir(dirPath).then((children) => {
return winjs.TPromise.join(
children.map((child) => {
if (namePattern && !namePattern.test(child)) {
return winjs.TPromise.as(null);
}
return fileExists(paths.join(dirPath, child)).then(isFile => {
return isFile ? child : null;
});
})
).then((subdirs) => {
return subdirs.filter(subdir => (subdir !== null));
});
});
} | src/vs/workbench/parts/snippets/electron-browser/snippetsTracker.ts | 0 | https://github.com/microsoft/vscode/commit/e12eb3dc06b131a8c00fbe61c77ae98311f103e9 | [
0.00017617575940676033,
0.00017116616072598845,
0.0001632474159123376,
0.0001720784930512309,
0.0000037238305594655685
] |
{
"id": 2,
"code_window": [
"import {Match, FileMatch, SearchResult} from 'vs/workbench/parts/search/common/searchModel';\n",
"import { TestInstantiationService } from 'vs/test/utils/instantiationTestUtils';\n",
"import {SearchSorter, SearchDataSource} from 'vs/workbench/parts/search/browser/searchResultsView';\n",
"import {IFileMatch, ILineMatch} from 'vs/platform/search/common/search';\n",
"\n",
"function aFileMatch(path: string, searchResult?: SearchResult, ...lineMatches: ILineMatch[]): FileMatch {\n",
"\tlet rawMatch: IFileMatch= {\n",
"\t\tresource: uri.file('C:\\\\' + path),\n",
"\t\tlineMatches: lineMatches\n",
"\t};\n",
"\treturn new FileMatch(null, searchResult, rawMatch, null, null);\n",
"}\n",
"\n",
"suite('Search - Viewlet', () => {\n",
"\tlet instantiation: TestInstantiationService;\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"import { createMockModelService } from 'vs/test/utils/servicesTestUtils';\n",
"import { IModelService } from 'vs/editor/common/services/modelService';\n"
],
"file_path": "src/vs/workbench/parts/search/test/browser/searchViewlet.test.ts",
"type": "replace",
"edit_start_line_idx": 12
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
// Do not edit this file. It is machine generated.
{
"entryAriaLabel": "{0}, selector de archivos de trabajo",
"noResultsFound": "No se encontraron archivos de trabajo coincidentes.",
"noWorkingFiles": "La lista de archivos de trabajo está vacía.",
"workingFilesGroupLabel": "archivos de trabajo"
} | i18n/esn/src/vs/workbench/parts/files/browser/workingFilesPicker.i18n.json | 0 | https://github.com/microsoft/vscode/commit/e12eb3dc06b131a8c00fbe61c77ae98311f103e9 | [
0.00017635643598623574,
0.0001734115940053016,
0.00017046673747245222,
0.0001734115940053016,
0.0000029448492568917572
] |
{
"id": 2,
"code_window": [
"import {Match, FileMatch, SearchResult} from 'vs/workbench/parts/search/common/searchModel';\n",
"import { TestInstantiationService } from 'vs/test/utils/instantiationTestUtils';\n",
"import {SearchSorter, SearchDataSource} from 'vs/workbench/parts/search/browser/searchResultsView';\n",
"import {IFileMatch, ILineMatch} from 'vs/platform/search/common/search';\n",
"\n",
"function aFileMatch(path: string, searchResult?: SearchResult, ...lineMatches: ILineMatch[]): FileMatch {\n",
"\tlet rawMatch: IFileMatch= {\n",
"\t\tresource: uri.file('C:\\\\' + path),\n",
"\t\tlineMatches: lineMatches\n",
"\t};\n",
"\treturn new FileMatch(null, searchResult, rawMatch, null, null);\n",
"}\n",
"\n",
"suite('Search - Viewlet', () => {\n",
"\tlet instantiation: TestInstantiationService;\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"import { createMockModelService } from 'vs/test/utils/servicesTestUtils';\n",
"import { IModelService } from 'vs/editor/common/services/modelService';\n"
],
"file_path": "src/vs/workbench/parts/search/test/browser/searchViewlet.test.ts",
"type": "replace",
"edit_start_line_idx": 12
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
// Do not edit this file. It is machine generated.
{
"focusSideBar": "Перевести фокус на боковую панель",
"viewCategory": "Просмотреть"
} | i18n/rus/src/vs/workbench/browser/parts/sidebar/sidebarPart.i18n.json | 0 | https://github.com/microsoft/vscode/commit/e12eb3dc06b131a8c00fbe61c77ae98311f103e9 | [
0.00017519143875688314,
0.00017519143875688314,
0.00017519143875688314,
0.00017519143875688314,
0
] |
{
"id": 3,
"code_window": [
"\tlet instantiation: TestInstantiationService;\n",
"\n",
"\tsetup(() => {\n",
"\t\tinstantiation = new TestInstantiationService();\n",
"\t});\n",
"\n",
"\ttest('Data Source', function () {\n",
"\t\tlet ds = new SearchDataSource();\n",
"\t\tlet result = instantiation.createInstance(SearchResult, null);\n"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\tinstantiation.stub(IModelService, createMockModelService(instantiation));\n"
],
"file_path": "src/vs/workbench/parts/search/test/browser/searchViewlet.test.ts",
"type": "add",
"edit_start_line_idx": 26
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
'use strict';
import * as assert from 'assert';
import * as sinon from 'sinon';
import { TestInstantiationService } from 'vs/test/utils/instantiationTestUtils';
import { Match, FileMatch, SearchResult, SearchModel } from 'vs/workbench/parts/search/common/searchModel';
import URI from 'vs/base/common/uri';
import {IFileMatch, ILineMatch} from 'vs/platform/search/common/search';
import { ITelemetryService } from 'vs/platform/telemetry/common/telemetry';
import { Range } from 'vs/editor/common/core/range';
suite('SearchResult', () => {
let instantiationService: TestInstantiationService;
setup(() => {
instantiationService= new TestInstantiationService();
instantiationService.stub(ITelemetryService);
});
test('Line Match', function () {
let fileMatch = aFileMatch('folder\\file.txt');
let lineMatch = new Match(fileMatch, 'foo bar', 1, 0, 3);
assert.equal(lineMatch.text(), 'foo bar');
assert.equal(lineMatch.range().startLineNumber, 2);
assert.equal(lineMatch.range().endLineNumber, 2);
assert.equal(lineMatch.range().startColumn, 1);
assert.equal(lineMatch.range().endColumn, 4);
});
test('Line Match - Remove', function () {
let fileMatch = aFileMatch('folder\\file.txt', null, ...[{
preview: 'foo bar',
lineNumber: 1,
offsetAndLengths: [[0, 3]]
}]);
let lineMatch = fileMatch.matches()[0];
fileMatch.remove(lineMatch);
assert.equal(fileMatch.matches().length, 0);
});
test('File Match', function () {
let fileMatch = aFileMatch('folder\\file.txt');
assert.equal(fileMatch.matches(), 0);
assert.equal(fileMatch.resource().toString(), 'file:///c%3A/folder/file.txt');
assert.equal(fileMatch.name(), 'file.txt');
fileMatch = aFileMatch('file.txt');
assert.equal(fileMatch.matches(), 0);
assert.equal(fileMatch.resource().toString(), 'file:///c%3A/file.txt');
assert.equal(fileMatch.name(), 'file.txt');
});
test('Alle Drei Zusammen', function () {
let searchResult = instantiationService.createInstance(SearchResult, null);
let fileMatch = aFileMatch('far\\boo', searchResult);
let lineMatch = new Match(fileMatch, 'foo bar', 1, 0, 3);
assert(lineMatch.parent() === fileMatch);
assert(fileMatch.parent() === searchResult);
});
test('Search Result: Adding a raw match will add a file match with line matches', function () {
let testObject = aSearchResult();
let target= [aRawMatch('file://c:/', aLineMatch('preview 1', 1, [[1, 3], [4, 7]]), aLineMatch('preview 2'))];
testObject.add(target);
assert.equal(3, testObject.count());
let actual= testObject.matches();
assert.equal(1, actual.length);
assert.equal('file://c:/', actual[0].resource().toString());
let actuaMatches= actual[0].matches();
assert.equal(3, actuaMatches.length);
assert.equal('preview 1', actuaMatches[0].text());
assert.ok(new Range(2, 2, 2, 5).equalsRange(actuaMatches[0].range()));
assert.equal('preview 1', actuaMatches[1].text());
assert.ok(new Range(2, 5, 2, 12).equalsRange(actuaMatches[1].range()));
assert.equal('preview 2', actuaMatches[2].text());
assert.ok(new Range(2, 1, 2, 2).equalsRange(actuaMatches[2].range()));
});
test('Search Result: Adding multiple raw matches', function () {
let testObject = aSearchResult();
let target= [aRawMatch('file://c:/1', aLineMatch('preview 1', 1, [[1, 3], [4, 7]])), aRawMatch('file://c:/2', aLineMatch('preview 2'))];
testObject.add(target);
assert.equal(3, testObject.count());
let actual= testObject.matches();
assert.equal(2, actual.length);
assert.equal('file://c:/1', actual[0].resource().toString());
let actuaMatches= actual[0].matches();
assert.equal(2, actuaMatches.length);
assert.equal('preview 1', actuaMatches[0].text());
assert.ok(new Range(2, 2, 2, 5).equalsRange(actuaMatches[0].range()));
assert.equal('preview 1', actuaMatches[1].text());
assert.ok(new Range(2, 5, 2, 12).equalsRange(actuaMatches[1].range()));
actuaMatches= actual[1].matches();
assert.equal(1, actuaMatches.length);
assert.equal('preview 2', actuaMatches[0].text());
assert.ok(new Range(2, 1, 2, 2).equalsRange(actuaMatches[0].range()));
});
test('Search Result: Dispose disposes matches', function () {
let target1= sinon.spy();
let target2= sinon.spy();
let testObject = aSearchResult();
testObject.add([aRawMatch('file://c:/1', aLineMatch('preview 1')), aRawMatch('file://c:/2', aLineMatch('preview 2'))]);
testObject.matches()[0].onDispose(target1);
testObject.matches()[1].onDispose(target2);
testObject.dispose();
assert.ok(testObject.isEmpty());
assert.ok(target1.calledOnce);
assert.ok(target2.calledOnce);
});
test('Search Result: Removing all line matches and adding back will add file back to result', function () {
let testObject = aSearchResult();
testObject.add([aRawMatch('file://c:/1', aLineMatch('preview 1'))]);
let target= testObject.matches()[0];
let matchToRemove= target.matches()[0];
target.remove(matchToRemove);
assert.ok(testObject.isEmpty());
target.add(matchToRemove, true);
assert.equal(1, testObject.fileCount());
assert.equal(target, testObject.matches()[0]);
});
//// ----- utils
//function lineHasDecorations(model: editor.IModel, lineNumber: number, decorations: { start: number; end: number; }[]): void {
// let lineDecorations:typeof decorations = [];
// let decs = model.getLineDecorations(lineNumber);
// for (let i = 0, len = decs.length; i < len; i++) {
// lineDecorations.push({
// start: decs[i].range.startColumn,
// end: decs[i].range.endColumn
// });
// }
// assert.deepEqual(lineDecorations, decorations);
//}
//
//function lineHasNoDecoration(model: editor.IModel, lineNumber: number): void {
// lineHasDecorations(model, lineNumber, []);
//}
//
//function lineHasDecoration(model: editor.IModel, lineNumber: number, start: number, end: number): void {
// lineHasDecorations(model, lineNumber, [{
// start: start,
// end: end
// }]);
//}
//// ----- end utils
//
//test('Model Highlights', function () {
//
// let fileMatch = instantiation.createInstance(FileMatch, null, toUri('folder\\file.txt'));
// fileMatch.add(new Match(fileMatch, 'line2', 1, 0, 2));
// fileMatch.connect();
// lineHasDecoration(oneModel, 2, 1, 3);
//});
//
//test('Dispose', function () {
//
// let fileMatch = instantiation.createInstance(FileMatch, null, toUri('folder\\file.txt'));
// fileMatch.add(new Match(fileMatch, 'line2', 1, 0, 2));
// fileMatch.connect();
// lineHasDecoration(oneModel, 2, 1, 3);
//
// fileMatch.dispose();
// lineHasNoDecoration(oneModel, 2);
//});
function aFileMatch(path: string, searchResult?: SearchResult, ...lineMatches: ILineMatch[]): FileMatch {
let rawMatch: IFileMatch = {
resource: URI.file('C:\\' + path),
lineMatches: lineMatches
};
return new FileMatch(null, searchResult, rawMatch, null, null);
}
function aSearchResult(): SearchResult {
let searchModel = instantiationService.createInstance(SearchModel);
return searchModel.searchResult;
}
function aRawMatch(resource: string, ...lineMatches: ILineMatch[]): IFileMatch {
return { resource: URI.parse(resource), lineMatches };
}
function aLineMatch(preview: string, lineNumber: number = 1, offsetAndLengths: number[][] = [[0, 1]]): ILineMatch {
return { preview, lineNumber, offsetAndLengths };
}
}); | src/vs/workbench/parts/search/test/common/searchResult.test.ts | 1 | https://github.com/microsoft/vscode/commit/e12eb3dc06b131a8c00fbe61c77ae98311f103e9 | [
0.9920400381088257,
0.10201993584632874,
0.0001636452943785116,
0.0001778983569238335,
0.2819911539554596
] |
{
"id": 3,
"code_window": [
"\tlet instantiation: TestInstantiationService;\n",
"\n",
"\tsetup(() => {\n",
"\t\tinstantiation = new TestInstantiationService();\n",
"\t});\n",
"\n",
"\ttest('Data Source', function () {\n",
"\t\tlet ds = new SearchDataSource();\n",
"\t\tlet result = instantiation.createInstance(SearchResult, null);\n"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\tinstantiation.stub(IModelService, createMockModelService(instantiation));\n"
],
"file_path": "src/vs/workbench/parts/search/test/browser/searchViewlet.test.ts",
"type": "add",
"edit_start_line_idx": 26
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
// Do not edit this file. It is machine generated.
{
"no result": "Nessun risultato."
} | i18n/ita/src/vs/editor/contrib/rename/common/rename.i18n.json | 0 | https://github.com/microsoft/vscode/commit/e12eb3dc06b131a8c00fbe61c77ae98311f103e9 | [
0.00017761890194378793,
0.00017761890194378793,
0.00017761890194378793,
0.00017761890194378793,
0
] |
{
"id": 3,
"code_window": [
"\tlet instantiation: TestInstantiationService;\n",
"\n",
"\tsetup(() => {\n",
"\t\tinstantiation = new TestInstantiationService();\n",
"\t});\n",
"\n",
"\ttest('Data Source', function () {\n",
"\t\tlet ds = new SearchDataSource();\n",
"\t\tlet result = instantiation.createInstance(SearchResult, null);\n"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\tinstantiation.stub(IModelService, createMockModelService(instantiation));\n"
],
"file_path": "src/vs/workbench/parts/search/test/browser/searchViewlet.test.ts",
"type": "add",
"edit_start_line_idx": 26
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
// Do not edit this file. It is machine generated.
{
"dotnet": "Используйте сборку dotnet.",
"msbuild": "Используйте msbuild для компиляции проекта.",
"tscConfig": "Используйте компилятор tsc с файлом tsconfig.json.",
"tscFile": "Используйте компилятор tsc в указанном файле.",
"tscOpenFile": "Используйте компилятор tsc в открытом файле.",
"tscWatch": "Используйте компилятор tsc в режиме просмотра."
} | i18n/rus/extensions/tasks/out/tasksMain.i18n.json | 0 | https://github.com/microsoft/vscode/commit/e12eb3dc06b131a8c00fbe61c77ae98311f103e9 | [
0.00017192019731737673,
0.00017111004854086787,
0.000170299899764359,
0.00017111004854086787,
8.101487765088677e-7
] |
{
"id": 3,
"code_window": [
"\tlet instantiation: TestInstantiationService;\n",
"\n",
"\tsetup(() => {\n",
"\t\tinstantiation = new TestInstantiationService();\n",
"\t});\n",
"\n",
"\ttest('Data Source', function () {\n",
"\t\tlet ds = new SearchDataSource();\n",
"\t\tlet result = instantiation.createInstance(SearchResult, null);\n"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\tinstantiation.stub(IModelService, createMockModelService(instantiation));\n"
],
"file_path": "src/vs/workbench/parts/search/test/browser/searchViewlet.test.ts",
"type": "add",
"edit_start_line_idx": 26
} | /*---------------------------------------------------------------------------------------------
* 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/panelpart';
import nls = require('vs/nls');
import {TPromise} from 'vs/base/common/winjs.base';
import {KeyMod, KeyCode, CommonKeybindings} from 'vs/base/common/keyCodes';
import {Action, IAction} from 'vs/base/common/actions';
import {Builder} from 'vs/base/browser/builder';
import dom = require('vs/base/browser/dom');
import {Registry} from 'vs/platform/platform';
import {Scope} from 'vs/workbench/browser/actionBarRegistry';
import {SyncActionDescriptor} from 'vs/platform/actions/common/actions';
import {IWorkbenchActionRegistry, Extensions as WorkbenchExtensions} from 'vs/workbench/common/actionRegistry';
import {IPanel} from 'vs/workbench/common/panel';
import {CompositePart} from 'vs/workbench/browser/parts/compositePart';
import {Panel, PanelRegistry, Extensions as PanelExtensions} from 'vs/workbench/browser/panel';
import {IPanelService} from 'vs/workbench/services/panel/common/panelService';
import {IPartService} from 'vs/workbench/services/part/common/partService';
import {IStorageService} from 'vs/platform/storage/common/storage';
import {IContextMenuService} from 'vs/platform/contextview/browser/contextView';
import {IEventService} from 'vs/platform/event/common/event';
import {IMessageService} from 'vs/platform/message/common/message';
import {ITelemetryService} from 'vs/platform/telemetry/common/telemetry';
import {IKeybindingService} from 'vs/platform/keybinding/common/keybinding';
import {IKeyboardEvent} from 'vs/base/browser/keyboardEvent';
import {IInstantiationService} from 'vs/platform/instantiation/common/instantiation';
export class PanelPart extends CompositePart<Panel> implements IPanelService {
public static activePanelSettingsKey = 'workbench.panelpart.activepanelid';
public _serviceBrand: any;
private blockOpeningPanel: boolean;
constructor(
id: string,
@IMessageService messageService: IMessageService,
@IStorageService storageService: IStorageService,
@IEventService eventService: IEventService,
@ITelemetryService telemetryService: ITelemetryService,
@IContextMenuService contextMenuService: IContextMenuService,
@IPartService partService: IPartService,
@IKeybindingService keybindingService: IKeybindingService,
@IInstantiationService instantiationService: IInstantiationService
) {
super(
messageService,
storageService,
eventService,
telemetryService,
contextMenuService,
partService,
keybindingService,
instantiationService,
(<PanelRegistry>Registry.as(PanelExtensions.Panels)),
PanelPart.activePanelSettingsKey,
'panel',
'panel',
Scope.PANEL,
id
);
}
public create(parent: Builder): void {
super.create(parent);
dom.addStandardDisposableListener(this.getContainer().getHTMLElement(), 'keyup', (e: IKeyboardEvent) => {
if (e.equals(CommonKeybindings.ESCAPE)) {
this.partService.setPanelHidden(true);
e.preventDefault();
}
});
}
public openPanel(id: string, focus?: boolean): TPromise<Panel> {
if (this.blockOpeningPanel) {
return TPromise.as(null); // Workaround against a potential race condition
}
// First check if panel is hidden and show if so
if (this.partService.isPanelHidden()) {
try {
this.blockOpeningPanel = true;
this.partService.setPanelHidden(false);
} finally {
this.blockOpeningPanel = false;
}
}
return this.openComposite(id, focus);
}
protected getActions(): IAction[] {
return [this.instantiationService.createInstance(ClosePanelAction, ClosePanelAction.ID, ClosePanelAction.LABEL)];
}
public getActivePanel(): IPanel {
return this.getActiveComposite();
}
public getLastActivePanelId(): string {
return this.getLastActiveCompositetId();
}
public hideActivePanel(): TPromise<void> {
return this.hideActiveComposite();
}
}
class ClosePanelAction extends Action {
static ID = 'workbench.action.closePanel';
static LABEL = nls.localize('closePanel', "Close");
constructor(
id: string,
name: string,
@IPartService private partService: IPartService
) {
super(id, name, 'hide-panel-action');
}
public run(): TPromise<boolean> {
this.partService.setPanelHidden(true);
return TPromise.as(true);
}
}
class TogglePanelAction extends Action {
static ID = 'workbench.action.togglePanel';
static LABEL = nls.localize('togglePanel', "Toggle Panel Visibility");
constructor(
id: string,
name: string,
@IPartService private partService: IPartService
) {
super(id, name, null);
}
public run(): TPromise<boolean> {
this.partService.setPanelHidden(!this.partService.isPanelHidden());
return TPromise.as(true);
}
}
class FocusPanelAction extends Action {
public static ID = 'workbench.action.focusPanel';
public static LABEL = nls.localize('focusPanel', "Focus into Panel");
constructor(
id: string,
label: string,
@IPanelService private panelService: IPanelService,
@IPartService private partService: IPartService
) {
super(id, label);
}
public run(): TPromise<boolean> {
// Show panel
if (this.partService.isPanelHidden()) {
this.partService.setPanelHidden(false);
}
// Focus into active panel
else {
let panel = this.panelService.getActivePanel();
if (panel) {
panel.focus();
}
}
return TPromise.as(true);
}
}
let actionRegistry = <IWorkbenchActionRegistry>Registry.as(WorkbenchExtensions.WorkbenchActions);
actionRegistry.registerWorkbenchAction(new SyncActionDescriptor(TogglePanelAction, TogglePanelAction.ID, TogglePanelAction.LABEL, { primary: KeyMod.CtrlCmd | KeyCode.KEY_J }), 'View: Toggle Panel Visibility', nls.localize('view', "View"));
actionRegistry.registerWorkbenchAction(new SyncActionDescriptor(FocusPanelAction, FocusPanelAction.ID, FocusPanelAction.LABEL), 'View: Focus into Panel', nls.localize('view', "View"));
| src/vs/workbench/browser/parts/panel/panelPart.ts | 0 | https://github.com/microsoft/vscode/commit/e12eb3dc06b131a8c00fbe61c77ae98311f103e9 | [
0.0004154882626608014,
0.00018890264618676156,
0.00016610480088274926,
0.0001745333574945107,
0.000053889842092758045
] |
{
"id": 4,
"code_window": [
"\t\tassert(s.compare(null, lineMatch2, lineMatch1) > 0);\n",
"\t\tassert(s.compare(null, lineMatch2, lineMatch3) === 0);\n",
"\t});\n",
"});\n"
],
"labels": [
"keep",
"keep",
"add",
"keep"
],
"after_edit": [
"\n",
"\tfunction aFileMatch(path: string, searchResult?: SearchResult, ...lineMatches: ILineMatch[]): FileMatch {\n",
"\t\tlet rawMatch: IFileMatch= {\n",
"\t\t\tresource: uri.file('C:\\\\' + path),\n",
"\t\t\tlineMatches: lineMatches\n",
"\t\t};\n",
"\t\treturn instantiation.createInstance(FileMatch, null, searchResult, rawMatch);\n",
"\t}\n"
],
"file_path": "src/vs/workbench/parts/search/test/browser/searchViewlet.test.ts",
"type": "add",
"edit_start_line_idx": 68
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
'use strict';
import * as assert from 'assert';
import * as sinon from 'sinon';
import { TestInstantiationService } from 'vs/test/utils/instantiationTestUtils';
import { DeferredPPromise } from 'vs/test/utils/promiseTestUtils';
import { PPromise } from 'vs/base/common/winjs.base';
import { nullEvent } from 'vs/base/common/timer';
import { SearchModel } from 'vs/workbench/parts/search/common/searchModel';
import URI from 'vs/base/common/uri';
import {IFileMatch, ILineMatch} from 'vs/platform/search/common/search';
import { ITelemetryService } from 'vs/platform/telemetry/common/telemetry';
import { ISearchService, ISearchComplete, ISearchProgressItem } from 'vs/platform/search/common/search';
import { Range } from 'vs/editor/common/core/range';
suite('SearchModel', () => {
let instantiationService: TestInstantiationService;
let restoreStubs;
setup(() => {
restoreStubs= [];
instantiationService= new TestInstantiationService();
instantiationService.stub(ITelemetryService);
});
teardown(() => {
restoreStubs.forEach(element => {
element.restore();
});
});
test('Search Model: Search adds to results', function () {
let results= [aRawMatch('file://c:/1', aLineMatch('preview 1', 1, [[1, 3], [4, 7]])), aRawMatch('file://c:/2', aLineMatch('preview 2'))];
instantiationService.stub(ISearchService, 'search', PPromise.as({results: results}));
let testObject= instantiationService.createInstance(SearchModel);
testObject.search({contentPattern: {pattern: 'somestring'}, type: 1});
let actual= testObject.searchResult.matches();
assert.equal(2, actual.length);
assert.equal('file://c:/1', actual[0].resource().toString());
let actuaMatches= actual[0].matches();
assert.equal(2, actuaMatches.length);
assert.equal('preview 1', actuaMatches[0].text());
assert.ok(new Range(2, 2, 2, 5).equalsRange(actuaMatches[0].range()));
assert.equal('preview 1', actuaMatches[1].text());
assert.ok(new Range(2, 5, 2, 12).equalsRange(actuaMatches[1].range()));
actuaMatches= actual[1].matches();
assert.equal(1, actuaMatches.length);
assert.equal('preview 2', actuaMatches[0].text());
assert.ok(new Range(2, 1, 2, 2).equalsRange(actuaMatches[0].range()));
});
test('Search Model: Search adds to results during progress', function (done) {
let results= [aRawMatch('file://c:/1', aLineMatch('preview 1', 1, [[1, 3], [4, 7]])), aRawMatch('file://c:/2', aLineMatch('preview 2'))];
let promise= new DeferredPPromise<ISearchComplete, ISearchProgressItem>();
instantiationService.stub(ISearchService, 'search', promise);
let testObject= instantiationService.createInstance(SearchModel);
let result= testObject.search({contentPattern: {pattern: 'somestring'}, type: 1});
promise.progress(results[0]);
promise.progress(results[1]);
promise.complete({results: []});
result.done(() => {
let actual= testObject.searchResult.matches();
assert.equal(2, actual.length);
assert.equal('file://c:/1', actual[0].resource().toString());
let actuaMatches= actual[0].matches();
assert.equal(2, actuaMatches.length);
assert.equal('preview 1', actuaMatches[0].text());
assert.ok(new Range(2, 2, 2, 5).equalsRange(actuaMatches[0].range()));
assert.equal('preview 1', actuaMatches[1].text());
assert.ok(new Range(2, 5, 2, 12).equalsRange(actuaMatches[1].range()));
actuaMatches= actual[1].matches();
assert.equal(1, actuaMatches.length);
assert.equal('preview 2', actuaMatches[0].text());
assert.ok(new Range(2, 1, 2, 2).equalsRange(actuaMatches[0].range()));
done();
});
});
test('Search Model: Search reports telemetry on search completed', function () {
let target= instantiationService.spy(ITelemetryService, 'publicLog');
let results= [aRawMatch('file://c:/1', aLineMatch('preview 1', 1, [[1, 3], [4, 7]])), aRawMatch('file://c:/2', aLineMatch('preview 2'))];
instantiationService.stub(ISearchService, 'search', PPromise.as({results: results}));
let testObject= instantiationService.createInstance(SearchModel);
testObject.search({contentPattern: {pattern: 'somestring'}, type: 1});
assert.ok(target.calledOnce);
assert.deepEqual(['searchResultsShown', {count: 3, fileCount: 2}], target.args[0]);
});
test('Search Model: Search reports timed telemetry on search when progress is not called', function () {
let target2= sinon.spy();
stub(nullEvent, 'stop', target2);
let target1= sinon.stub().returns(nullEvent);
instantiationService.stub(ITelemetryService, 'timedPublicLog', target1);
instantiationService.stub(ISearchService, 'search', PPromise.as({results: []}));
let testObject= instantiationService.createInstance(SearchModel);
testObject.search({contentPattern: {pattern: 'somestring'}, type: 1});
assert.ok(target1.calledTwice);
assert.ok(target1.calledWith('searchResultsFirstRender'));
assert.ok(target1.calledWith('searchResultsFinished'));
assert.ok(target2.calledThrice);
});
test('Search Model: Search reports timed telemetry on search when progress is called', function (done) {
let target2= sinon.spy();
stub(nullEvent, 'stop', target2);
let target1= sinon.stub().returns(nullEvent);
instantiationService.stub(ITelemetryService, 'timedPublicLog', target1);
let promise= new DeferredPPromise<ISearchComplete, ISearchProgressItem>();
instantiationService.stub(ISearchService, 'search', promise);
let testObject= instantiationService.createInstance(SearchModel);
let result= testObject.search({contentPattern: {pattern: 'somestring'}, type: 1});
promise.progress(aRawMatch('file://c:/1', aLineMatch('some preview')));
promise.complete({results: []});
result.done(() => {
assert.ok(target1.calledTwice);
assert.ok(target1.calledWith('searchResultsFirstRender'));
assert.ok(target1.calledWith('searchResultsFinished'));
assert.equal(4, target2.callCount);
done();
});
});
test('Search Model: Search reports timed telemetry on search when error is called', function (done) {
let target2= sinon.spy();
stub(nullEvent, 'stop', target2);
let target1= sinon.stub().returns(nullEvent);
instantiationService.stub(ITelemetryService, 'timedPublicLog', target1);
let promise= new DeferredPPromise<ISearchComplete, ISearchProgressItem>();
instantiationService.stub(ISearchService, 'search', promise);
let testObject= instantiationService.createInstance(SearchModel);
let result= testObject.search({contentPattern: {pattern: 'somestring'}, type: 1});
promise.error('error');
result.done(() => {}, () => {
assert.ok(target1.calledTwice);
assert.ok(target1.calledWith('searchResultsFirstRender'));
assert.ok(target1.calledWith('searchResultsFinished'));
assert.ok(target2.calledThrice);
done();
});
});
test('Search Model: Search reports timed telemetry on search when error is cancelled error', function (done) {
let target2= sinon.spy();
stub(nullEvent, 'stop', target2);
let target1= sinon.stub().returns(nullEvent);
instantiationService.stub(ITelemetryService, 'timedPublicLog', target1);
let promise= new DeferredPPromise<ISearchComplete, ISearchProgressItem>();
instantiationService.stub(ISearchService, 'search', promise);
let testObject= instantiationService.createInstance(SearchModel);
let result= testObject.search({contentPattern: {pattern: 'somestring'}, type: 1});
promise.cancel();
result.done(() => {}, () => {
assert.ok(target1.calledTwice);
assert.ok(target1.calledWith('searchResultsFirstRender'));
assert.ok(target1.calledWith('searchResultsFinished'));
assert.ok(target2.calledThrice);
done();
});
});
test('Search Model: Search results are cleared during search', function () {
let results= [aRawMatch('file://c:/1', aLineMatch('preview 1', 1, [[1, 3], [4, 7]])), aRawMatch('file://c:/2', aLineMatch('preview 2'))];
instantiationService.stub(ISearchService, 'search', PPromise.as({results: results}));
let testObject:SearchModel= instantiationService.createInstance(SearchModel);
testObject.search({contentPattern: {pattern: 'somestring'}, type: 1});
assert.ok(!testObject.searchResult.isEmpty());
instantiationService.stub(ISearchService, 'search', new DeferredPPromise<ISearchComplete, ISearchProgressItem>());
testObject.search({contentPattern: {pattern: 'somestring'}, type: 1});
assert.ok(testObject.searchResult.isEmpty());
});
test('Search Model: Previous search is cancelled when new search is called', function () {
let target= sinon.spy();
instantiationService.stub(ISearchService, 'search', new DeferredPPromise((c, e, p) => {}, target));
let testObject:SearchModel= instantiationService.createInstance(SearchModel);
testObject.search({contentPattern: {pattern: 'somestring'}, type: 1});
instantiationService.stub(ISearchService, 'search', new DeferredPPromise<ISearchComplete, ISearchProgressItem>());
testObject.search({contentPattern: {pattern: 'somestring'}, type: 1});
assert.ok(target.calledOnce);
});
test('Search Model: isReplaceActive return false if no replace text is set', function () {
let testObject:SearchModel= instantiationService.createInstance(SearchModel);
assert.ok(!testObject.isReplaceActive());
});
test('Search Model: isReplaceActive return false if replace text is set to null', function () {
let testObject:SearchModel= instantiationService.createInstance(SearchModel);
testObject.replaceText= null;
assert.ok(!testObject.isReplaceActive());
});
test('Search Model: isReplaceActive return false if replace text is set to undefined', function () {
let testObject:SearchModel= instantiationService.createInstance(SearchModel);
testObject.replaceText= void 0;
assert.ok(!testObject.isReplaceActive());
});
test('Search Model: isReplaceActive return true if replace text is set to empty string', function () {
let testObject:SearchModel= instantiationService.createInstance(SearchModel);
testObject.replaceText= '';
assert.ok(testObject.isReplaceActive());
});
test('Search Model: isReplaceActive return true if replace text is set to non empty string', function () {
let testObject:SearchModel= instantiationService.createInstance(SearchModel);
testObject.replaceText= 'some value';
assert.ok(testObject.isReplaceActive());
});
test('Search Model: hasReplaceText return false if no replace text is set', function () {
let testObject:SearchModel= instantiationService.createInstance(SearchModel);
assert.ok(!testObject.hasReplaceText());
});
test('Search Model: hasReplaceText return false if replace text is set to null', function () {
let testObject:SearchModel= instantiationService.createInstance(SearchModel);
testObject.replaceText= null;
assert.ok(!testObject.hasReplaceText());
});
test('Search Model: hasReplaceText return false if replace text is set to undefined', function () {
let testObject:SearchModel= instantiationService.createInstance(SearchModel);
testObject.replaceText= void 0;
assert.ok(!testObject.hasReplaceText());
});
test('Search Model: hasReplaceText return false if replace text is set to empty string', function () {
let testObject:SearchModel= instantiationService.createInstance(SearchModel);
testObject.replaceText= '';
assert.ok(!testObject.hasReplaceText());
});
test('Search Model: hasReplaceText return true if replace text is set to non empty string', function () {
let testObject:SearchModel= instantiationService.createInstance(SearchModel);
testObject.replaceText= 'some value';
assert.ok(testObject.hasReplaceText());
});
function aRawMatch(resource: string, ...lineMatches: ILineMatch[]): IFileMatch {
return { resource: URI.parse(resource), lineMatches };
}
function aLineMatch(preview: string, lineNumber: number = 1, offsetAndLengths: number[][] = [[0, 1]]): ILineMatch {
return { preview, lineNumber, offsetAndLengths };
}
function stub(arg1, arg2, arg3) : sinon.SinonStub {
const stub= sinon.stub(arg1, arg2, arg3);
restoreStubs.push(stub);
return stub;
}
}); | src/vs/workbench/parts/search/test/common/searchModel.test.ts | 1 | https://github.com/microsoft/vscode/commit/e12eb3dc06b131a8c00fbe61c77ae98311f103e9 | [
0.00024420765112154186,
0.00017682737961877137,
0.0001675119565334171,
0.00017555028898641467,
0.000012517231880337931
] |
{
"id": 4,
"code_window": [
"\t\tassert(s.compare(null, lineMatch2, lineMatch1) > 0);\n",
"\t\tassert(s.compare(null, lineMatch2, lineMatch3) === 0);\n",
"\t});\n",
"});\n"
],
"labels": [
"keep",
"keep",
"add",
"keep"
],
"after_edit": [
"\n",
"\tfunction aFileMatch(path: string, searchResult?: SearchResult, ...lineMatches: ILineMatch[]): FileMatch {\n",
"\t\tlet rawMatch: IFileMatch= {\n",
"\t\t\tresource: uri.file('C:\\\\' + path),\n",
"\t\t\tlineMatches: lineMatches\n",
"\t\t};\n",
"\t\treturn instantiation.createInstance(FileMatch, null, searchResult, rawMatch);\n",
"\t}\n"
],
"file_path": "src/vs/workbench/parts/search/test/browser/searchViewlet.test.ts",
"type": "add",
"edit_start_line_idx": 68
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
.monaco-workbench > .sidebar > .title > .title-actions {
background-color: rgb(243, 243, 243);
}
.vs-dark .monaco-workbench > .sidebar > .title > .title-actions {
background-color: rgb(37, 37, 38);
}
.monaco-workbench > .sidebar > .content {
overflow: hidden;
}
.monaco-workbench.nosidebar > .sidebar {
display: none !important;
visibility: hidden !important;
}
.monaco-workbench .viewlet .collapsible.header .title {
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.monaco-workbench .viewlet .collapsible.header .actions {
width: 0; /* not using display: none for keyboard a11y reasons */
}
.monaco-workbench .viewlet .split-view-view:hover .actions,
.monaco-workbench .viewlet .collapsible.header.focused .actions {
width: initial;
flex: 1;
}
.monaco-workbench .viewlet .collapsible.header .actions .action-label {
width: 28px;
background-size: 16px;
background-position: center center;
background-repeat: no-repeat;
margin-right: 0;
height: 22px;
}
.monaco-workbench .viewlet .collapsible.header .actions .action-label .label {
display: none;
}
.monaco-workbench .viewlet .collapsible.header.collapsed .actions {
display: none;
}
.monaco-workbench .viewlet .collapsible.header .action-label {
margin-right: 0.2em;
background-repeat: no-repeat;
width: 16px;
height: 16px;
}
/* High Contrast Theming */
.hc-black .monaco-workbench > .sidebar.left {
border-right: 1px solid #6FC3DF;
}
.hc-black .monaco-workbench > .sidebar.right {
border-left: 1px solid #6FC3DF;
}
.hc-black .monaco-workbench > .sidebar > .title > .title-actions {
background-color: #000;
} | src/vs/workbench/browser/parts/sidebar/media/sidebarpart.css | 0 | https://github.com/microsoft/vscode/commit/e12eb3dc06b131a8c00fbe61c77ae98311f103e9 | [
0.00017762095376383513,
0.00017294124700129032,
0.00016861593758221716,
0.00017312727868556976,
0.0000028207007289893227
] |
{
"id": 4,
"code_window": [
"\t\tassert(s.compare(null, lineMatch2, lineMatch1) > 0);\n",
"\t\tassert(s.compare(null, lineMatch2, lineMatch3) === 0);\n",
"\t});\n",
"});\n"
],
"labels": [
"keep",
"keep",
"add",
"keep"
],
"after_edit": [
"\n",
"\tfunction aFileMatch(path: string, searchResult?: SearchResult, ...lineMatches: ILineMatch[]): FileMatch {\n",
"\t\tlet rawMatch: IFileMatch= {\n",
"\t\t\tresource: uri.file('C:\\\\' + path),\n",
"\t\t\tlineMatches: lineMatches\n",
"\t\t};\n",
"\t\treturn instantiation.createInstance(FileMatch, null, searchResult, rawMatch);\n",
"\t}\n"
],
"file_path": "src/vs/workbench/parts/search/test/browser/searchViewlet.test.ts",
"type": "add",
"edit_start_line_idx": 68
} | {
"name": "theme-abyss",
"version": "0.1.0",
"publisher": "vscode",
"engines": { "vscode": "*" },
"contributes": {
"themes": [
{
"label": "Abyss",
"uiTheme": "vs-dark",
"path": "./themes/Abyss.tmTheme"
}
]
}
} | extensions/theme-abyss/package.json | 0 | https://github.com/microsoft/vscode/commit/e12eb3dc06b131a8c00fbe61c77ae98311f103e9 | [
0.00017624818428885192,
0.00017567997565492988,
0.00017511178157292306,
0.00017567997565492988,
5.682013579644263e-7
] |
{
"id": 4,
"code_window": [
"\t\tassert(s.compare(null, lineMatch2, lineMatch1) > 0);\n",
"\t\tassert(s.compare(null, lineMatch2, lineMatch3) === 0);\n",
"\t});\n",
"});\n"
],
"labels": [
"keep",
"keep",
"add",
"keep"
],
"after_edit": [
"\n",
"\tfunction aFileMatch(path: string, searchResult?: SearchResult, ...lineMatches: ILineMatch[]): FileMatch {\n",
"\t\tlet rawMatch: IFileMatch= {\n",
"\t\t\tresource: uri.file('C:\\\\' + path),\n",
"\t\t\tlineMatches: lineMatches\n",
"\t\t};\n",
"\t\treturn instantiation.createInstance(FileMatch, null, searchResult, rawMatch);\n",
"\t}\n"
],
"file_path": "src/vs/workbench/parts/search/test/browser/searchViewlet.test.ts",
"type": "add",
"edit_start_line_idx": 68
} | [
{
"c": "#",
"t": "comment.definition.line.number-sign.punctuation.shell",
"r": {
"dark_plus": ".vs-dark.vscode-theme-defaults-themes-dark_plus-json .token.comment rgb(96, 139, 78)",
"light_plus": ".vs.vscode-theme-defaults-themes-light_plus-json .token.comment rgb(0, 128, 0)",
"dark_vs": ".vs-dark.vscode-theme-defaults-themes-dark_vs-json .token.comment rgb(96, 139, 78)",
"light_vs": ".vs.vscode-theme-defaults-themes-light_vs-json .token.comment rgb(0, 128, 0)",
"hc_black": ".hc-black.vscode-theme-defaults-themes-hc_black-json .token.comment rgb(124, 166, 104)"
}
},
{
"c": "!/usr/bin/env bash",
"t": "comment.line.number-sign.shell",
"r": {
"dark_plus": ".vs-dark.vscode-theme-defaults-themes-dark_plus-json .token.comment rgb(96, 139, 78)",
"light_plus": ".vs.vscode-theme-defaults-themes-light_plus-json .token.comment rgb(0, 128, 0)",
"dark_vs": ".vs-dark.vscode-theme-defaults-themes-dark_vs-json .token.comment rgb(96, 139, 78)",
"light_vs": ".vs.vscode-theme-defaults-themes-light_vs-json .token.comment rgb(0, 128, 0)",
"hc_black": ".hc-black.vscode-theme-defaults-themes-hc_black-json .token.comment rgb(124, 166, 104)"
}
},
{
"c": "if",
"t": "control.if-block.keyword.meta.scope.shell",
"r": {
"dark_plus": ".vs-dark.vscode-theme-defaults-themes-dark_plus-json .token.keyword.control rgb(197, 134, 192)",
"light_plus": ".vs.vscode-theme-defaults-themes-light_plus-json .token.keyword.control rgb(175, 0, 219)",
"dark_vs": ".vs-dark.vscode-theme-defaults-themes-dark_vs-json .token.keyword.control rgb(86, 156, 214)",
"light_vs": ".vs.vscode-theme-defaults-themes-light_vs-json .token.keyword.control rgb(0, 0, 255)",
"hc_black": ".hc-black.vscode-theme-defaults-themes-hc_black-json .token.keyword.control rgb(86, 156, 214)"
}
},
{
"c": " ",
"t": "if-block.meta.scope.shell",
"r": {
"dark_plus": ".vs-dark .token rgb(212, 212, 212)",
"light_plus": ".vs .token rgb(0, 0, 0)",
"dark_vs": ".vs-dark .token rgb(212, 212, 212)",
"light_vs": ".vs .token rgb(0, 0, 0)",
"hc_black": ".hc-black .token rgb(255, 255, 255)"
}
},
{
"c": "[[",
"t": "definition.if-block.logical-expression.meta.punctuation.scope.shell",
"r": {
"dark_plus": ".vs-dark .token rgb(212, 212, 212)",
"light_plus": ".vs .token rgb(0, 0, 0)",
"dark_vs": ".vs-dark .token rgb(212, 212, 212)",
"light_vs": ".vs .token rgb(0, 0, 0)",
"hc_black": ".hc-black .token rgb(255, 255, 255)"
}
},
{
"c": " ",
"t": "if-block.logical-expression.meta.scope.shell",
"r": {
"dark_plus": ".vs-dark .token rgb(212, 212, 212)",
"light_plus": ".vs .token rgb(0, 0, 0)",
"dark_vs": ".vs-dark .token rgb(212, 212, 212)",
"light_vs": ".vs .token rgb(0, 0, 0)",
"hc_black": ".hc-black .token rgb(255, 255, 255)"
}
},
{
"c": "\"",
"t": "begin.definition.double.if-block.logical-expression.meta.punctuation.quoted.scope.shell.string",
"r": {
"dark_plus": ".vs-dark.vscode-theme-defaults-themes-dark_plus-json .token.string rgb(206, 145, 120)",
"light_plus": ".vs.vscode-theme-defaults-themes-light_plus-json .token.string rgb(163, 21, 21)",
"dark_vs": ".vs-dark.vscode-theme-defaults-themes-dark_vs-json .token.string rgb(206, 145, 120)",
"light_vs": ".vs.vscode-theme-defaults-themes-light_vs-json .token.string rgb(163, 21, 21)",
"hc_black": ".hc-black.vscode-theme-defaults-themes-hc_black-json .token.string rgb(206, 145, 120)"
}
},
{
"c": "$",
"t": "definition.double.if-block.logical-expression.meta.normal.other.punctuation.quoted.scope.shell.string.variable",
"r": {
"dark_plus": ".vs-dark.vscode-theme-defaults-themes-dark_plus-json .token.variable rgb(156, 220, 254)",
"light_plus": ".vs.vscode-theme-defaults-themes-light_plus-json .token.variable rgb(0, 16, 128)",
"dark_vs": ".vs-dark.vscode-theme-defaults-themes-dark_vs-json .token.string rgb(206, 145, 120)",
"light_vs": ".vs.vscode-theme-defaults-themes-light_vs-json .token.string rgb(163, 21, 21)",
"hc_black": ".hc-black.vscode-theme-defaults-themes-hc_black-json .token.string rgb(206, 145, 120)"
}
},
{
"c": "OSTYPE",
"t": "double.if-block.logical-expression.meta.normal.other.quoted.scope.shell.string.variable",
"r": {
"dark_plus": ".vs-dark.vscode-theme-defaults-themes-dark_plus-json .token.variable rgb(156, 220, 254)",
"light_plus": ".vs.vscode-theme-defaults-themes-light_plus-json .token.variable rgb(0, 16, 128)",
"dark_vs": ".vs-dark.vscode-theme-defaults-themes-dark_vs-json .token.string rgb(206, 145, 120)",
"light_vs": ".vs.vscode-theme-defaults-themes-light_vs-json .token.string rgb(163, 21, 21)",
"hc_black": ".hc-black.vscode-theme-defaults-themes-hc_black-json .token.string rgb(206, 145, 120)"
}
},
{
"c": "\"",
"t": "definition.double.end.if-block.logical-expression.meta.punctuation.quoted.scope.shell.string",
"r": {
"dark_plus": ".vs-dark.vscode-theme-defaults-themes-dark_plus-json .token.string rgb(206, 145, 120)",
"light_plus": ".vs.vscode-theme-defaults-themes-light_plus-json .token.string rgb(163, 21, 21)",
"dark_vs": ".vs-dark.vscode-theme-defaults-themes-dark_vs-json .token.string rgb(206, 145, 120)",
"light_vs": ".vs.vscode-theme-defaults-themes-light_vs-json .token.string rgb(163, 21, 21)",
"hc_black": ".hc-black.vscode-theme-defaults-themes-hc_black-json .token.string rgb(206, 145, 120)"
}
},
{
"c": " ",
"t": "if-block.logical-expression.meta.scope.shell",
"r": {
"dark_plus": ".vs-dark .token rgb(212, 212, 212)",
"light_plus": ".vs .token rgb(0, 0, 0)",
"dark_vs": ".vs-dark .token rgb(212, 212, 212)",
"light_vs": ".vs .token rgb(0, 0, 0)",
"hc_black": ".hc-black .token rgb(255, 255, 255)"
}
},
{
"c": "==",
"t": "if-block.keyword.logical.logical-expression.meta.operator.scope.shell",
"r": {
"dark_plus": ".vs-dark.vscode-theme-defaults-themes-dark_plus-json .token.keyword.operator rgb(212, 212, 212)",
"light_plus": ".vs.vscode-theme-defaults-themes-light_plus-json .token.keyword.operator rgb(0, 0, 0)",
"dark_vs": ".vs-dark.vscode-theme-defaults-themes-dark_vs-json .token.keyword.operator rgb(212, 212, 212)",
"light_vs": ".vs.vscode-theme-defaults-themes-light_vs-json .token.keyword.operator rgb(0, 0, 0)",
"hc_black": ".hc-black.vscode-theme-defaults-themes-hc_black-json .token.keyword.operator rgb(212, 212, 212)"
}
},
{
"c": " ",
"t": "if-block.logical-expression.meta.scope.shell",
"r": {
"dark_plus": ".vs-dark .token rgb(212, 212, 212)",
"light_plus": ".vs .token rgb(0, 0, 0)",
"dark_vs": ".vs-dark .token rgb(212, 212, 212)",
"light_vs": ".vs .token rgb(0, 0, 0)",
"hc_black": ".hc-black .token rgb(255, 255, 255)"
}
},
{
"c": "\"",
"t": "begin.definition.double.if-block.logical-expression.meta.punctuation.quoted.scope.shell.string",
"r": {
"dark_plus": ".vs-dark.vscode-theme-defaults-themes-dark_plus-json .token.string rgb(206, 145, 120)",
"light_plus": ".vs.vscode-theme-defaults-themes-light_plus-json .token.string rgb(163, 21, 21)",
"dark_vs": ".vs-dark.vscode-theme-defaults-themes-dark_vs-json .token.string rgb(206, 145, 120)",
"light_vs": ".vs.vscode-theme-defaults-themes-light_vs-json .token.string rgb(163, 21, 21)",
"hc_black": ".hc-black.vscode-theme-defaults-themes-hc_black-json .token.string rgb(206, 145, 120)"
}
},
{
"c": "darwin",
"t": "double.if-block.logical-expression.meta.quoted.scope.shell.string",
"r": {
"dark_plus": ".vs-dark.vscode-theme-defaults-themes-dark_plus-json .token.string rgb(206, 145, 120)",
"light_plus": ".vs.vscode-theme-defaults-themes-light_plus-json .token.string rgb(163, 21, 21)",
"dark_vs": ".vs-dark.vscode-theme-defaults-themes-dark_vs-json .token.string rgb(206, 145, 120)",
"light_vs": ".vs.vscode-theme-defaults-themes-light_vs-json .token.string rgb(163, 21, 21)",
"hc_black": ".hc-black.vscode-theme-defaults-themes-hc_black-json .token.string rgb(206, 145, 120)"
}
},
{
"c": "\"",
"t": "definition.double.end.if-block.logical-expression.meta.punctuation.quoted.scope.shell.string",
"r": {
"dark_plus": ".vs-dark.vscode-theme-defaults-themes-dark_plus-json .token.string rgb(206, 145, 120)",
"light_plus": ".vs.vscode-theme-defaults-themes-light_plus-json .token.string rgb(163, 21, 21)",
"dark_vs": ".vs-dark.vscode-theme-defaults-themes-dark_vs-json .token.string rgb(206, 145, 120)",
"light_vs": ".vs.vscode-theme-defaults-themes-light_vs-json .token.string rgb(163, 21, 21)",
"hc_black": ".hc-black.vscode-theme-defaults-themes-hc_black-json .token.string rgb(206, 145, 120)"
}
},
{
"c": "*",
"t": "glob.if-block.keyword.logical-expression.meta.operator.scope.shell",
"r": {
"dark_plus": ".vs-dark.vscode-theme-defaults-themes-dark_plus-json .token.keyword.operator rgb(212, 212, 212)",
"light_plus": ".vs.vscode-theme-defaults-themes-light_plus-json .token.keyword.operator rgb(0, 0, 0)",
"dark_vs": ".vs-dark.vscode-theme-defaults-themes-dark_vs-json .token.keyword.operator rgb(212, 212, 212)",
"light_vs": ".vs.vscode-theme-defaults-themes-light_vs-json .token.keyword.operator rgb(0, 0, 0)",
"hc_black": ".hc-black.vscode-theme-defaults-themes-hc_black-json .token.keyword.operator rgb(212, 212, 212)"
}
},
{
"c": " ",
"t": "if-block.logical-expression.meta.scope.shell",
"r": {
"dark_plus": ".vs-dark .token rgb(212, 212, 212)",
"light_plus": ".vs .token rgb(0, 0, 0)",
"dark_vs": ".vs-dark .token rgb(212, 212, 212)",
"light_vs": ".vs .token rgb(0, 0, 0)",
"hc_black": ".hc-black .token rgb(255, 255, 255)"
}
},
{
"c": "]]",
"t": "definition.if-block.logical-expression.meta.punctuation.scope.shell",
"r": {
"dark_plus": ".vs-dark .token rgb(212, 212, 212)",
"light_plus": ".vs .token rgb(0, 0, 0)",
"dark_vs": ".vs-dark .token rgb(212, 212, 212)",
"light_vs": ".vs .token rgb(0, 0, 0)",
"hc_black": ".hc-black .token rgb(255, 255, 255)"
}
},
{
"c": ";",
"t": "if-block.keyword.list.meta.operator.scope.shell",
"r": {
"dark_plus": ".vs-dark.vscode-theme-defaults-themes-dark_plus-json .token.keyword.operator rgb(212, 212, 212)",
"light_plus": ".vs.vscode-theme-defaults-themes-light_plus-json .token.keyword.operator rgb(0, 0, 0)",
"dark_vs": ".vs-dark.vscode-theme-defaults-themes-dark_vs-json .token.keyword.operator rgb(212, 212, 212)",
"light_vs": ".vs.vscode-theme-defaults-themes-light_vs-json .token.keyword.operator rgb(0, 0, 0)",
"hc_black": ".hc-black.vscode-theme-defaults-themes-hc_black-json .token.keyword.operator rgb(212, 212, 212)"
}
},
{
"c": " ",
"t": "if-block.meta.scope.shell",
"r": {
"dark_plus": ".vs-dark .token rgb(212, 212, 212)",
"light_plus": ".vs .token rgb(0, 0, 0)",
"dark_vs": ".vs-dark .token rgb(212, 212, 212)",
"light_vs": ".vs .token rgb(0, 0, 0)",
"hc_black": ".hc-black .token rgb(255, 255, 255)"
}
},
{
"c": "then",
"t": "control.if-block.keyword.meta.scope.shell",
"r": {
"dark_plus": ".vs-dark.vscode-theme-defaults-themes-dark_plus-json .token.keyword.control rgb(197, 134, 192)",
"light_plus": ".vs.vscode-theme-defaults-themes-light_plus-json .token.keyword.control rgb(175, 0, 219)",
"dark_vs": ".vs-dark.vscode-theme-defaults-themes-dark_vs-json .token.keyword.control rgb(86, 156, 214)",
"light_vs": ".vs.vscode-theme-defaults-themes-light_vs-json .token.keyword.control rgb(0, 0, 255)",
"hc_black": ".hc-black.vscode-theme-defaults-themes-hc_black-json .token.keyword.control rgb(86, 156, 214)"
}
},
{
"c": "\t",
"t": "if-block.meta.scope.shell",
"r": {
"dark_plus": ".vs-dark .token rgb(212, 212, 212)",
"light_plus": ".vs .token rgb(0, 0, 0)",
"dark_vs": ".vs-dark .token rgb(212, 212, 212)",
"light_vs": ".vs .token rgb(0, 0, 0)",
"hc_black": ".hc-black .token rgb(255, 255, 255)"
}
},
{
"c": "realpath",
"t": "entity.function.if-block.meta.name.scope.shell",
"r": {
"dark_plus": ".vs-dark.vscode-theme-defaults-themes-dark_plus-json .token.entity.name.function rgb(220, 220, 170)",
"light_plus": ".vs.vscode-theme-defaults-themes-light_plus-json .token.entity.name.function rgb(121, 94, 38)",
"dark_vs": ".vs-dark.vscode-theme-defaults-themes-dark_vs-json .token.entity.name.function rgb(212, 212, 212)",
"light_vs": ".vs .token rgb(0, 0, 0)",
"hc_black": ".hc-black .token rgb(255, 255, 255)"
}
},
{
"c": "()",
"t": "arguments.definition.function.if-block.meta.punctuation.scope.shell",
"r": {
"dark_plus": ".vs-dark .token rgb(212, 212, 212)",
"light_plus": ".vs .token rgb(0, 0, 0)",
"dark_vs": ".vs-dark .token rgb(212, 212, 212)",
"light_vs": ".vs .token rgb(0, 0, 0)",
"hc_black": ".hc-black .token rgb(255, 255, 255)"
}
},
{
"c": " ",
"t": "function.if-block.meta.scope.shell",
"r": {
"dark_plus": ".vs-dark .token rgb(212, 212, 212)",
"light_plus": ".vs .token rgb(0, 0, 0)",
"dark_vs": ".vs-dark .token rgb(212, 212, 212)",
"light_vs": ".vs .token rgb(0, 0, 0)",
"hc_black": ".hc-black .token rgb(255, 255, 255)"
}
},
{
"c": "{",
"t": "definition.function.group.if-block.meta.punctuation.scope.shell",
"r": {
"dark_plus": ".vs-dark .token rgb(212, 212, 212)",
"light_plus": ".vs .token rgb(0, 0, 0)",
"dark_vs": ".vs-dark .token rgb(212, 212, 212)",
"light_vs": ".vs .token rgb(0, 0, 0)",
"hc_black": ".hc-black .token rgb(255, 255, 255)"
}
},
{
"c": " ",
"t": "function.group.if-block.meta.scope.shell",
"r": {
"dark_plus": ".vs-dark .token rgb(212, 212, 212)",
"light_plus": ".vs .token rgb(0, 0, 0)",
"dark_vs": ".vs-dark .token rgb(212, 212, 212)",
"light_vs": ".vs .token rgb(0, 0, 0)",
"hc_black": ".hc-black .token rgb(255, 255, 255)"
}
},
{
"c": "[[",
"t": "definition.function.group.if-block.logical-expression.meta.punctuation.scope.shell",
"r": {
"dark_plus": ".vs-dark .token rgb(212, 212, 212)",
"light_plus": ".vs .token rgb(0, 0, 0)",
"dark_vs": ".vs-dark .token rgb(212, 212, 212)",
"light_vs": ".vs .token rgb(0, 0, 0)",
"hc_black": ".hc-black .token rgb(255, 255, 255)"
}
},
{
"c": " ",
"t": "function.group.if-block.logical-expression.meta.scope.shell",
"r": {
"dark_plus": ".vs-dark .token rgb(212, 212, 212)",
"light_plus": ".vs .token rgb(0, 0, 0)",
"dark_vs": ".vs-dark .token rgb(212, 212, 212)",
"light_vs": ".vs .token rgb(0, 0, 0)",
"hc_black": ".hc-black .token rgb(255, 255, 255)"
}
},
{
"c": "$",
"t": "definition.function.group.if-block.logical-expression.meta.other.positional.punctuation.scope.shell.variable",
"r": {
"dark_plus": ".vs-dark.vscode-theme-defaults-themes-dark_plus-json .token.variable rgb(156, 220, 254)",
"light_plus": ".vs.vscode-theme-defaults-themes-light_plus-json .token.variable rgb(0, 16, 128)",
"dark_vs": ".vs-dark .token rgb(212, 212, 212)",
"light_vs": ".vs .token rgb(0, 0, 0)",
"hc_black": ".hc-black .token rgb(255, 255, 255)"
}
},
{
"c": "1",
"t": "function.group.if-block.logical-expression.meta.other.positional.scope.shell.variable",
"r": {
"dark_plus": ".vs-dark.vscode-theme-defaults-themes-dark_plus-json .token.variable rgb(156, 220, 254)",
"light_plus": ".vs.vscode-theme-defaults-themes-light_plus-json .token.variable rgb(0, 16, 128)",
"dark_vs": ".vs-dark .token rgb(212, 212, 212)",
"light_vs": ".vs .token rgb(0, 0, 0)",
"hc_black": ".hc-black .token rgb(255, 255, 255)"
}
},
{
"c": " ",
"t": "function.group.if-block.logical-expression.meta.scope.shell",
"r": {
"dark_plus": ".vs-dark .token rgb(212, 212, 212)",
"light_plus": ".vs .token rgb(0, 0, 0)",
"dark_vs": ".vs-dark .token rgb(212, 212, 212)",
"light_vs": ".vs .token rgb(0, 0, 0)",
"hc_black": ".hc-black .token rgb(255, 255, 255)"
}
},
{
"c": "=",
"t": "function.group.if-block.keyword.logical.logical-expression.meta.operator.scope.shell",
"r": {
"dark_plus": ".vs-dark.vscode-theme-defaults-themes-dark_plus-json .token.keyword.operator rgb(212, 212, 212)",
"light_plus": ".vs.vscode-theme-defaults-themes-light_plus-json .token.keyword.operator rgb(0, 0, 0)",
"dark_vs": ".vs-dark.vscode-theme-defaults-themes-dark_vs-json .token.keyword.operator rgb(212, 212, 212)",
"light_vs": ".vs.vscode-theme-defaults-themes-light_vs-json .token.keyword.operator rgb(0, 0, 0)",
"hc_black": ".hc-black.vscode-theme-defaults-themes-hc_black-json .token.keyword.operator rgb(212, 212, 212)"
}
},
{
"c": " /",
"t": "function.group.if-block.logical-expression.meta.scope.shell",
"r": {
"dark_plus": ".vs-dark .token rgb(212, 212, 212)",
"light_plus": ".vs .token rgb(0, 0, 0)",
"dark_vs": ".vs-dark .token rgb(212, 212, 212)",
"light_vs": ".vs .token rgb(0, 0, 0)",
"hc_black": ".hc-black .token rgb(255, 255, 255)"
}
},
{
"c": "*",
"t": "function.glob.group.if-block.keyword.logical-expression.meta.operator.scope.shell",
"r": {
"dark_plus": ".vs-dark.vscode-theme-defaults-themes-dark_plus-json .token.keyword.operator rgb(212, 212, 212)",
"light_plus": ".vs.vscode-theme-defaults-themes-light_plus-json .token.keyword.operator rgb(0, 0, 0)",
"dark_vs": ".vs-dark.vscode-theme-defaults-themes-dark_vs-json .token.keyword.operator rgb(212, 212, 212)",
"light_vs": ".vs.vscode-theme-defaults-themes-light_vs-json .token.keyword.operator rgb(0, 0, 0)",
"hc_black": ".hc-black.vscode-theme-defaults-themes-hc_black-json .token.keyword.operator rgb(212, 212, 212)"
}
},
{
"c": " ",
"t": "function.group.if-block.logical-expression.meta.scope.shell",
"r": {
"dark_plus": ".vs-dark .token rgb(212, 212, 212)",
"light_plus": ".vs .token rgb(0, 0, 0)",
"dark_vs": ".vs-dark .token rgb(212, 212, 212)",
"light_vs": ".vs .token rgb(0, 0, 0)",
"hc_black": ".hc-black .token rgb(255, 255, 255)"
}
},
{
"c": "]]",
"t": "definition.function.group.if-block.logical-expression.meta.punctuation.scope.shell",
"r": {
"dark_plus": ".vs-dark .token rgb(212, 212, 212)",
"light_plus": ".vs .token rgb(0, 0, 0)",
"dark_vs": ".vs-dark .token rgb(212, 212, 212)",
"light_vs": ".vs .token rgb(0, 0, 0)",
"hc_black": ".hc-black .token rgb(255, 255, 255)"
}
},
{
"c": " ",
"t": "function.group.if-block.meta.scope.shell",
"r": {
"dark_plus": ".vs-dark .token rgb(212, 212, 212)",
"light_plus": ".vs .token rgb(0, 0, 0)",
"dark_vs": ".vs-dark .token rgb(212, 212, 212)",
"light_vs": ".vs .token rgb(0, 0, 0)",
"hc_black": ".hc-black .token rgb(255, 255, 255)"
}
},
{
"c": "&&",
"t": "function.group.if-block.keyword.list.meta.operator.scope.shell",
"r": {
"dark_plus": ".vs-dark.vscode-theme-defaults-themes-dark_plus-json .token.keyword.operator rgb(212, 212, 212)",
"light_plus": ".vs.vscode-theme-defaults-themes-light_plus-json .token.keyword.operator rgb(0, 0, 0)",
"dark_vs": ".vs-dark.vscode-theme-defaults-themes-dark_vs-json .token.keyword.operator rgb(212, 212, 212)",
"light_vs": ".vs.vscode-theme-defaults-themes-light_vs-json .token.keyword.operator rgb(0, 0, 0)",
"hc_black": ".hc-black.vscode-theme-defaults-themes-hc_black-json .token.keyword.operator rgb(212, 212, 212)"
}
},
{
"c": " ",
"t": "function.group.if-block.meta.scope.shell",
"r": {
"dark_plus": ".vs-dark .token rgb(212, 212, 212)",
"light_plus": ".vs .token rgb(0, 0, 0)",
"dark_vs": ".vs-dark .token rgb(212, 212, 212)",
"light_vs": ".vs .token rgb(0, 0, 0)",
"hc_black": ".hc-black .token rgb(255, 255, 255)"
}
},
{
"c": "echo",
"t": "builtin.function.group.if-block.meta.scope.shell.support",
"r": {
"dark_plus": ".vs-dark .token rgb(212, 212, 212)",
"light_plus": ".vs .token rgb(0, 0, 0)",
"dark_vs": ".vs-dark .token rgb(212, 212, 212)",
"light_vs": ".vs .token rgb(0, 0, 0)",
"hc_black": ".hc-black .token rgb(255, 255, 255)"
}
},
{
"c": " ",
"t": "function.group.if-block.meta.scope.shell",
"r": {
"dark_plus": ".vs-dark .token rgb(212, 212, 212)",
"light_plus": ".vs .token rgb(0, 0, 0)",
"dark_vs": ".vs-dark .token rgb(212, 212, 212)",
"light_vs": ".vs .token rgb(0, 0, 0)",
"hc_black": ".hc-black .token rgb(255, 255, 255)"
}
},
{
"c": "\"",
"t": "begin.definition.double.function.group.if-block.meta.punctuation.quoted.scope.shell.string",
"r": {
"dark_plus": ".vs-dark.vscode-theme-defaults-themes-dark_plus-json .token.string rgb(206, 145, 120)",
"light_plus": ".vs.vscode-theme-defaults-themes-light_plus-json .token.string rgb(163, 21, 21)",
"dark_vs": ".vs-dark.vscode-theme-defaults-themes-dark_vs-json .token.string rgb(206, 145, 120)",
"light_vs": ".vs.vscode-theme-defaults-themes-light_vs-json .token.string rgb(163, 21, 21)",
"hc_black": ".hc-black.vscode-theme-defaults-themes-hc_black-json .token.string rgb(206, 145, 120)"
}
},
{
"c": "$",
"t": "definition.double.function.group.if-block.meta.other.positional.punctuation.quoted.scope.shell.string.variable",
"r": {
"dark_plus": ".vs-dark.vscode-theme-defaults-themes-dark_plus-json .token.variable rgb(156, 220, 254)",
"light_plus": ".vs.vscode-theme-defaults-themes-light_plus-json .token.variable rgb(0, 16, 128)",
"dark_vs": ".vs-dark.vscode-theme-defaults-themes-dark_vs-json .token.string rgb(206, 145, 120)",
"light_vs": ".vs.vscode-theme-defaults-themes-light_vs-json .token.string rgb(163, 21, 21)",
"hc_black": ".hc-black.vscode-theme-defaults-themes-hc_black-json .token.string rgb(206, 145, 120)"
}
},
{
"c": "1",
"t": "double.function.group.if-block.meta.other.positional.quoted.scope.shell.string.variable",
"r": {
"dark_plus": ".vs-dark.vscode-theme-defaults-themes-dark_plus-json .token.variable rgb(156, 220, 254)",
"light_plus": ".vs.vscode-theme-defaults-themes-light_plus-json .token.variable rgb(0, 16, 128)",
"dark_vs": ".vs-dark.vscode-theme-defaults-themes-dark_vs-json .token.string rgb(206, 145, 120)",
"light_vs": ".vs.vscode-theme-defaults-themes-light_vs-json .token.string rgb(163, 21, 21)",
"hc_black": ".hc-black.vscode-theme-defaults-themes-hc_black-json .token.string rgb(206, 145, 120)"
}
},
{
"c": "\"",
"t": "definition.double.end.function.group.if-block.meta.punctuation.quoted.scope.shell.string",
"r": {
"dark_plus": ".vs-dark.vscode-theme-defaults-themes-dark_plus-json .token.string rgb(206, 145, 120)",
"light_plus": ".vs.vscode-theme-defaults-themes-light_plus-json .token.string rgb(163, 21, 21)",
"dark_vs": ".vs-dark.vscode-theme-defaults-themes-dark_vs-json .token.string rgb(206, 145, 120)",
"light_vs": ".vs.vscode-theme-defaults-themes-light_vs-json .token.string rgb(163, 21, 21)",
"hc_black": ".hc-black.vscode-theme-defaults-themes-hc_black-json .token.string rgb(206, 145, 120)"
}
},
{
"c": " ",
"t": "function.group.if-block.meta.scope.shell",
"r": {
"dark_plus": ".vs-dark .token rgb(212, 212, 212)",
"light_plus": ".vs .token rgb(0, 0, 0)",
"dark_vs": ".vs-dark .token rgb(212, 212, 212)",
"light_vs": ".vs .token rgb(0, 0, 0)",
"hc_black": ".hc-black .token rgb(255, 255, 255)"
}
},
{
"c": "||",
"t": "function.group.if-block.keyword.meta.operator.pipe.scope.shell",
"r": {
"dark_plus": ".vs-dark.vscode-theme-defaults-themes-dark_plus-json .token.keyword.operator rgb(212, 212, 212)",
"light_plus": ".vs.vscode-theme-defaults-themes-light_plus-json .token.keyword.operator rgb(0, 0, 0)",
"dark_vs": ".vs-dark.vscode-theme-defaults-themes-dark_vs-json .token.keyword.operator rgb(212, 212, 212)",
"light_vs": ".vs.vscode-theme-defaults-themes-light_vs-json .token.keyword.operator rgb(0, 0, 0)",
"hc_black": ".hc-black.vscode-theme-defaults-themes-hc_black-json .token.keyword.operator rgb(212, 212, 212)"
}
},
{
"c": " ",
"t": "function.group.if-block.meta.scope.shell",
"r": {
"dark_plus": ".vs-dark .token rgb(212, 212, 212)",
"light_plus": ".vs .token rgb(0, 0, 0)",
"dark_vs": ".vs-dark .token rgb(212, 212, 212)",
"light_vs": ".vs .token rgb(0, 0, 0)",
"hc_black": ".hc-black .token rgb(255, 255, 255)"
}
},
{
"c": "echo",
"t": "builtin.function.group.if-block.meta.scope.shell.support",
"r": {
"dark_plus": ".vs-dark .token rgb(212, 212, 212)",
"light_plus": ".vs .token rgb(0, 0, 0)",
"dark_vs": ".vs-dark .token rgb(212, 212, 212)",
"light_vs": ".vs .token rgb(0, 0, 0)",
"hc_black": ".hc-black .token rgb(255, 255, 255)"
}
},
{
"c": " ",
"t": "function.group.if-block.meta.scope.shell",
"r": {
"dark_plus": ".vs-dark .token rgb(212, 212, 212)",
"light_plus": ".vs .token rgb(0, 0, 0)",
"dark_vs": ".vs-dark .token rgb(212, 212, 212)",
"light_vs": ".vs .token rgb(0, 0, 0)",
"hc_black": ".hc-black .token rgb(255, 255, 255)"
}
},
{
"c": "\"",
"t": "begin.definition.double.function.group.if-block.meta.punctuation.quoted.scope.shell.string",
"r": {
"dark_plus": ".vs-dark.vscode-theme-defaults-themes-dark_plus-json .token.string rgb(206, 145, 120)",
"light_plus": ".vs.vscode-theme-defaults-themes-light_plus-json .token.string rgb(163, 21, 21)",
"dark_vs": ".vs-dark.vscode-theme-defaults-themes-dark_vs-json .token.string rgb(206, 145, 120)",
"light_vs": ".vs.vscode-theme-defaults-themes-light_vs-json .token.string rgb(163, 21, 21)",
"hc_black": ".hc-black.vscode-theme-defaults-themes-hc_black-json .token.string rgb(206, 145, 120)"
}
},
{
"c": "$",
"t": "definition.double.function.group.if-block.meta.normal.other.punctuation.quoted.scope.shell.string.variable",
"r": {
"dark_plus": ".vs-dark.vscode-theme-defaults-themes-dark_plus-json .token.variable rgb(156, 220, 254)",
"light_plus": ".vs.vscode-theme-defaults-themes-light_plus-json .token.variable rgb(0, 16, 128)",
"dark_vs": ".vs-dark.vscode-theme-defaults-themes-dark_vs-json .token.string rgb(206, 145, 120)",
"light_vs": ".vs.vscode-theme-defaults-themes-light_vs-json .token.string rgb(163, 21, 21)",
"hc_black": ".hc-black.vscode-theme-defaults-themes-hc_black-json .token.string rgb(206, 145, 120)"
}
},
{
"c": "PWD",
"t": "double.function.group.if-block.meta.normal.other.quoted.scope.shell.string.variable",
"r": {
"dark_plus": ".vs-dark.vscode-theme-defaults-themes-dark_plus-json .token.variable rgb(156, 220, 254)",
"light_plus": ".vs.vscode-theme-defaults-themes-light_plus-json .token.variable rgb(0, 16, 128)",
"dark_vs": ".vs-dark.vscode-theme-defaults-themes-dark_vs-json .token.string rgb(206, 145, 120)",
"light_vs": ".vs.vscode-theme-defaults-themes-light_vs-json .token.string rgb(163, 21, 21)",
"hc_black": ".hc-black.vscode-theme-defaults-themes-hc_black-json .token.string rgb(206, 145, 120)"
}
},
{
"c": "/",
"t": "double.function.group.if-block.meta.quoted.scope.shell.string",
"r": {
"dark_plus": ".vs-dark.vscode-theme-defaults-themes-dark_plus-json .token.string rgb(206, 145, 120)",
"light_plus": ".vs.vscode-theme-defaults-themes-light_plus-json .token.string rgb(163, 21, 21)",
"dark_vs": ".vs-dark.vscode-theme-defaults-themes-dark_vs-json .token.string rgb(206, 145, 120)",
"light_vs": ".vs.vscode-theme-defaults-themes-light_vs-json .token.string rgb(163, 21, 21)",
"hc_black": ".hc-black.vscode-theme-defaults-themes-hc_black-json .token.string rgb(206, 145, 120)"
}
},
{
"c": "${",
"t": "bracket.definition.double.function.group.if-block.meta.other.punctuation.quoted.scope.shell.string.variable",
"r": {
"dark_plus": ".vs-dark.vscode-theme-defaults-themes-dark_plus-json .token.variable rgb(156, 220, 254)",
"light_plus": ".vs.vscode-theme-defaults-themes-light_plus-json .token.variable rgb(0, 16, 128)",
"dark_vs": ".vs-dark.vscode-theme-defaults-themes-dark_vs-json .token.string rgb(206, 145, 120)",
"light_vs": ".vs.vscode-theme-defaults-themes-light_vs-json .token.string rgb(163, 21, 21)",
"hc_black": ".hc-black.vscode-theme-defaults-themes-hc_black-json .token.string rgb(206, 145, 120)"
}
},
{
"c": "1",
"t": "bracket.double.function.group.if-block.meta.other.quoted.scope.shell.string.variable",
"r": {
"dark_plus": ".vs-dark.vscode-theme-defaults-themes-dark_plus-json .token.variable rgb(156, 220, 254)",
"light_plus": ".vs.vscode-theme-defaults-themes-light_plus-json .token.variable rgb(0, 16, 128)",
"dark_vs": ".vs-dark.vscode-theme-defaults-themes-dark_vs-json .token.string rgb(206, 145, 120)",
"light_vs": ".vs.vscode-theme-defaults-themes-light_vs-json .token.string rgb(163, 21, 21)",
"hc_black": ".hc-black.vscode-theme-defaults-themes-hc_black-json .token.string rgb(206, 145, 120)"
}
},
{
"c": "#",
"t": "bracket.double.expansion.function.group.if-block.keyword.meta.operator.other.quoted.scope.shell.string.variable",
"r": {
"dark_plus": ".vs-dark.vscode-theme-defaults-themes-dark_plus-json .token.keyword.operator rgb(212, 212, 212)",
"light_plus": ".vs.vscode-theme-defaults-themes-light_plus-json .token.keyword.operator rgb(0, 0, 0)",
"dark_vs": ".vs-dark.vscode-theme-defaults-themes-dark_vs-json .token.keyword.operator rgb(212, 212, 212)",
"light_vs": ".vs.vscode-theme-defaults-themes-light_vs-json .token.keyword.operator rgb(0, 0, 0)",
"hc_black": ".hc-black.vscode-theme-defaults-themes-hc_black-json .token.keyword.operator rgb(212, 212, 212)"
}
},
{
"c": ".",
"t": "bracket.double.function.group.if-block.meta.other.quoted.scope.shell.string.variable",
"r": {
"dark_plus": ".vs-dark.vscode-theme-defaults-themes-dark_plus-json .token.variable rgb(156, 220, 254)",
"light_plus": ".vs.vscode-theme-defaults-themes-light_plus-json .token.variable rgb(0, 16, 128)",
"dark_vs": ".vs-dark.vscode-theme-defaults-themes-dark_vs-json .token.string rgb(206, 145, 120)",
"light_vs": ".vs.vscode-theme-defaults-themes-light_vs-json .token.string rgb(163, 21, 21)",
"hc_black": ".hc-black.vscode-theme-defaults-themes-hc_black-json .token.string rgb(206, 145, 120)"
}
},
{
"c": "/",
"t": "bracket.double.expansion.function.group.if-block.keyword.meta.operator.other.quoted.scope.shell.string.variable",
"r": {
"dark_plus": ".vs-dark.vscode-theme-defaults-themes-dark_plus-json .token.keyword.operator rgb(212, 212, 212)",
"light_plus": ".vs.vscode-theme-defaults-themes-light_plus-json .token.keyword.operator rgb(0, 0, 0)",
"dark_vs": ".vs-dark.vscode-theme-defaults-themes-dark_vs-json .token.keyword.operator rgb(212, 212, 212)",
"light_vs": ".vs.vscode-theme-defaults-themes-light_vs-json .token.keyword.operator rgb(0, 0, 0)",
"hc_black": ".hc-black.vscode-theme-defaults-themes-hc_black-json .token.keyword.operator rgb(212, 212, 212)"
}
},
{
"c": "}",
"t": "bracket.definition.double.function.group.if-block.meta.other.punctuation.quoted.scope.shell.string.variable",
"r": {
"dark_plus": ".vs-dark.vscode-theme-defaults-themes-dark_plus-json .token.variable rgb(156, 220, 254)",
"light_plus": ".vs.vscode-theme-defaults-themes-light_plus-json .token.variable rgb(0, 16, 128)",
"dark_vs": ".vs-dark.vscode-theme-defaults-themes-dark_vs-json .token.string rgb(206, 145, 120)",
"light_vs": ".vs.vscode-theme-defaults-themes-light_vs-json .token.string rgb(163, 21, 21)",
"hc_black": ".hc-black.vscode-theme-defaults-themes-hc_black-json .token.string rgb(206, 145, 120)"
}
},
{
"c": "\"",
"t": "definition.double.end.function.group.if-block.meta.punctuation.quoted.scope.shell.string",
"r": {
"dark_plus": ".vs-dark.vscode-theme-defaults-themes-dark_plus-json .token.string rgb(206, 145, 120)",
"light_plus": ".vs.vscode-theme-defaults-themes-light_plus-json .token.string rgb(163, 21, 21)",
"dark_vs": ".vs-dark.vscode-theme-defaults-themes-dark_vs-json .token.string rgb(206, 145, 120)",
"light_vs": ".vs.vscode-theme-defaults-themes-light_vs-json .token.string rgb(163, 21, 21)",
"hc_black": ".hc-black.vscode-theme-defaults-themes-hc_black-json .token.string rgb(206, 145, 120)"
}
},
{
"c": ";",
"t": "function.group.if-block.keyword.list.meta.operator.scope.shell",
"r": {
"dark_plus": ".vs-dark.vscode-theme-defaults-themes-dark_plus-json .token.keyword.operator rgb(212, 212, 212)",
"light_plus": ".vs.vscode-theme-defaults-themes-light_plus-json .token.keyword.operator rgb(0, 0, 0)",
"dark_vs": ".vs-dark.vscode-theme-defaults-themes-dark_vs-json .token.keyword.operator rgb(212, 212, 212)",
"light_vs": ".vs.vscode-theme-defaults-themes-light_vs-json .token.keyword.operator rgb(0, 0, 0)",
"hc_black": ".hc-black.vscode-theme-defaults-themes-hc_black-json .token.keyword.operator rgb(212, 212, 212)"
}
},
{
"c": " ",
"t": "function.group.if-block.meta.scope.shell",
"r": {
"dark_plus": ".vs-dark .token rgb(212, 212, 212)",
"light_plus": ".vs .token rgb(0, 0, 0)",
"dark_vs": ".vs-dark .token rgb(212, 212, 212)",
"light_vs": ".vs .token rgb(0, 0, 0)",
"hc_black": ".hc-black .token rgb(255, 255, 255)"
}
},
{
"c": "}",
"t": "definition.function.group.if-block.meta.punctuation.scope.shell",
"r": {
"dark_plus": ".vs-dark .token rgb(212, 212, 212)",
"light_plus": ".vs .token rgb(0, 0, 0)",
"dark_vs": ".vs-dark .token rgb(212, 212, 212)",
"light_vs": ".vs .token rgb(0, 0, 0)",
"hc_black": ".hc-black .token rgb(255, 255, 255)"
}
},
{
"c": "\tROOT=",
"t": "if-block.meta.scope.shell",
"r": {
"dark_plus": ".vs-dark .token rgb(212, 212, 212)",
"light_plus": ".vs .token rgb(0, 0, 0)",
"dark_vs": ".vs-dark .token rgb(212, 212, 212)",
"light_vs": ".vs .token rgb(0, 0, 0)",
"hc_black": ".hc-black .token rgb(255, 255, 255)"
}
},
{
"c": "$(",
"t": "begin.definition.dollar.if-block.interpolated.meta.punctuation.scope.shell.string",
"r": {
"dark_plus": ".vs-dark.vscode-theme-defaults-themes-dark_plus-json .token.string rgb(206, 145, 120)",
"light_plus": ".vs.vscode-theme-defaults-themes-light_plus-json .token.string rgb(163, 21, 21)",
"dark_vs": ".vs-dark.vscode-theme-defaults-themes-dark_vs-json .token.string rgb(206, 145, 120)",
"light_vs": ".vs.vscode-theme-defaults-themes-light_vs-json .token.string rgb(163, 21, 21)",
"hc_black": ".hc-black.vscode-theme-defaults-themes-hc_black-json .token.string rgb(206, 145, 120)"
}
},
{
"c": "dirname ",
"t": "dollar.if-block.interpolated.meta.scope.shell.string",
"r": {
"dark_plus": ".vs-dark.vscode-theme-defaults-themes-dark_plus-json .token.string rgb(206, 145, 120)",
"light_plus": ".vs.vscode-theme-defaults-themes-light_plus-json .token.string rgb(163, 21, 21)",
"dark_vs": ".vs-dark.vscode-theme-defaults-themes-dark_vs-json .token.string rgb(206, 145, 120)",
"light_vs": ".vs.vscode-theme-defaults-themes-light_vs-json .token.string rgb(163, 21, 21)",
"hc_black": ".hc-black.vscode-theme-defaults-themes-hc_black-json .token.string rgb(206, 145, 120)"
}
},
{
"c": "$(",
"t": "begin.definition.dollar.if-block.interpolated.meta.punctuation.scope.shell.string",
"r": {
"dark_plus": ".vs-dark.vscode-theme-defaults-themes-dark_plus-json .token.string rgb(206, 145, 120)",
"light_plus": ".vs.vscode-theme-defaults-themes-light_plus-json .token.string rgb(163, 21, 21)",
"dark_vs": ".vs-dark.vscode-theme-defaults-themes-dark_vs-json .token.string rgb(206, 145, 120)",
"light_vs": ".vs.vscode-theme-defaults-themes-light_vs-json .token.string rgb(163, 21, 21)",
"hc_black": ".hc-black.vscode-theme-defaults-themes-hc_black-json .token.string rgb(206, 145, 120)"
}
},
{
"c": "dirname ",
"t": "dollar.if-block.interpolated.meta.scope.shell.string",
"r": {
"dark_plus": ".vs-dark.vscode-theme-defaults-themes-dark_plus-json .token.string rgb(206, 145, 120)",
"light_plus": ".vs.vscode-theme-defaults-themes-light_plus-json .token.string rgb(163, 21, 21)",
"dark_vs": ".vs-dark.vscode-theme-defaults-themes-dark_vs-json .token.string rgb(206, 145, 120)",
"light_vs": ".vs.vscode-theme-defaults-themes-light_vs-json .token.string rgb(163, 21, 21)",
"hc_black": ".hc-black.vscode-theme-defaults-themes-hc_black-json .token.string rgb(206, 145, 120)"
}
},
{
"c": "$(",
"t": "begin.definition.dollar.if-block.interpolated.meta.punctuation.scope.shell.string",
"r": {
"dark_plus": ".vs-dark.vscode-theme-defaults-themes-dark_plus-json .token.string rgb(206, 145, 120)",
"light_plus": ".vs.vscode-theme-defaults-themes-light_plus-json .token.string rgb(163, 21, 21)",
"dark_vs": ".vs-dark.vscode-theme-defaults-themes-dark_vs-json .token.string rgb(206, 145, 120)",
"light_vs": ".vs.vscode-theme-defaults-themes-light_vs-json .token.string rgb(163, 21, 21)",
"hc_black": ".hc-black.vscode-theme-defaults-themes-hc_black-json .token.string rgb(206, 145, 120)"
}
},
{
"c": "realpath ",
"t": "dollar.if-block.interpolated.meta.scope.shell.string",
"r": {
"dark_plus": ".vs-dark.vscode-theme-defaults-themes-dark_plus-json .token.string rgb(206, 145, 120)",
"light_plus": ".vs.vscode-theme-defaults-themes-light_plus-json .token.string rgb(163, 21, 21)",
"dark_vs": ".vs-dark.vscode-theme-defaults-themes-dark_vs-json .token.string rgb(206, 145, 120)",
"light_vs": ".vs.vscode-theme-defaults-themes-light_vs-json .token.string rgb(163, 21, 21)",
"hc_black": ".hc-black.vscode-theme-defaults-themes-hc_black-json .token.string rgb(206, 145, 120)"
}
},
{
"c": "\"",
"t": "begin.definition.dollar.double.if-block.interpolated.meta.punctuation.quoted.scope.shell.string",
"r": {
"dark_plus": ".vs-dark.vscode-theme-defaults-themes-dark_plus-json .token.string rgb(206, 145, 120)",
"light_plus": ".vs.vscode-theme-defaults-themes-light_plus-json .token.string rgb(163, 21, 21)",
"dark_vs": ".vs-dark.vscode-theme-defaults-themes-dark_vs-json .token.string rgb(206, 145, 120)",
"light_vs": ".vs.vscode-theme-defaults-themes-light_vs-json .token.string rgb(163, 21, 21)",
"hc_black": ".hc-black.vscode-theme-defaults-themes-hc_black-json .token.string rgb(206, 145, 120)"
}
},
{
"c": "$",
"t": "definition.dollar.double.if-block.interpolated.meta.other.punctuation.quoted.scope.shell.special.string.variable",
"r": {
"dark_plus": ".vs-dark.vscode-theme-defaults-themes-dark_plus-json .token.variable rgb(156, 220, 254)",
"light_plus": ".vs.vscode-theme-defaults-themes-light_plus-json .token.variable rgb(0, 16, 128)",
"dark_vs": ".vs-dark.vscode-theme-defaults-themes-dark_vs-json .token.string rgb(206, 145, 120)",
"light_vs": ".vs.vscode-theme-defaults-themes-light_vs-json .token.string rgb(163, 21, 21)",
"hc_black": ".hc-black.vscode-theme-defaults-themes-hc_black-json .token.string rgb(206, 145, 120)"
}
},
{
"c": "0",
"t": "dollar.double.if-block.interpolated.meta.other.quoted.scope.shell.special.string.variable",
"r": {
"dark_plus": ".vs-dark.vscode-theme-defaults-themes-dark_plus-json .token.variable rgb(156, 220, 254)",
"light_plus": ".vs.vscode-theme-defaults-themes-light_plus-json .token.variable rgb(0, 16, 128)",
"dark_vs": ".vs-dark.vscode-theme-defaults-themes-dark_vs-json .token.string rgb(206, 145, 120)",
"light_vs": ".vs.vscode-theme-defaults-themes-light_vs-json .token.string rgb(163, 21, 21)",
"hc_black": ".hc-black.vscode-theme-defaults-themes-hc_black-json .token.string rgb(206, 145, 120)"
}
},
{
"c": "\"",
"t": "definition.dollar.double.end.if-block.interpolated.meta.punctuation.quoted.scope.shell.string",
"r": {
"dark_plus": ".vs-dark.vscode-theme-defaults-themes-dark_plus-json .token.string rgb(206, 145, 120)",
"light_plus": ".vs.vscode-theme-defaults-themes-light_plus-json .token.string rgb(163, 21, 21)",
"dark_vs": ".vs-dark.vscode-theme-defaults-themes-dark_vs-json .token.string rgb(206, 145, 120)",
"light_vs": ".vs.vscode-theme-defaults-themes-light_vs-json .token.string rgb(163, 21, 21)",
"hc_black": ".hc-black.vscode-theme-defaults-themes-hc_black-json .token.string rgb(206, 145, 120)"
}
},
{
"c": ")))",
"t": "definition.dollar.end.if-block.interpolated.meta.punctuation.scope.shell.string",
"r": {
"dark_plus": ".vs-dark.vscode-theme-defaults-themes-dark_plus-json .token.string rgb(206, 145, 120)",
"light_plus": ".vs.vscode-theme-defaults-themes-light_plus-json .token.string rgb(163, 21, 21)",
"dark_vs": ".vs-dark.vscode-theme-defaults-themes-dark_vs-json .token.string rgb(206, 145, 120)",
"light_vs": ".vs.vscode-theme-defaults-themes-light_vs-json .token.string rgb(163, 21, 21)",
"hc_black": ".hc-black.vscode-theme-defaults-themes-hc_black-json .token.string rgb(206, 145, 120)"
}
},
{
"c": "else",
"t": "control.if-block.keyword.meta.scope.shell",
"r": {
"dark_plus": ".vs-dark.vscode-theme-defaults-themes-dark_plus-json .token.keyword.control rgb(197, 134, 192)",
"light_plus": ".vs.vscode-theme-defaults-themes-light_plus-json .token.keyword.control rgb(175, 0, 219)",
"dark_vs": ".vs-dark.vscode-theme-defaults-themes-dark_vs-json .token.keyword.control rgb(86, 156, 214)",
"light_vs": ".vs.vscode-theme-defaults-themes-light_vs-json .token.keyword.control rgb(0, 0, 255)",
"hc_black": ".hc-black.vscode-theme-defaults-themes-hc_black-json .token.keyword.control rgb(86, 156, 214)"
}
},
{
"c": "\tROOT=",
"t": "if-block.meta.scope.shell",
"r": {
"dark_plus": ".vs-dark .token rgb(212, 212, 212)",
"light_plus": ".vs .token rgb(0, 0, 0)",
"dark_vs": ".vs-dark .token rgb(212, 212, 212)",
"light_vs": ".vs .token rgb(0, 0, 0)",
"hc_black": ".hc-black .token rgb(255, 255, 255)"
}
},
{
"c": "$(",
"t": "begin.definition.dollar.if-block.interpolated.meta.punctuation.scope.shell.string",
"r": {
"dark_plus": ".vs-dark.vscode-theme-defaults-themes-dark_plus-json .token.string rgb(206, 145, 120)",
"light_plus": ".vs.vscode-theme-defaults-themes-light_plus-json .token.string rgb(163, 21, 21)",
"dark_vs": ".vs-dark.vscode-theme-defaults-themes-dark_vs-json .token.string rgb(206, 145, 120)",
"light_vs": ".vs.vscode-theme-defaults-themes-light_vs-json .token.string rgb(163, 21, 21)",
"hc_black": ".hc-black.vscode-theme-defaults-themes-hc_black-json .token.string rgb(206, 145, 120)"
}
},
{
"c": "dirname ",
"t": "dollar.if-block.interpolated.meta.scope.shell.string",
"r": {
"dark_plus": ".vs-dark.vscode-theme-defaults-themes-dark_plus-json .token.string rgb(206, 145, 120)",
"light_plus": ".vs.vscode-theme-defaults-themes-light_plus-json .token.string rgb(163, 21, 21)",
"dark_vs": ".vs-dark.vscode-theme-defaults-themes-dark_vs-json .token.string rgb(206, 145, 120)",
"light_vs": ".vs.vscode-theme-defaults-themes-light_vs-json .token.string rgb(163, 21, 21)",
"hc_black": ".hc-black.vscode-theme-defaults-themes-hc_black-json .token.string rgb(206, 145, 120)"
}
},
{
"c": "$(",
"t": "begin.definition.dollar.if-block.interpolated.meta.punctuation.scope.shell.string",
"r": {
"dark_plus": ".vs-dark.vscode-theme-defaults-themes-dark_plus-json .token.string rgb(206, 145, 120)",
"light_plus": ".vs.vscode-theme-defaults-themes-light_plus-json .token.string rgb(163, 21, 21)",
"dark_vs": ".vs-dark.vscode-theme-defaults-themes-dark_vs-json .token.string rgb(206, 145, 120)",
"light_vs": ".vs.vscode-theme-defaults-themes-light_vs-json .token.string rgb(163, 21, 21)",
"hc_black": ".hc-black.vscode-theme-defaults-themes-hc_black-json .token.string rgb(206, 145, 120)"
}
},
{
"c": "dirname ",
"t": "dollar.if-block.interpolated.meta.scope.shell.string",
"r": {
"dark_plus": ".vs-dark.vscode-theme-defaults-themes-dark_plus-json .token.string rgb(206, 145, 120)",
"light_plus": ".vs.vscode-theme-defaults-themes-light_plus-json .token.string rgb(163, 21, 21)",
"dark_vs": ".vs-dark.vscode-theme-defaults-themes-dark_vs-json .token.string rgb(206, 145, 120)",
"light_vs": ".vs.vscode-theme-defaults-themes-light_vs-json .token.string rgb(163, 21, 21)",
"hc_black": ".hc-black.vscode-theme-defaults-themes-hc_black-json .token.string rgb(206, 145, 120)"
}
},
{
"c": "$(",
"t": "begin.definition.dollar.if-block.interpolated.meta.punctuation.scope.shell.string",
"r": {
"dark_plus": ".vs-dark.vscode-theme-defaults-themes-dark_plus-json .token.string rgb(206, 145, 120)",
"light_plus": ".vs.vscode-theme-defaults-themes-light_plus-json .token.string rgb(163, 21, 21)",
"dark_vs": ".vs-dark.vscode-theme-defaults-themes-dark_vs-json .token.string rgb(206, 145, 120)",
"light_vs": ".vs.vscode-theme-defaults-themes-light_vs-json .token.string rgb(163, 21, 21)",
"hc_black": ".hc-black.vscode-theme-defaults-themes-hc_black-json .token.string rgb(206, 145, 120)"
}
},
{
"c": "readlink -f ",
"t": "dollar.if-block.interpolated.meta.scope.shell.string",
"r": {
"dark_plus": ".vs-dark.vscode-theme-defaults-themes-dark_plus-json .token.string rgb(206, 145, 120)",
"light_plus": ".vs.vscode-theme-defaults-themes-light_plus-json .token.string rgb(163, 21, 21)",
"dark_vs": ".vs-dark.vscode-theme-defaults-themes-dark_vs-json .token.string rgb(206, 145, 120)",
"light_vs": ".vs.vscode-theme-defaults-themes-light_vs-json .token.string rgb(163, 21, 21)",
"hc_black": ".hc-black.vscode-theme-defaults-themes-hc_black-json .token.string rgb(206, 145, 120)"
}
},
{
"c": "$",
"t": "definition.dollar.if-block.interpolated.meta.other.punctuation.scope.shell.special.string.variable",
"r": {
"dark_plus": ".vs-dark.vscode-theme-defaults-themes-dark_plus-json .token.variable rgb(156, 220, 254)",
"light_plus": ".vs.vscode-theme-defaults-themes-light_plus-json .token.variable rgb(0, 16, 128)",
"dark_vs": ".vs-dark.vscode-theme-defaults-themes-dark_vs-json .token.string rgb(206, 145, 120)",
"light_vs": ".vs.vscode-theme-defaults-themes-light_vs-json .token.string rgb(163, 21, 21)",
"hc_black": ".hc-black.vscode-theme-defaults-themes-hc_black-json .token.string rgb(206, 145, 120)"
}
},
{
"c": "0",
"t": "dollar.if-block.interpolated.meta.other.scope.shell.special.string.variable",
"r": {
"dark_plus": ".vs-dark.vscode-theme-defaults-themes-dark_plus-json .token.variable rgb(156, 220, 254)",
"light_plus": ".vs.vscode-theme-defaults-themes-light_plus-json .token.variable rgb(0, 16, 128)",
"dark_vs": ".vs-dark.vscode-theme-defaults-themes-dark_vs-json .token.string rgb(206, 145, 120)",
"light_vs": ".vs.vscode-theme-defaults-themes-light_vs-json .token.string rgb(163, 21, 21)",
"hc_black": ".hc-black.vscode-theme-defaults-themes-hc_black-json .token.string rgb(206, 145, 120)"
}
},
{
"c": ")))",
"t": "definition.dollar.end.if-block.interpolated.meta.punctuation.scope.shell.string",
"r": {
"dark_plus": ".vs-dark.vscode-theme-defaults-themes-dark_plus-json .token.string rgb(206, 145, 120)",
"light_plus": ".vs.vscode-theme-defaults-themes-light_plus-json .token.string rgb(163, 21, 21)",
"dark_vs": ".vs-dark.vscode-theme-defaults-themes-dark_vs-json .token.string rgb(206, 145, 120)",
"light_vs": ".vs.vscode-theme-defaults-themes-light_vs-json .token.string rgb(163, 21, 21)",
"hc_black": ".hc-black.vscode-theme-defaults-themes-hc_black-json .token.string rgb(206, 145, 120)"
}
},
{
"c": "fi",
"t": "control.if-block.keyword.meta.scope.shell",
"r": {
"dark_plus": ".vs-dark.vscode-theme-defaults-themes-dark_plus-json .token.keyword.control rgb(197, 134, 192)",
"light_plus": ".vs.vscode-theme-defaults-themes-light_plus-json .token.keyword.control rgb(175, 0, 219)",
"dark_vs": ".vs-dark.vscode-theme-defaults-themes-dark_vs-json .token.keyword.control rgb(86, 156, 214)",
"light_vs": ".vs.vscode-theme-defaults-themes-light_vs-json .token.keyword.control rgb(0, 0, 255)",
"hc_black": ".hc-black.vscode-theme-defaults-themes-hc_black-json .token.keyword.control rgb(86, 156, 214)"
}
},
{
"c": "function",
"t": "function.meta.shell.storage.type",
"r": {
"dark_plus": ".vs-dark.vscode-theme-defaults-themes-dark_plus-json .token.storage.type rgb(86, 156, 214)",
"light_plus": ".vs.vscode-theme-defaults-themes-light_plus-json .token.storage.type rgb(0, 0, 255)",
"dark_vs": ".vs-dark.vscode-theme-defaults-themes-dark_vs-json .token.storage.type rgb(86, 156, 214)",
"light_vs": ".vs.vscode-theme-defaults-themes-light_vs-json .token.storage.type rgb(0, 0, 255)",
"hc_black": ".hc-black.vscode-theme-defaults-themes-hc_black-json .token.storage.type rgb(86, 156, 214)"
}
},
{
"c": " ",
"t": "function.meta.shell",
"r": {
"dark_plus": ".vs-dark .token rgb(212, 212, 212)",
"light_plus": ".vs .token rgb(0, 0, 0)",
"dark_vs": ".vs-dark .token rgb(212, 212, 212)",
"light_vs": ".vs .token rgb(0, 0, 0)",
"hc_black": ".hc-black .token rgb(255, 255, 255)"
}
},
{
"c": "code()",
"t": "entity.function.meta.name.shell",
"r": {
"dark_plus": ".vs-dark.vscode-theme-defaults-themes-dark_plus-json .token.entity.name.function rgb(220, 220, 170)",
"light_plus": ".vs.vscode-theme-defaults-themes-light_plus-json .token.entity.name.function rgb(121, 94, 38)",
"dark_vs": ".vs-dark.vscode-theme-defaults-themes-dark_vs-json .token.entity.name.function rgb(212, 212, 212)",
"light_vs": ".vs .token rgb(0, 0, 0)",
"hc_black": ".hc-black .token rgb(255, 255, 255)"
}
},
{
"c": " ",
"t": "function.meta.shell",
"r": {
"dark_plus": ".vs-dark .token rgb(212, 212, 212)",
"light_plus": ".vs .token rgb(0, 0, 0)",
"dark_vs": ".vs-dark .token rgb(212, 212, 212)",
"light_vs": ".vs .token rgb(0, 0, 0)",
"hc_black": ".hc-black .token rgb(255, 255, 255)"
}
},
{
"c": "{",
"t": "definition.function.group.meta.punctuation.scope.shell",
"r": {
"dark_plus": ".vs-dark .token rgb(212, 212, 212)",
"light_plus": ".vs .token rgb(0, 0, 0)",
"dark_vs": ".vs-dark .token rgb(212, 212, 212)",
"light_vs": ".vs .token rgb(0, 0, 0)",
"hc_black": ".hc-black .token rgb(255, 255, 255)"
}
},
{
"c": "\t",
"t": "function.group.meta.scope.shell",
"r": {
"dark_plus": ".vs-dark .token rgb(212, 212, 212)",
"light_plus": ".vs .token rgb(0, 0, 0)",
"dark_vs": ".vs-dark .token rgb(212, 212, 212)",
"light_vs": ".vs .token rgb(0, 0, 0)",
"hc_black": ".hc-black .token rgb(255, 255, 255)"
}
},
{
"c": "cd",
"t": "builtin.function.group.meta.scope.shell.support",
"r": {
"dark_plus": ".vs-dark .token rgb(212, 212, 212)",
"light_plus": ".vs .token rgb(0, 0, 0)",
"dark_vs": ".vs-dark .token rgb(212, 212, 212)",
"light_vs": ".vs .token rgb(0, 0, 0)",
"hc_black": ".hc-black .token rgb(255, 255, 255)"
}
},
{
"c": " ",
"t": "function.group.meta.scope.shell",
"r": {
"dark_plus": ".vs-dark .token rgb(212, 212, 212)",
"light_plus": ".vs .token rgb(0, 0, 0)",
"dark_vs": ".vs-dark .token rgb(212, 212, 212)",
"light_vs": ".vs .token rgb(0, 0, 0)",
"hc_black": ".hc-black .token rgb(255, 255, 255)"
}
},
{
"c": "$",
"t": "definition.function.group.meta.normal.other.punctuation.scope.shell.variable",
"r": {
"dark_plus": ".vs-dark.vscode-theme-defaults-themes-dark_plus-json .token.variable rgb(156, 220, 254)",
"light_plus": ".vs.vscode-theme-defaults-themes-light_plus-json .token.variable rgb(0, 16, 128)",
"dark_vs": ".vs-dark .token rgb(212, 212, 212)",
"light_vs": ".vs .token rgb(0, 0, 0)",
"hc_black": ".hc-black .token rgb(255, 255, 255)"
}
},
{
"c": "ROOT",
"t": "function.group.meta.normal.other.scope.shell.variable",
"r": {
"dark_plus": ".vs-dark.vscode-theme-defaults-themes-dark_plus-json .token.variable rgb(156, 220, 254)",
"light_plus": ".vs.vscode-theme-defaults-themes-light_plus-json .token.variable rgb(0, 16, 128)",
"dark_vs": ".vs-dark .token rgb(212, 212, 212)",
"light_vs": ".vs .token rgb(0, 0, 0)",
"hc_black": ".hc-black .token rgb(255, 255, 255)"
}
},
{
"c": "\t",
"t": "comment.function.group.leading.meta.punctuation.scope.shell.whitespace",
"r": {
"dark_plus": ".vs-dark.vscode-theme-defaults-themes-dark_plus-json .token.comment rgba(227, 228, 226, 0.156863)",
"light_plus": ".vs.vscode-theme-defaults-themes-light_plus-json .token.comment rgba(51, 51, 51, 0.2)",
"dark_vs": ".vs-dark.vscode-theme-defaults-themes-dark_vs-json .token.comment rgba(227, 228, 226, 0.156863)",
"light_vs": ".vs.vscode-theme-defaults-themes-light_vs-json .token.comment rgba(51, 51, 51, 0.2)",
"hc_black": ".hc-black.vscode-theme-defaults-themes-hc_black-json .token.comment rgba(227, 228, 226, 0.156863)"
}
},
{
"c": "#",
"t": "comment.definition.function.group.line.meta.number-sign.punctuation.scope.shell",
"r": {
"dark_plus": ".vs-dark.vscode-theme-defaults-themes-dark_plus-json .token.comment rgb(96, 139, 78)",
"light_plus": ".vs.vscode-theme-defaults-themes-light_plus-json .token.comment rgb(0, 128, 0)",
"dark_vs": ".vs-dark.vscode-theme-defaults-themes-dark_vs-json .token.comment rgb(96, 139, 78)",
"light_vs": ".vs.vscode-theme-defaults-themes-light_vs-json .token.comment rgb(0, 128, 0)",
"hc_black": ".hc-black.vscode-theme-defaults-themes-hc_black-json .token.comment rgb(124, 166, 104)"
}
},
{
"c": " Node modules",
"t": "comment.function.group.line.meta.number-sign.scope.shell",
"r": {
"dark_plus": ".vs-dark.vscode-theme-defaults-themes-dark_plus-json .token.comment rgb(96, 139, 78)",
"light_plus": ".vs.vscode-theme-defaults-themes-light_plus-json .token.comment rgb(0, 128, 0)",
"dark_vs": ".vs-dark.vscode-theme-defaults-themes-dark_vs-json .token.comment rgb(96, 139, 78)",
"light_vs": ".vs.vscode-theme-defaults-themes-light_vs-json .token.comment rgb(0, 128, 0)",
"hc_black": ".hc-black.vscode-theme-defaults-themes-hc_black-json .token.comment rgb(124, 166, 104)"
}
},
{
"c": "\t",
"t": "function.group.meta.scope.shell",
"r": {
"dark_plus": ".vs-dark .token rgb(212, 212, 212)",
"light_plus": ".vs .token rgb(0, 0, 0)",
"dark_vs": ".vs-dark .token rgb(212, 212, 212)",
"light_vs": ".vs .token rgb(0, 0, 0)",
"hc_black": ".hc-black .token rgb(255, 255, 255)"
}
},
{
"c": "test",
"t": "builtin.function.group.meta.scope.shell.support",
"r": {
"dark_plus": ".vs-dark .token rgb(212, 212, 212)",
"light_plus": ".vs .token rgb(0, 0, 0)",
"dark_vs": ".vs-dark .token rgb(212, 212, 212)",
"light_vs": ".vs .token rgb(0, 0, 0)",
"hc_black": ".hc-black .token rgb(255, 255, 255)"
}
},
{
"c": " -d node_modules ",
"t": "function.group.meta.scope.shell",
"r": {
"dark_plus": ".vs-dark .token rgb(212, 212, 212)",
"light_plus": ".vs .token rgb(0, 0, 0)",
"dark_vs": ".vs-dark .token rgb(212, 212, 212)",
"light_vs": ".vs .token rgb(0, 0, 0)",
"hc_black": ".hc-black .token rgb(255, 255, 255)"
}
},
{
"c": "||",
"t": "function.group.keyword.meta.operator.pipe.scope.shell",
"r": {
"dark_plus": ".vs-dark.vscode-theme-defaults-themes-dark_plus-json .token.keyword.operator rgb(212, 212, 212)",
"light_plus": ".vs.vscode-theme-defaults-themes-light_plus-json .token.keyword.operator rgb(0, 0, 0)",
"dark_vs": ".vs-dark.vscode-theme-defaults-themes-dark_vs-json .token.keyword.operator rgb(212, 212, 212)",
"light_vs": ".vs.vscode-theme-defaults-themes-light_vs-json .token.keyword.operator rgb(0, 0, 0)",
"hc_black": ".hc-black.vscode-theme-defaults-themes-hc_black-json .token.keyword.operator rgb(212, 212, 212)"
}
},
{
"c": " ./scripts/npm.sh install",
"t": "function.group.meta.scope.shell",
"r": {
"dark_plus": ".vs-dark .token rgb(212, 212, 212)",
"light_plus": ".vs .token rgb(0, 0, 0)",
"dark_vs": ".vs-dark .token rgb(212, 212, 212)",
"light_vs": ".vs .token rgb(0, 0, 0)",
"hc_black": ".hc-black .token rgb(255, 255, 255)"
}
},
{
"c": "\t",
"t": "comment.function.group.leading.meta.punctuation.scope.shell.whitespace",
"r": {
"dark_plus": ".vs-dark.vscode-theme-defaults-themes-dark_plus-json .token.comment rgba(227, 228, 226, 0.156863)",
"light_plus": ".vs.vscode-theme-defaults-themes-light_plus-json .token.comment rgba(51, 51, 51, 0.2)",
"dark_vs": ".vs-dark.vscode-theme-defaults-themes-dark_vs-json .token.comment rgba(227, 228, 226, 0.156863)",
"light_vs": ".vs.vscode-theme-defaults-themes-light_vs-json .token.comment rgba(51, 51, 51, 0.2)",
"hc_black": ".hc-black.vscode-theme-defaults-themes-hc_black-json .token.comment rgba(227, 228, 226, 0.156863)"
}
},
{
"c": "#",
"t": "comment.definition.function.group.line.meta.number-sign.punctuation.scope.shell",
"r": {
"dark_plus": ".vs-dark.vscode-theme-defaults-themes-dark_plus-json .token.comment rgb(96, 139, 78)",
"light_plus": ".vs.vscode-theme-defaults-themes-light_plus-json .token.comment rgb(0, 128, 0)",
"dark_vs": ".vs-dark.vscode-theme-defaults-themes-dark_vs-json .token.comment rgb(96, 139, 78)",
"light_vs": ".vs.vscode-theme-defaults-themes-light_vs-json .token.comment rgb(0, 128, 0)",
"hc_black": ".hc-black.vscode-theme-defaults-themes-hc_black-json .token.comment rgb(124, 166, 104)"
}
},
{
"c": " Configuration",
"t": "comment.function.group.line.meta.number-sign.scope.shell",
"r": {
"dark_plus": ".vs-dark.vscode-theme-defaults-themes-dark_plus-json .token.comment rgb(96, 139, 78)",
"light_plus": ".vs.vscode-theme-defaults-themes-light_plus-json .token.comment rgb(0, 128, 0)",
"dark_vs": ".vs-dark.vscode-theme-defaults-themes-dark_vs-json .token.comment rgb(96, 139, 78)",
"light_vs": ".vs.vscode-theme-defaults-themes-light_vs-json .token.comment rgb(0, 128, 0)",
"hc_black": ".hc-black.vscode-theme-defaults-themes-hc_black-json .token.comment rgb(124, 166, 104)"
}
},
{
"c": "\t",
"t": "function.group.meta.scope.shell",
"r": {
"dark_plus": ".vs-dark .token rgb(212, 212, 212)",
"light_plus": ".vs .token rgb(0, 0, 0)",
"dark_vs": ".vs-dark .token rgb(212, 212, 212)",
"light_vs": ".vs .token rgb(0, 0, 0)",
"hc_black": ".hc-black .token rgb(255, 255, 255)"
}
},
{
"c": "export",
"t": "function.group.meta.modifier.scope.shell.storage",
"r": {
"dark_plus": ".vs-dark.vscode-theme-defaults-themes-dark_plus-json .token.storage.modifier rgb(86, 156, 214)",
"light_plus": ".vs.vscode-theme-defaults-themes-light_plus-json .token.storage.modifier rgb(0, 0, 255)",
"dark_vs": ".vs-dark.vscode-theme-defaults-themes-dark_vs-json .token.storage.modifier rgb(86, 156, 214)",
"light_vs": ".vs.vscode-theme-defaults-themes-light_vs-json .token.storage.modifier rgb(0, 0, 255)",
"hc_black": ".hc-black.vscode-theme-defaults-themes-hc_black-json .token.storage.modifier rgb(86, 156, 214)"
}
},
{
"c": " NODE_ENV=development",
"t": "function.group.meta.scope.shell",
"r": {
"dark_plus": ".vs-dark .token rgb(212, 212, 212)",
"light_plus": ".vs .token rgb(0, 0, 0)",
"dark_vs": ".vs-dark .token rgb(212, 212, 212)",
"light_vs": ".vs .token rgb(0, 0, 0)",
"hc_black": ".hc-black .token rgb(255, 255, 255)"
}
},
{
"c": "\t",
"t": "comment.function.group.leading.meta.punctuation.scope.shell.whitespace",
"r": {
"dark_plus": ".vs-dark.vscode-theme-defaults-themes-dark_plus-json .token.comment rgba(227, 228, 226, 0.156863)",
"light_plus": ".vs.vscode-theme-defaults-themes-light_plus-json .token.comment rgba(51, 51, 51, 0.2)",
"dark_vs": ".vs-dark.vscode-theme-defaults-themes-dark_vs-json .token.comment rgba(227, 228, 226, 0.156863)",
"light_vs": ".vs.vscode-theme-defaults-themes-light_vs-json .token.comment rgba(51, 51, 51, 0.2)",
"hc_black": ".hc-black.vscode-theme-defaults-themes-hc_black-json .token.comment rgba(227, 228, 226, 0.156863)"
}
},
{
"c": "#",
"t": "comment.definition.function.group.line.meta.number-sign.punctuation.scope.shell",
"r": {
"dark_plus": ".vs-dark.vscode-theme-defaults-themes-dark_plus-json .token.comment rgb(96, 139, 78)",
"light_plus": ".vs.vscode-theme-defaults-themes-light_plus-json .token.comment rgb(0, 128, 0)",
"dark_vs": ".vs-dark.vscode-theme-defaults-themes-dark_vs-json .token.comment rgb(96, 139, 78)",
"light_vs": ".vs.vscode-theme-defaults-themes-light_vs-json .token.comment rgb(0, 128, 0)",
"hc_black": ".hc-black.vscode-theme-defaults-themes-hc_black-json .token.comment rgb(124, 166, 104)"
}
},
{
"c": " Launch Code",
"t": "comment.function.group.line.meta.number-sign.scope.shell",
"r": {
"dark_plus": ".vs-dark.vscode-theme-defaults-themes-dark_plus-json .token.comment rgb(96, 139, 78)",
"light_plus": ".vs.vscode-theme-defaults-themes-light_plus-json .token.comment rgb(0, 128, 0)",
"dark_vs": ".vs-dark.vscode-theme-defaults-themes-dark_vs-json .token.comment rgb(96, 139, 78)",
"light_vs": ".vs.vscode-theme-defaults-themes-light_vs-json .token.comment rgb(0, 128, 0)",
"hc_black": ".hc-black.vscode-theme-defaults-themes-hc_black-json .token.comment rgb(124, 166, 104)"
}
},
{
"c": "\t",
"t": "function.group.if-block.meta.scope.shell",
"r": {
"dark_plus": ".vs-dark .token rgb(212, 212, 212)",
"light_plus": ".vs .token rgb(0, 0, 0)",
"dark_vs": ".vs-dark .token rgb(212, 212, 212)",
"light_vs": ".vs .token rgb(0, 0, 0)",
"hc_black": ".hc-black .token rgb(255, 255, 255)"
}
},
{
"c": "if",
"t": "control.function.group.if-block.keyword.meta.scope.shell",
"r": {
"dark_plus": ".vs-dark.vscode-theme-defaults-themes-dark_plus-json .token.keyword.control rgb(197, 134, 192)",
"light_plus": ".vs.vscode-theme-defaults-themes-light_plus-json .token.keyword.control rgb(175, 0, 219)",
"dark_vs": ".vs-dark.vscode-theme-defaults-themes-dark_vs-json .token.keyword.control rgb(86, 156, 214)",
"light_vs": ".vs.vscode-theme-defaults-themes-light_vs-json .token.keyword.control rgb(0, 0, 255)",
"hc_black": ".hc-black.vscode-theme-defaults-themes-hc_black-json .token.keyword.control rgb(86, 156, 214)"
}
},
{
"c": " ",
"t": "function.group.if-block.meta.scope.shell",
"r": {
"dark_plus": ".vs-dark .token rgb(212, 212, 212)",
"light_plus": ".vs .token rgb(0, 0, 0)",
"dark_vs": ".vs-dark .token rgb(212, 212, 212)",
"light_vs": ".vs .token rgb(0, 0, 0)",
"hc_black": ".hc-black .token rgb(255, 255, 255)"
}
},
{
"c": "[[",
"t": "definition.function.group.if-block.logical-expression.meta.punctuation.scope.shell",
"r": {
"dark_plus": ".vs-dark .token rgb(212, 212, 212)",
"light_plus": ".vs .token rgb(0, 0, 0)",
"dark_vs": ".vs-dark .token rgb(212, 212, 212)",
"light_vs": ".vs .token rgb(0, 0, 0)",
"hc_black": ".hc-black .token rgb(255, 255, 255)"
}
},
{
"c": " ",
"t": "function.group.if-block.logical-expression.meta.scope.shell",
"r": {
"dark_plus": ".vs-dark .token rgb(212, 212, 212)",
"light_plus": ".vs .token rgb(0, 0, 0)",
"dark_vs": ".vs-dark .token rgb(212, 212, 212)",
"light_vs": ".vs .token rgb(0, 0, 0)",
"hc_black": ".hc-black .token rgb(255, 255, 255)"
}
},
{
"c": "\"",
"t": "begin.definition.double.function.group.if-block.logical-expression.meta.punctuation.quoted.scope.shell.string",
"r": {
"dark_plus": ".vs-dark.vscode-theme-defaults-themes-dark_plus-json .token.string rgb(206, 145, 120)",
"light_plus": ".vs.vscode-theme-defaults-themes-light_plus-json .token.string rgb(163, 21, 21)",
"dark_vs": ".vs-dark.vscode-theme-defaults-themes-dark_vs-json .token.string rgb(206, 145, 120)",
"light_vs": ".vs.vscode-theme-defaults-themes-light_vs-json .token.string rgb(163, 21, 21)",
"hc_black": ".hc-black.vscode-theme-defaults-themes-hc_black-json .token.string rgb(206, 145, 120)"
}
},
{
"c": "$",
"t": "definition.double.function.group.if-block.logical-expression.meta.normal.other.punctuation.quoted.scope.shell.string.variable",
"r": {
"dark_plus": ".vs-dark.vscode-theme-defaults-themes-dark_plus-json .token.variable rgb(156, 220, 254)",
"light_plus": ".vs.vscode-theme-defaults-themes-light_plus-json .token.variable rgb(0, 16, 128)",
"dark_vs": ".vs-dark.vscode-theme-defaults-themes-dark_vs-json .token.string rgb(206, 145, 120)",
"light_vs": ".vs.vscode-theme-defaults-themes-light_vs-json .token.string rgb(163, 21, 21)",
"hc_black": ".hc-black.vscode-theme-defaults-themes-hc_black-json .token.string rgb(206, 145, 120)"
}
},
{
"c": "OSTYPE",
"t": "double.function.group.if-block.logical-expression.meta.normal.other.quoted.scope.shell.string.variable",
"r": {
"dark_plus": ".vs-dark.vscode-theme-defaults-themes-dark_plus-json .token.variable rgb(156, 220, 254)",
"light_plus": ".vs.vscode-theme-defaults-themes-light_plus-json .token.variable rgb(0, 16, 128)",
"dark_vs": ".vs-dark.vscode-theme-defaults-themes-dark_vs-json .token.string rgb(206, 145, 120)",
"light_vs": ".vs.vscode-theme-defaults-themes-light_vs-json .token.string rgb(163, 21, 21)",
"hc_black": ".hc-black.vscode-theme-defaults-themes-hc_black-json .token.string rgb(206, 145, 120)"
}
},
{
"c": "\"",
"t": "definition.double.end.function.group.if-block.logical-expression.meta.punctuation.quoted.scope.shell.string",
"r": {
"dark_plus": ".vs-dark.vscode-theme-defaults-themes-dark_plus-json .token.string rgb(206, 145, 120)",
"light_plus": ".vs.vscode-theme-defaults-themes-light_plus-json .token.string rgb(163, 21, 21)",
"dark_vs": ".vs-dark.vscode-theme-defaults-themes-dark_vs-json .token.string rgb(206, 145, 120)",
"light_vs": ".vs.vscode-theme-defaults-themes-light_vs-json .token.string rgb(163, 21, 21)",
"hc_black": ".hc-black.vscode-theme-defaults-themes-hc_black-json .token.string rgb(206, 145, 120)"
}
},
{
"c": " ",
"t": "function.group.if-block.logical-expression.meta.scope.shell",
"r": {
"dark_plus": ".vs-dark .token rgb(212, 212, 212)",
"light_plus": ".vs .token rgb(0, 0, 0)",
"dark_vs": ".vs-dark .token rgb(212, 212, 212)",
"light_vs": ".vs .token rgb(0, 0, 0)",
"hc_black": ".hc-black .token rgb(255, 255, 255)"
}
},
{
"c": "==",
"t": "function.group.if-block.keyword.logical.logical-expression.meta.operator.scope.shell",
"r": {
"dark_plus": ".vs-dark.vscode-theme-defaults-themes-dark_plus-json .token.keyword.operator rgb(212, 212, 212)",
"light_plus": ".vs.vscode-theme-defaults-themes-light_plus-json .token.keyword.operator rgb(0, 0, 0)",
"dark_vs": ".vs-dark.vscode-theme-defaults-themes-dark_vs-json .token.keyword.operator rgb(212, 212, 212)",
"light_vs": ".vs.vscode-theme-defaults-themes-light_vs-json .token.keyword.operator rgb(0, 0, 0)",
"hc_black": ".hc-black.vscode-theme-defaults-themes-hc_black-json .token.keyword.operator rgb(212, 212, 212)"
}
},
{
"c": " ",
"t": "function.group.if-block.logical-expression.meta.scope.shell",
"r": {
"dark_plus": ".vs-dark .token rgb(212, 212, 212)",
"light_plus": ".vs .token rgb(0, 0, 0)",
"dark_vs": ".vs-dark .token rgb(212, 212, 212)",
"light_vs": ".vs .token rgb(0, 0, 0)",
"hc_black": ".hc-black .token rgb(255, 255, 255)"
}
},
{
"c": "\"",
"t": "begin.definition.double.function.group.if-block.logical-expression.meta.punctuation.quoted.scope.shell.string",
"r": {
"dark_plus": ".vs-dark.vscode-theme-defaults-themes-dark_plus-json .token.string rgb(206, 145, 120)",
"light_plus": ".vs.vscode-theme-defaults-themes-light_plus-json .token.string rgb(163, 21, 21)",
"dark_vs": ".vs-dark.vscode-theme-defaults-themes-dark_vs-json .token.string rgb(206, 145, 120)",
"light_vs": ".vs.vscode-theme-defaults-themes-light_vs-json .token.string rgb(163, 21, 21)",
"hc_black": ".hc-black.vscode-theme-defaults-themes-hc_black-json .token.string rgb(206, 145, 120)"
}
},
{
"c": "darwin",
"t": "double.function.group.if-block.logical-expression.meta.quoted.scope.shell.string",
"r": {
"dark_plus": ".vs-dark.vscode-theme-defaults-themes-dark_plus-json .token.string rgb(206, 145, 120)",
"light_plus": ".vs.vscode-theme-defaults-themes-light_plus-json .token.string rgb(163, 21, 21)",
"dark_vs": ".vs-dark.vscode-theme-defaults-themes-dark_vs-json .token.string rgb(206, 145, 120)",
"light_vs": ".vs.vscode-theme-defaults-themes-light_vs-json .token.string rgb(163, 21, 21)",
"hc_black": ".hc-black.vscode-theme-defaults-themes-hc_black-json .token.string rgb(206, 145, 120)"
}
},
{
"c": "\"",
"t": "definition.double.end.function.group.if-block.logical-expression.meta.punctuation.quoted.scope.shell.string",
"r": {
"dark_plus": ".vs-dark.vscode-theme-defaults-themes-dark_plus-json .token.string rgb(206, 145, 120)",
"light_plus": ".vs.vscode-theme-defaults-themes-light_plus-json .token.string rgb(163, 21, 21)",
"dark_vs": ".vs-dark.vscode-theme-defaults-themes-dark_vs-json .token.string rgb(206, 145, 120)",
"light_vs": ".vs.vscode-theme-defaults-themes-light_vs-json .token.string rgb(163, 21, 21)",
"hc_black": ".hc-black.vscode-theme-defaults-themes-hc_black-json .token.string rgb(206, 145, 120)"
}
},
{
"c": "*",
"t": "function.glob.group.if-block.keyword.logical-expression.meta.operator.scope.shell",
"r": {
"dark_plus": ".vs-dark.vscode-theme-defaults-themes-dark_plus-json .token.keyword.operator rgb(212, 212, 212)",
"light_plus": ".vs.vscode-theme-defaults-themes-light_plus-json .token.keyword.operator rgb(0, 0, 0)",
"dark_vs": ".vs-dark.vscode-theme-defaults-themes-dark_vs-json .token.keyword.operator rgb(212, 212, 212)",
"light_vs": ".vs.vscode-theme-defaults-themes-light_vs-json .token.keyword.operator rgb(0, 0, 0)",
"hc_black": ".hc-black.vscode-theme-defaults-themes-hc_black-json .token.keyword.operator rgb(212, 212, 212)"
}
},
{
"c": " ",
"t": "function.group.if-block.logical-expression.meta.scope.shell",
"r": {
"dark_plus": ".vs-dark .token rgb(212, 212, 212)",
"light_plus": ".vs .token rgb(0, 0, 0)",
"dark_vs": ".vs-dark .token rgb(212, 212, 212)",
"light_vs": ".vs .token rgb(0, 0, 0)",
"hc_black": ".hc-black .token rgb(255, 255, 255)"
}
},
{
"c": "]]",
"t": "definition.function.group.if-block.logical-expression.meta.punctuation.scope.shell",
"r": {
"dark_plus": ".vs-dark .token rgb(212, 212, 212)",
"light_plus": ".vs .token rgb(0, 0, 0)",
"dark_vs": ".vs-dark .token rgb(212, 212, 212)",
"light_vs": ".vs .token rgb(0, 0, 0)",
"hc_black": ".hc-black .token rgb(255, 255, 255)"
}
},
{
"c": ";",
"t": "function.group.if-block.keyword.list.meta.operator.scope.shell",
"r": {
"dark_plus": ".vs-dark.vscode-theme-defaults-themes-dark_plus-json .token.keyword.operator rgb(212, 212, 212)",
"light_plus": ".vs.vscode-theme-defaults-themes-light_plus-json .token.keyword.operator rgb(0, 0, 0)",
"dark_vs": ".vs-dark.vscode-theme-defaults-themes-dark_vs-json .token.keyword.operator rgb(212, 212, 212)",
"light_vs": ".vs.vscode-theme-defaults-themes-light_vs-json .token.keyword.operator rgb(0, 0, 0)",
"hc_black": ".hc-black.vscode-theme-defaults-themes-hc_black-json .token.keyword.operator rgb(212, 212, 212)"
}
},
{
"c": " ",
"t": "function.group.if-block.meta.scope.shell",
"r": {
"dark_plus": ".vs-dark .token rgb(212, 212, 212)",
"light_plus": ".vs .token rgb(0, 0, 0)",
"dark_vs": ".vs-dark .token rgb(212, 212, 212)",
"light_vs": ".vs .token rgb(0, 0, 0)",
"hc_black": ".hc-black .token rgb(255, 255, 255)"
}
},
{
"c": "then",
"t": "control.function.group.if-block.keyword.meta.scope.shell",
"r": {
"dark_plus": ".vs-dark.vscode-theme-defaults-themes-dark_plus-json .token.keyword.control rgb(197, 134, 192)",
"light_plus": ".vs.vscode-theme-defaults-themes-light_plus-json .token.keyword.control rgb(175, 0, 219)",
"dark_vs": ".vs-dark.vscode-theme-defaults-themes-dark_vs-json .token.keyword.control rgb(86, 156, 214)",
"light_vs": ".vs.vscode-theme-defaults-themes-light_vs-json .token.keyword.control rgb(0, 0, 255)",
"hc_black": ".hc-black.vscode-theme-defaults-themes-hc_black-json .token.keyword.control rgb(86, 156, 214)"
}
},
{
"c": "\t\t",
"t": "function.group.if-block.meta.scope.shell",
"r": {
"dark_plus": ".vs-dark .token rgb(212, 212, 212)",
"light_plus": ".vs .token rgb(0, 0, 0)",
"dark_vs": ".vs-dark .token rgb(212, 212, 212)",
"light_vs": ".vs .token rgb(0, 0, 0)",
"hc_black": ".hc-black .token rgb(255, 255, 255)"
}
},
{
"c": "exec",
"t": "builtin.function.group.if-block.meta.scope.shell.support",
"r": {
"dark_plus": ".vs-dark .token rgb(212, 212, 212)",
"light_plus": ".vs .token rgb(0, 0, 0)",
"dark_vs": ".vs-dark .token rgb(212, 212, 212)",
"light_vs": ".vs .token rgb(0, 0, 0)",
"hc_black": ".hc-black .token rgb(255, 255, 255)"
}
},
{
"c": " ./.build/electron/Electron.app/Contents/MacOS/Electron ",
"t": "function.group.if-block.meta.scope.shell",
"r": {
"dark_plus": ".vs-dark .token rgb(212, 212, 212)",
"light_plus": ".vs .token rgb(0, 0, 0)",
"dark_vs": ".vs-dark .token rgb(212, 212, 212)",
"light_vs": ".vs .token rgb(0, 0, 0)",
"hc_black": ".hc-black .token rgb(255, 255, 255)"
}
},
{
"c": ".",
"t": "builtin.function.group.if-block.meta.scope.shell.support",
"r": {
"dark_plus": ".vs-dark .token rgb(212, 212, 212)",
"light_plus": ".vs .token rgb(0, 0, 0)",
"dark_vs": ".vs-dark .token rgb(212, 212, 212)",
"light_vs": ".vs .token rgb(0, 0, 0)",
"hc_black": ".hc-black .token rgb(255, 255, 255)"
}
},
{
"c": " ",
"t": "function.group.if-block.meta.scope.shell",
"r": {
"dark_plus": ".vs-dark .token rgb(212, 212, 212)",
"light_plus": ".vs .token rgb(0, 0, 0)",
"dark_vs": ".vs-dark .token rgb(212, 212, 212)",
"light_vs": ".vs .token rgb(0, 0, 0)",
"hc_black": ".hc-black .token rgb(255, 255, 255)"
}
},
{
"c": "\"",
"t": "begin.definition.double.function.group.if-block.meta.punctuation.quoted.scope.shell.string",
"r": {
"dark_plus": ".vs-dark.vscode-theme-defaults-themes-dark_plus-json .token.string rgb(206, 145, 120)",
"light_plus": ".vs.vscode-theme-defaults-themes-light_plus-json .token.string rgb(163, 21, 21)",
"dark_vs": ".vs-dark.vscode-theme-defaults-themes-dark_vs-json .token.string rgb(206, 145, 120)",
"light_vs": ".vs.vscode-theme-defaults-themes-light_vs-json .token.string rgb(163, 21, 21)",
"hc_black": ".hc-black.vscode-theme-defaults-themes-hc_black-json .token.string rgb(206, 145, 120)"
}
},
{
"c": "$",
"t": "definition.double.function.group.if-block.meta.other.punctuation.quoted.scope.shell.special.string.variable",
"r": {
"dark_plus": ".vs-dark.vscode-theme-defaults-themes-dark_plus-json .token.variable rgb(156, 220, 254)",
"light_plus": ".vs.vscode-theme-defaults-themes-light_plus-json .token.variable rgb(0, 16, 128)",
"dark_vs": ".vs-dark.vscode-theme-defaults-themes-dark_vs-json .token.string rgb(206, 145, 120)",
"light_vs": ".vs.vscode-theme-defaults-themes-light_vs-json .token.string rgb(163, 21, 21)",
"hc_black": ".hc-black.vscode-theme-defaults-themes-hc_black-json .token.string rgb(206, 145, 120)"
}
},
{
"c": "@",
"t": "double.function.group.if-block.meta.other.quoted.scope.shell.special.string.variable",
"r": {
"dark_plus": ".vs-dark.vscode-theme-defaults-themes-dark_plus-json .token.variable rgb(156, 220, 254)",
"light_plus": ".vs.vscode-theme-defaults-themes-light_plus-json .token.variable rgb(0, 16, 128)",
"dark_vs": ".vs-dark.vscode-theme-defaults-themes-dark_vs-json .token.string rgb(206, 145, 120)",
"light_vs": ".vs.vscode-theme-defaults-themes-light_vs-json .token.string rgb(163, 21, 21)",
"hc_black": ".hc-black.vscode-theme-defaults-themes-hc_black-json .token.string rgb(206, 145, 120)"
}
},
{
"c": "\"",
"t": "definition.double.end.function.group.if-block.meta.punctuation.quoted.scope.shell.string",
"r": {
"dark_plus": ".vs-dark.vscode-theme-defaults-themes-dark_plus-json .token.string rgb(206, 145, 120)",
"light_plus": ".vs.vscode-theme-defaults-themes-light_plus-json .token.string rgb(163, 21, 21)",
"dark_vs": ".vs-dark.vscode-theme-defaults-themes-dark_vs-json .token.string rgb(206, 145, 120)",
"light_vs": ".vs.vscode-theme-defaults-themes-light_vs-json .token.string rgb(163, 21, 21)",
"hc_black": ".hc-black.vscode-theme-defaults-themes-hc_black-json .token.string rgb(206, 145, 120)"
}
},
{
"c": "\t",
"t": "function.group.if-block.meta.scope.shell",
"r": {
"dark_plus": ".vs-dark .token rgb(212, 212, 212)",
"light_plus": ".vs .token rgb(0, 0, 0)",
"dark_vs": ".vs-dark .token rgb(212, 212, 212)",
"light_vs": ".vs .token rgb(0, 0, 0)",
"hc_black": ".hc-black .token rgb(255, 255, 255)"
}
},
{
"c": "else",
"t": "control.function.group.if-block.keyword.meta.scope.shell",
"r": {
"dark_plus": ".vs-dark.vscode-theme-defaults-themes-dark_plus-json .token.keyword.control rgb(197, 134, 192)",
"light_plus": ".vs.vscode-theme-defaults-themes-light_plus-json .token.keyword.control rgb(175, 0, 219)",
"dark_vs": ".vs-dark.vscode-theme-defaults-themes-dark_vs-json .token.keyword.control rgb(86, 156, 214)",
"light_vs": ".vs.vscode-theme-defaults-themes-light_vs-json .token.keyword.control rgb(0, 0, 255)",
"hc_black": ".hc-black.vscode-theme-defaults-themes-hc_black-json .token.keyword.control rgb(86, 156, 214)"
}
},
{
"c": "\t\t",
"t": "function.group.if-block.meta.scope.shell",
"r": {
"dark_plus": ".vs-dark .token rgb(212, 212, 212)",
"light_plus": ".vs .token rgb(0, 0, 0)",
"dark_vs": ".vs-dark .token rgb(212, 212, 212)",
"light_vs": ".vs .token rgb(0, 0, 0)",
"hc_black": ".hc-black .token rgb(255, 255, 255)"
}
},
{
"c": "exec",
"t": "builtin.function.group.if-block.meta.scope.shell.support",
"r": {
"dark_plus": ".vs-dark .token rgb(212, 212, 212)",
"light_plus": ".vs .token rgb(0, 0, 0)",
"dark_vs": ".vs-dark .token rgb(212, 212, 212)",
"light_vs": ".vs .token rgb(0, 0, 0)",
"hc_black": ".hc-black .token rgb(255, 255, 255)"
}
},
{
"c": " ./.build/electron/electron ",
"t": "function.group.if-block.meta.scope.shell",
"r": {
"dark_plus": ".vs-dark .token rgb(212, 212, 212)",
"light_plus": ".vs .token rgb(0, 0, 0)",
"dark_vs": ".vs-dark .token rgb(212, 212, 212)",
"light_vs": ".vs .token rgb(0, 0, 0)",
"hc_black": ".hc-black .token rgb(255, 255, 255)"
}
},
{
"c": ".",
"t": "builtin.function.group.if-block.meta.scope.shell.support",
"r": {
"dark_plus": ".vs-dark .token rgb(212, 212, 212)",
"light_plus": ".vs .token rgb(0, 0, 0)",
"dark_vs": ".vs-dark .token rgb(212, 212, 212)",
"light_vs": ".vs .token rgb(0, 0, 0)",
"hc_black": ".hc-black .token rgb(255, 255, 255)"
}
},
{
"c": " ",
"t": "function.group.if-block.meta.scope.shell",
"r": {
"dark_plus": ".vs-dark .token rgb(212, 212, 212)",
"light_plus": ".vs .token rgb(0, 0, 0)",
"dark_vs": ".vs-dark .token rgb(212, 212, 212)",
"light_vs": ".vs .token rgb(0, 0, 0)",
"hc_black": ".hc-black .token rgb(255, 255, 255)"
}
},
{
"c": "\"",
"t": "begin.definition.double.function.group.if-block.meta.punctuation.quoted.scope.shell.string",
"r": {
"dark_plus": ".vs-dark.vscode-theme-defaults-themes-dark_plus-json .token.string rgb(206, 145, 120)",
"light_plus": ".vs.vscode-theme-defaults-themes-light_plus-json .token.string rgb(163, 21, 21)",
"dark_vs": ".vs-dark.vscode-theme-defaults-themes-dark_vs-json .token.string rgb(206, 145, 120)",
"light_vs": ".vs.vscode-theme-defaults-themes-light_vs-json .token.string rgb(163, 21, 21)",
"hc_black": ".hc-black.vscode-theme-defaults-themes-hc_black-json .token.string rgb(206, 145, 120)"
}
},
{
"c": "$",
"t": "definition.double.function.group.if-block.meta.other.punctuation.quoted.scope.shell.special.string.variable",
"r": {
"dark_plus": ".vs-dark.vscode-theme-defaults-themes-dark_plus-json .token.variable rgb(156, 220, 254)",
"light_plus": ".vs.vscode-theme-defaults-themes-light_plus-json .token.variable rgb(0, 16, 128)",
"dark_vs": ".vs-dark.vscode-theme-defaults-themes-dark_vs-json .token.string rgb(206, 145, 120)",
"light_vs": ".vs.vscode-theme-defaults-themes-light_vs-json .token.string rgb(163, 21, 21)",
"hc_black": ".hc-black.vscode-theme-defaults-themes-hc_black-json .token.string rgb(206, 145, 120)"
}
},
{
"c": "@",
"t": "double.function.group.if-block.meta.other.quoted.scope.shell.special.string.variable",
"r": {
"dark_plus": ".vs-dark.vscode-theme-defaults-themes-dark_plus-json .token.variable rgb(156, 220, 254)",
"light_plus": ".vs.vscode-theme-defaults-themes-light_plus-json .token.variable rgb(0, 16, 128)",
"dark_vs": ".vs-dark.vscode-theme-defaults-themes-dark_vs-json .token.string rgb(206, 145, 120)",
"light_vs": ".vs.vscode-theme-defaults-themes-light_vs-json .token.string rgb(163, 21, 21)",
"hc_black": ".hc-black.vscode-theme-defaults-themes-hc_black-json .token.string rgb(206, 145, 120)"
}
},
{
"c": "\"",
"t": "definition.double.end.function.group.if-block.meta.punctuation.quoted.scope.shell.string",
"r": {
"dark_plus": ".vs-dark.vscode-theme-defaults-themes-dark_plus-json .token.string rgb(206, 145, 120)",
"light_plus": ".vs.vscode-theme-defaults-themes-light_plus-json .token.string rgb(163, 21, 21)",
"dark_vs": ".vs-dark.vscode-theme-defaults-themes-dark_vs-json .token.string rgb(206, 145, 120)",
"light_vs": ".vs.vscode-theme-defaults-themes-light_vs-json .token.string rgb(163, 21, 21)",
"hc_black": ".hc-black.vscode-theme-defaults-themes-hc_black-json .token.string rgb(206, 145, 120)"
}
},
{
"c": "\t",
"t": "function.group.if-block.meta.scope.shell",
"r": {
"dark_plus": ".vs-dark .token rgb(212, 212, 212)",
"light_plus": ".vs .token rgb(0, 0, 0)",
"dark_vs": ".vs-dark .token rgb(212, 212, 212)",
"light_vs": ".vs .token rgb(0, 0, 0)",
"hc_black": ".hc-black .token rgb(255, 255, 255)"
}
},
{
"c": "fi",
"t": "control.function.group.if-block.keyword.meta.scope.shell",
"r": {
"dark_plus": ".vs-dark.vscode-theme-defaults-themes-dark_plus-json .token.keyword.control rgb(197, 134, 192)",
"light_plus": ".vs.vscode-theme-defaults-themes-light_plus-json .token.keyword.control rgb(175, 0, 219)",
"dark_vs": ".vs-dark.vscode-theme-defaults-themes-dark_vs-json .token.keyword.control rgb(86, 156, 214)",
"light_vs": ".vs.vscode-theme-defaults-themes-light_vs-json .token.keyword.control rgb(0, 0, 255)",
"hc_black": ".hc-black.vscode-theme-defaults-themes-hc_black-json .token.keyword.control rgb(86, 156, 214)"
}
},
{
"c": "}",
"t": "definition.function.group.meta.punctuation.scope.shell",
"r": {
"dark_plus": ".vs-dark .token rgb(212, 212, 212)",
"light_plus": ".vs .token rgb(0, 0, 0)",
"dark_vs": ".vs-dark .token rgb(212, 212, 212)",
"light_vs": ".vs .token rgb(0, 0, 0)",
"hc_black": ".hc-black .token rgb(255, 255, 255)"
}
},
{
"c": "code ",
"t": "",
"r": {
"dark_plus": ".vs-dark .token rgb(212, 212, 212)",
"light_plus": ".vs .token rgb(0, 0, 0)",
"dark_vs": ".vs-dark .token rgb(212, 212, 212)",
"light_vs": ".vs .token rgb(0, 0, 0)",
"hc_black": ".hc-black .token rgb(255, 255, 255)"
}
},
{
"c": "\"",
"t": "begin.definition.double.punctuation.quoted.shell.string",
"r": {
"dark_plus": ".vs-dark.vscode-theme-defaults-themes-dark_plus-json .token.string rgb(206, 145, 120)",
"light_plus": ".vs.vscode-theme-defaults-themes-light_plus-json .token.string rgb(163, 21, 21)",
"dark_vs": ".vs-dark.vscode-theme-defaults-themes-dark_vs-json .token.string rgb(206, 145, 120)",
"light_vs": ".vs.vscode-theme-defaults-themes-light_vs-json .token.string rgb(163, 21, 21)",
"hc_black": ".hc-black.vscode-theme-defaults-themes-hc_black-json .token.string rgb(206, 145, 120)"
}
},
{
"c": "$",
"t": "definition.double.other.punctuation.quoted.shell.special.string.variable",
"r": {
"dark_plus": ".vs-dark.vscode-theme-defaults-themes-dark_plus-json .token.variable rgb(156, 220, 254)",
"light_plus": ".vs.vscode-theme-defaults-themes-light_plus-json .token.variable rgb(0, 16, 128)",
"dark_vs": ".vs-dark.vscode-theme-defaults-themes-dark_vs-json .token.string rgb(206, 145, 120)",
"light_vs": ".vs.vscode-theme-defaults-themes-light_vs-json .token.string rgb(163, 21, 21)",
"hc_black": ".hc-black.vscode-theme-defaults-themes-hc_black-json .token.string rgb(206, 145, 120)"
}
},
{
"c": "@",
"t": "double.other.quoted.shell.special.string.variable",
"r": {
"dark_plus": ".vs-dark.vscode-theme-defaults-themes-dark_plus-json .token.variable rgb(156, 220, 254)",
"light_plus": ".vs.vscode-theme-defaults-themes-light_plus-json .token.variable rgb(0, 16, 128)",
"dark_vs": ".vs-dark.vscode-theme-defaults-themes-dark_vs-json .token.string rgb(206, 145, 120)",
"light_vs": ".vs.vscode-theme-defaults-themes-light_vs-json .token.string rgb(163, 21, 21)",
"hc_black": ".hc-black.vscode-theme-defaults-themes-hc_black-json .token.string rgb(206, 145, 120)"
}
},
{
"c": "\"",
"t": "definition.double.end.punctuation.quoted.shell.string",
"r": {
"dark_plus": ".vs-dark.vscode-theme-defaults-themes-dark_plus-json .token.string rgb(206, 145, 120)",
"light_plus": ".vs.vscode-theme-defaults-themes-light_plus-json .token.string rgb(163, 21, 21)",
"dark_vs": ".vs-dark.vscode-theme-defaults-themes-dark_vs-json .token.string rgb(206, 145, 120)",
"light_vs": ".vs.vscode-theme-defaults-themes-light_vs-json .token.string rgb(163, 21, 21)",
"hc_black": ".hc-black.vscode-theme-defaults-themes-hc_black-json .token.string rgb(206, 145, 120)"
}
}
] | extensions/shellscript/test/colorize-results/test_sh.json | 0 | https://github.com/microsoft/vscode/commit/e12eb3dc06b131a8c00fbe61c77ae98311f103e9 | [
0.00017625455802772194,
0.00017231586389243603,
0.00016602865071035922,
0.00017265106725972146,
0.000002432339215374668
] |
{
"id": 5,
"code_window": [
"import {IFileMatch, ILineMatch} from 'vs/platform/search/common/search';\n",
"import { ITelemetryService } from 'vs/platform/telemetry/common/telemetry';\n",
"import { ISearchService, ISearchComplete, ISearchProgressItem } from 'vs/platform/search/common/search';\n",
"import { Range } from 'vs/editor/common/core/range';\n",
"\n",
"suite('SearchModel', () => {\n",
"\n",
"\tlet instantiationService: TestInstantiationService;\n"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"import { createMockModelService } from 'vs/test/utils/servicesTestUtils';\n",
"import { IModelService } from 'vs/editor/common/services/modelService';\n"
],
"file_path": "src/vs/workbench/parts/search/test/common/searchModel.test.ts",
"type": "add",
"edit_start_line_idx": 18
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
'use strict';
import * as assert from 'assert';
import * as sinon from 'sinon';
import { TestInstantiationService } from 'vs/test/utils/instantiationTestUtils';
import { Match, FileMatch, SearchResult, SearchModel } from 'vs/workbench/parts/search/common/searchModel';
import URI from 'vs/base/common/uri';
import {IFileMatch, ILineMatch} from 'vs/platform/search/common/search';
import { ITelemetryService } from 'vs/platform/telemetry/common/telemetry';
import { Range } from 'vs/editor/common/core/range';
suite('SearchResult', () => {
let instantiationService: TestInstantiationService;
setup(() => {
instantiationService= new TestInstantiationService();
instantiationService.stub(ITelemetryService);
});
test('Line Match', function () {
let fileMatch = aFileMatch('folder\\file.txt');
let lineMatch = new Match(fileMatch, 'foo bar', 1, 0, 3);
assert.equal(lineMatch.text(), 'foo bar');
assert.equal(lineMatch.range().startLineNumber, 2);
assert.equal(lineMatch.range().endLineNumber, 2);
assert.equal(lineMatch.range().startColumn, 1);
assert.equal(lineMatch.range().endColumn, 4);
});
test('Line Match - Remove', function () {
let fileMatch = aFileMatch('folder\\file.txt', null, ...[{
preview: 'foo bar',
lineNumber: 1,
offsetAndLengths: [[0, 3]]
}]);
let lineMatch = fileMatch.matches()[0];
fileMatch.remove(lineMatch);
assert.equal(fileMatch.matches().length, 0);
});
test('File Match', function () {
let fileMatch = aFileMatch('folder\\file.txt');
assert.equal(fileMatch.matches(), 0);
assert.equal(fileMatch.resource().toString(), 'file:///c%3A/folder/file.txt');
assert.equal(fileMatch.name(), 'file.txt');
fileMatch = aFileMatch('file.txt');
assert.equal(fileMatch.matches(), 0);
assert.equal(fileMatch.resource().toString(), 'file:///c%3A/file.txt');
assert.equal(fileMatch.name(), 'file.txt');
});
test('Alle Drei Zusammen', function () {
let searchResult = instantiationService.createInstance(SearchResult, null);
let fileMatch = aFileMatch('far\\boo', searchResult);
let lineMatch = new Match(fileMatch, 'foo bar', 1, 0, 3);
assert(lineMatch.parent() === fileMatch);
assert(fileMatch.parent() === searchResult);
});
test('Search Result: Adding a raw match will add a file match with line matches', function () {
let testObject = aSearchResult();
let target= [aRawMatch('file://c:/', aLineMatch('preview 1', 1, [[1, 3], [4, 7]]), aLineMatch('preview 2'))];
testObject.add(target);
assert.equal(3, testObject.count());
let actual= testObject.matches();
assert.equal(1, actual.length);
assert.equal('file://c:/', actual[0].resource().toString());
let actuaMatches= actual[0].matches();
assert.equal(3, actuaMatches.length);
assert.equal('preview 1', actuaMatches[0].text());
assert.ok(new Range(2, 2, 2, 5).equalsRange(actuaMatches[0].range()));
assert.equal('preview 1', actuaMatches[1].text());
assert.ok(new Range(2, 5, 2, 12).equalsRange(actuaMatches[1].range()));
assert.equal('preview 2', actuaMatches[2].text());
assert.ok(new Range(2, 1, 2, 2).equalsRange(actuaMatches[2].range()));
});
test('Search Result: Adding multiple raw matches', function () {
let testObject = aSearchResult();
let target= [aRawMatch('file://c:/1', aLineMatch('preview 1', 1, [[1, 3], [4, 7]])), aRawMatch('file://c:/2', aLineMatch('preview 2'))];
testObject.add(target);
assert.equal(3, testObject.count());
let actual= testObject.matches();
assert.equal(2, actual.length);
assert.equal('file://c:/1', actual[0].resource().toString());
let actuaMatches= actual[0].matches();
assert.equal(2, actuaMatches.length);
assert.equal('preview 1', actuaMatches[0].text());
assert.ok(new Range(2, 2, 2, 5).equalsRange(actuaMatches[0].range()));
assert.equal('preview 1', actuaMatches[1].text());
assert.ok(new Range(2, 5, 2, 12).equalsRange(actuaMatches[1].range()));
actuaMatches= actual[1].matches();
assert.equal(1, actuaMatches.length);
assert.equal('preview 2', actuaMatches[0].text());
assert.ok(new Range(2, 1, 2, 2).equalsRange(actuaMatches[0].range()));
});
test('Search Result: Dispose disposes matches', function () {
let target1= sinon.spy();
let target2= sinon.spy();
let testObject = aSearchResult();
testObject.add([aRawMatch('file://c:/1', aLineMatch('preview 1')), aRawMatch('file://c:/2', aLineMatch('preview 2'))]);
testObject.matches()[0].onDispose(target1);
testObject.matches()[1].onDispose(target2);
testObject.dispose();
assert.ok(testObject.isEmpty());
assert.ok(target1.calledOnce);
assert.ok(target2.calledOnce);
});
test('Search Result: Removing all line matches and adding back will add file back to result', function () {
let testObject = aSearchResult();
testObject.add([aRawMatch('file://c:/1', aLineMatch('preview 1'))]);
let target= testObject.matches()[0];
let matchToRemove= target.matches()[0];
target.remove(matchToRemove);
assert.ok(testObject.isEmpty());
target.add(matchToRemove, true);
assert.equal(1, testObject.fileCount());
assert.equal(target, testObject.matches()[0]);
});
//// ----- utils
//function lineHasDecorations(model: editor.IModel, lineNumber: number, decorations: { start: number; end: number; }[]): void {
// let lineDecorations:typeof decorations = [];
// let decs = model.getLineDecorations(lineNumber);
// for (let i = 0, len = decs.length; i < len; i++) {
// lineDecorations.push({
// start: decs[i].range.startColumn,
// end: decs[i].range.endColumn
// });
// }
// assert.deepEqual(lineDecorations, decorations);
//}
//
//function lineHasNoDecoration(model: editor.IModel, lineNumber: number): void {
// lineHasDecorations(model, lineNumber, []);
//}
//
//function lineHasDecoration(model: editor.IModel, lineNumber: number, start: number, end: number): void {
// lineHasDecorations(model, lineNumber, [{
// start: start,
// end: end
// }]);
//}
//// ----- end utils
//
//test('Model Highlights', function () {
//
// let fileMatch = instantiation.createInstance(FileMatch, null, toUri('folder\\file.txt'));
// fileMatch.add(new Match(fileMatch, 'line2', 1, 0, 2));
// fileMatch.connect();
// lineHasDecoration(oneModel, 2, 1, 3);
//});
//
//test('Dispose', function () {
//
// let fileMatch = instantiation.createInstance(FileMatch, null, toUri('folder\\file.txt'));
// fileMatch.add(new Match(fileMatch, 'line2', 1, 0, 2));
// fileMatch.connect();
// lineHasDecoration(oneModel, 2, 1, 3);
//
// fileMatch.dispose();
// lineHasNoDecoration(oneModel, 2);
//});
function aFileMatch(path: string, searchResult?: SearchResult, ...lineMatches: ILineMatch[]): FileMatch {
let rawMatch: IFileMatch = {
resource: URI.file('C:\\' + path),
lineMatches: lineMatches
};
return new FileMatch(null, searchResult, rawMatch, null, null);
}
function aSearchResult(): SearchResult {
let searchModel = instantiationService.createInstance(SearchModel);
return searchModel.searchResult;
}
function aRawMatch(resource: string, ...lineMatches: ILineMatch[]): IFileMatch {
return { resource: URI.parse(resource), lineMatches };
}
function aLineMatch(preview: string, lineNumber: number = 1, offsetAndLengths: number[][] = [[0, 1]]): ILineMatch {
return { preview, lineNumber, offsetAndLengths };
}
}); | src/vs/workbench/parts/search/test/common/searchResult.test.ts | 1 | https://github.com/microsoft/vscode/commit/e12eb3dc06b131a8c00fbe61c77ae98311f103e9 | [
0.9979512095451355,
0.0923539400100708,
0.00016233671340160072,
0.00017412858142051846,
0.28641337156295776
] |
{
"id": 5,
"code_window": [
"import {IFileMatch, ILineMatch} from 'vs/platform/search/common/search';\n",
"import { ITelemetryService } from 'vs/platform/telemetry/common/telemetry';\n",
"import { ISearchService, ISearchComplete, ISearchProgressItem } from 'vs/platform/search/common/search';\n",
"import { Range } from 'vs/editor/common/core/range';\n",
"\n",
"suite('SearchModel', () => {\n",
"\n",
"\tlet instantiationService: TestInstantiationService;\n"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"import { createMockModelService } from 'vs/test/utils/servicesTestUtils';\n",
"import { IModelService } from 'vs/editor/common/services/modelService';\n"
],
"file_path": "src/vs/workbench/parts/search/test/common/searchModel.test.ts",
"type": "add",
"edit_start_line_idx": 18
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
// Do not edit this file. It is machine generated.
{
"dotnetCore": "Выполняет команду сборки .NET Core",
"externalCommand": "Пример для запуска произвольной внешней команды",
"msbuild": "Выполняет целевой объект сборки",
"tsc.config": "Компилирует проект TypeScript",
"tsc.watch": "Компилирует проект TypeScript в режиме наблюдения"
} | i18n/rus/src/vs/workbench/parts/tasks/common/taskTemplates.i18n.json | 0 | https://github.com/microsoft/vscode/commit/e12eb3dc06b131a8c00fbe61c77ae98311f103e9 | [
0.00017122113786172122,
0.00017089744505938143,
0.00017057375225704163,
0.00017089744505938143,
3.2369280233979225e-7
] |
{
"id": 5,
"code_window": [
"import {IFileMatch, ILineMatch} from 'vs/platform/search/common/search';\n",
"import { ITelemetryService } from 'vs/platform/telemetry/common/telemetry';\n",
"import { ISearchService, ISearchComplete, ISearchProgressItem } from 'vs/platform/search/common/search';\n",
"import { Range } from 'vs/editor/common/core/range';\n",
"\n",
"suite('SearchModel', () => {\n",
"\n",
"\tlet instantiationService: TestInstantiationService;\n"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"import { createMockModelService } from 'vs/test/utils/servicesTestUtils';\n",
"import { IModelService } from 'vs/editor/common/services/modelService';\n"
],
"file_path": "src/vs/workbench/parts/search/test/common/searchModel.test.ts",
"type": "add",
"edit_start_line_idx": 18
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
// Do not edit this file. It is machine generated.
{
"ColonExpected": "Ожидается двоеточие",
"DisallowedExtraPropWarning": "Свойство {0} запрещено",
"DoubleQuotesExpected": "Ключи свойств должны быть заключены в двойные кавычки",
"DuplicateKeyWarning": "Дублирующийся ключ объекта",
"End of file expected": "Ожидается конец файла",
"ExpectedCloseBrace": "Ожидается запятая или закрывающая фигурная скобка.",
"ExpectedCloseBracket": "Ожидается запятая или закрывающая скобка.",
"Invalid symbol": "Ожидается JSON-объект, массив или литерал",
"InvalidEscapeCharacter": "Недопустимый escape-символ в строке",
"InvalidNumberFormat": "Недопустимый числовой формат",
"InvalidUnicode": "Недопустимая последовательность Юникода в строке",
"MaxPropWarning": "У объекта больше свойств, чем предельно допустимо ({0})",
"MinPropWarning": "Объект имеет меньше свойств, чем требуется ({0})",
"MissingRequiredPropWarning": "Отсутствующее свойство \"{0}\"",
"PropertyExpected": "Ожидалось свойство",
"RequiredDependentPropWarning": "В объекте отсутствует свойство {0}, требуемое свойством {1}",
"UnexpectedEndOfComment": "Непредвиденное окончание комментария",
"UnexpectedEndOfNumber": "Непредвиденное окончание числа",
"UnexpectedEndOfString": "Непредвиденное окончание строки",
"ValueExpected": "Ожидаемое значение",
"additionalItemsWarning": "Согласно схеме, в массиве слишком много элементов. Ожидаемое количество - не более {0}",
"enumWarning": "Значение не является допустимым. Допустимые значения: {0}",
"exclusiveMaximumWarning": "Значение превышает эксклюзивный максимум {0}",
"exclusiveMinimumWarning": "Значение ниже эксклюзивного минимума {0}",
"maxItemsWarning": "В массиве слишком много элементов. Ожидаемое количество - не более {0}",
"maxLengthWarning": "Строка короче максимальной длины",
"maximumWarning": "Значение превышает максимум, {0}",
"minItemsWarning": "В массиве слишком мало элементов. Ожидаемое количество - не менее {0}",
"minLengthWarning": "Строка короче минимальной длины",
"minimumWarning": "Значение меньше минимума, {0}",
"multipleOfWarning": "Значение не делится на {0}",
"notSchemaWarning": "Соответствует неразрешенной схеме.",
"oneOfWarning": "Соответствует нескольким схемам, хотя достаточно, чтобы проверку прошла только одна.",
"patternWarning": "Строка не соответствует шаблону \"{0}\"",
"typeArrayMismatchWarning": "Неверный тип. Ожидаемый тип - один из {0}",
"typeMismatchWarning": "Неверный тип. Ожидаемый тип: \"{0}\"",
"uniqueItemsWarning": "Массив дублирующихся единиц"
} | i18n/rus/src/vs/languages/json/common/parser/jsonParser.i18n.json | 0 | https://github.com/microsoft/vscode/commit/e12eb3dc06b131a8c00fbe61c77ae98311f103e9 | [
0.00026674376567825675,
0.00019491792772896588,
0.00016837139264680445,
0.0001721779117360711,
0.000037261441320879385
] |
{
"id": 5,
"code_window": [
"import {IFileMatch, ILineMatch} from 'vs/platform/search/common/search';\n",
"import { ITelemetryService } from 'vs/platform/telemetry/common/telemetry';\n",
"import { ISearchService, ISearchComplete, ISearchProgressItem } from 'vs/platform/search/common/search';\n",
"import { Range } from 'vs/editor/common/core/range';\n",
"\n",
"suite('SearchModel', () => {\n",
"\n",
"\tlet instantiationService: TestInstantiationService;\n"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"import { createMockModelService } from 'vs/test/utils/servicesTestUtils';\n",
"import { IModelService } from 'vs/editor/common/services/modelService';\n"
],
"file_path": "src/vs/workbench/parts/search/test/common/searchModel.test.ts",
"type": "add",
"edit_start_line_idx": 18
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
'use strict';
import { workspace } from 'vscode';
export interface IConfiguration {
useCodeSnippetsOnMethodSuggest?: boolean;
}
export var defaultConfiguration: IConfiguration = {
useCodeSnippetsOnMethodSuggest: false
};
export function load(myPluginId: string): IConfiguration {
let configuration = workspace.getConfiguration(myPluginId);
let useCodeSnippetsOnMethodSuggest = configuration.get('useCodeSnippetsOnMethodSuggest', defaultConfiguration.useCodeSnippetsOnMethodSuggest);
return {
useCodeSnippetsOnMethodSuggest
};
} | extensions/typescript/src/features/configuration.ts | 0 | https://github.com/microsoft/vscode/commit/e12eb3dc06b131a8c00fbe61c77ae98311f103e9 | [
0.0001756614656187594,
0.00017213136015925556,
0.0001680198620306328,
0.0001727127964841202,
0.0000031466452128370292
] |
{
"id": 6,
"code_window": [
"\tsetup(() => {\n",
"\t\trestoreStubs= [];\n",
"\t\tinstantiationService= new TestInstantiationService();\n",
"\t\tinstantiationService.stub(ITelemetryService);\n",
"\t});\n",
"\n",
"\tteardown(() => {\n",
"\t\trestoreStubs.forEach(element => {\n",
"\t\t\telement.restore();\n"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\tinstantiationService.stub(IModelService, createMockModelService(instantiationService));\n"
],
"file_path": "src/vs/workbench/parts/search/test/common/searchModel.test.ts",
"type": "add",
"edit_start_line_idx": 28
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
'use strict';
import * as assert from 'assert';
import * as sinon from 'sinon';
import { TestInstantiationService } from 'vs/test/utils/instantiationTestUtils';
import { Match, FileMatch, SearchResult, SearchModel } from 'vs/workbench/parts/search/common/searchModel';
import URI from 'vs/base/common/uri';
import {IFileMatch, ILineMatch} from 'vs/platform/search/common/search';
import { ITelemetryService } from 'vs/platform/telemetry/common/telemetry';
import { Range } from 'vs/editor/common/core/range';
suite('SearchResult', () => {
let instantiationService: TestInstantiationService;
setup(() => {
instantiationService= new TestInstantiationService();
instantiationService.stub(ITelemetryService);
});
test('Line Match', function () {
let fileMatch = aFileMatch('folder\\file.txt');
let lineMatch = new Match(fileMatch, 'foo bar', 1, 0, 3);
assert.equal(lineMatch.text(), 'foo bar');
assert.equal(lineMatch.range().startLineNumber, 2);
assert.equal(lineMatch.range().endLineNumber, 2);
assert.equal(lineMatch.range().startColumn, 1);
assert.equal(lineMatch.range().endColumn, 4);
});
test('Line Match - Remove', function () {
let fileMatch = aFileMatch('folder\\file.txt', null, ...[{
preview: 'foo bar',
lineNumber: 1,
offsetAndLengths: [[0, 3]]
}]);
let lineMatch = fileMatch.matches()[0];
fileMatch.remove(lineMatch);
assert.equal(fileMatch.matches().length, 0);
});
test('File Match', function () {
let fileMatch = aFileMatch('folder\\file.txt');
assert.equal(fileMatch.matches(), 0);
assert.equal(fileMatch.resource().toString(), 'file:///c%3A/folder/file.txt');
assert.equal(fileMatch.name(), 'file.txt');
fileMatch = aFileMatch('file.txt');
assert.equal(fileMatch.matches(), 0);
assert.equal(fileMatch.resource().toString(), 'file:///c%3A/file.txt');
assert.equal(fileMatch.name(), 'file.txt');
});
test('Alle Drei Zusammen', function () {
let searchResult = instantiationService.createInstance(SearchResult, null);
let fileMatch = aFileMatch('far\\boo', searchResult);
let lineMatch = new Match(fileMatch, 'foo bar', 1, 0, 3);
assert(lineMatch.parent() === fileMatch);
assert(fileMatch.parent() === searchResult);
});
test('Search Result: Adding a raw match will add a file match with line matches', function () {
let testObject = aSearchResult();
let target= [aRawMatch('file://c:/', aLineMatch('preview 1', 1, [[1, 3], [4, 7]]), aLineMatch('preview 2'))];
testObject.add(target);
assert.equal(3, testObject.count());
let actual= testObject.matches();
assert.equal(1, actual.length);
assert.equal('file://c:/', actual[0].resource().toString());
let actuaMatches= actual[0].matches();
assert.equal(3, actuaMatches.length);
assert.equal('preview 1', actuaMatches[0].text());
assert.ok(new Range(2, 2, 2, 5).equalsRange(actuaMatches[0].range()));
assert.equal('preview 1', actuaMatches[1].text());
assert.ok(new Range(2, 5, 2, 12).equalsRange(actuaMatches[1].range()));
assert.equal('preview 2', actuaMatches[2].text());
assert.ok(new Range(2, 1, 2, 2).equalsRange(actuaMatches[2].range()));
});
test('Search Result: Adding multiple raw matches', function () {
let testObject = aSearchResult();
let target= [aRawMatch('file://c:/1', aLineMatch('preview 1', 1, [[1, 3], [4, 7]])), aRawMatch('file://c:/2', aLineMatch('preview 2'))];
testObject.add(target);
assert.equal(3, testObject.count());
let actual= testObject.matches();
assert.equal(2, actual.length);
assert.equal('file://c:/1', actual[0].resource().toString());
let actuaMatches= actual[0].matches();
assert.equal(2, actuaMatches.length);
assert.equal('preview 1', actuaMatches[0].text());
assert.ok(new Range(2, 2, 2, 5).equalsRange(actuaMatches[0].range()));
assert.equal('preview 1', actuaMatches[1].text());
assert.ok(new Range(2, 5, 2, 12).equalsRange(actuaMatches[1].range()));
actuaMatches= actual[1].matches();
assert.equal(1, actuaMatches.length);
assert.equal('preview 2', actuaMatches[0].text());
assert.ok(new Range(2, 1, 2, 2).equalsRange(actuaMatches[0].range()));
});
test('Search Result: Dispose disposes matches', function () {
let target1= sinon.spy();
let target2= sinon.spy();
let testObject = aSearchResult();
testObject.add([aRawMatch('file://c:/1', aLineMatch('preview 1')), aRawMatch('file://c:/2', aLineMatch('preview 2'))]);
testObject.matches()[0].onDispose(target1);
testObject.matches()[1].onDispose(target2);
testObject.dispose();
assert.ok(testObject.isEmpty());
assert.ok(target1.calledOnce);
assert.ok(target2.calledOnce);
});
test('Search Result: Removing all line matches and adding back will add file back to result', function () {
let testObject = aSearchResult();
testObject.add([aRawMatch('file://c:/1', aLineMatch('preview 1'))]);
let target= testObject.matches()[0];
let matchToRemove= target.matches()[0];
target.remove(matchToRemove);
assert.ok(testObject.isEmpty());
target.add(matchToRemove, true);
assert.equal(1, testObject.fileCount());
assert.equal(target, testObject.matches()[0]);
});
//// ----- utils
//function lineHasDecorations(model: editor.IModel, lineNumber: number, decorations: { start: number; end: number; }[]): void {
// let lineDecorations:typeof decorations = [];
// let decs = model.getLineDecorations(lineNumber);
// for (let i = 0, len = decs.length; i < len; i++) {
// lineDecorations.push({
// start: decs[i].range.startColumn,
// end: decs[i].range.endColumn
// });
// }
// assert.deepEqual(lineDecorations, decorations);
//}
//
//function lineHasNoDecoration(model: editor.IModel, lineNumber: number): void {
// lineHasDecorations(model, lineNumber, []);
//}
//
//function lineHasDecoration(model: editor.IModel, lineNumber: number, start: number, end: number): void {
// lineHasDecorations(model, lineNumber, [{
// start: start,
// end: end
// }]);
//}
//// ----- end utils
//
//test('Model Highlights', function () {
//
// let fileMatch = instantiation.createInstance(FileMatch, null, toUri('folder\\file.txt'));
// fileMatch.add(new Match(fileMatch, 'line2', 1, 0, 2));
// fileMatch.connect();
// lineHasDecoration(oneModel, 2, 1, 3);
//});
//
//test('Dispose', function () {
//
// let fileMatch = instantiation.createInstance(FileMatch, null, toUri('folder\\file.txt'));
// fileMatch.add(new Match(fileMatch, 'line2', 1, 0, 2));
// fileMatch.connect();
// lineHasDecoration(oneModel, 2, 1, 3);
//
// fileMatch.dispose();
// lineHasNoDecoration(oneModel, 2);
//});
function aFileMatch(path: string, searchResult?: SearchResult, ...lineMatches: ILineMatch[]): FileMatch {
let rawMatch: IFileMatch = {
resource: URI.file('C:\\' + path),
lineMatches: lineMatches
};
return new FileMatch(null, searchResult, rawMatch, null, null);
}
function aSearchResult(): SearchResult {
let searchModel = instantiationService.createInstance(SearchModel);
return searchModel.searchResult;
}
function aRawMatch(resource: string, ...lineMatches: ILineMatch[]): IFileMatch {
return { resource: URI.parse(resource), lineMatches };
}
function aLineMatch(preview: string, lineNumber: number = 1, offsetAndLengths: number[][] = [[0, 1]]): ILineMatch {
return { preview, lineNumber, offsetAndLengths };
}
}); | src/vs/workbench/parts/search/test/common/searchResult.test.ts | 1 | https://github.com/microsoft/vscode/commit/e12eb3dc06b131a8c00fbe61c77ae98311f103e9 | [
0.004547674674540758,
0.0005200349260121584,
0.0001675354433245957,
0.00017882901011034846,
0.001081349910236895
] |
{
"id": 6,
"code_window": [
"\tsetup(() => {\n",
"\t\trestoreStubs= [];\n",
"\t\tinstantiationService= new TestInstantiationService();\n",
"\t\tinstantiationService.stub(ITelemetryService);\n",
"\t});\n",
"\n",
"\tteardown(() => {\n",
"\t\trestoreStubs.forEach(element => {\n",
"\t\t\telement.restore();\n"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\tinstantiationService.stub(IModelService, createMockModelService(instantiationService));\n"
],
"file_path": "src/vs/workbench/parts/search/test/common/searchModel.test.ts",
"type": "add",
"edit_start_line_idx": 28
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
'use strict';
import {IHTMLContentElement} from 'vs/base/common/htmlContent';
import * as strings from 'vs/base/common/strings';
import {IMode, IState, ITokenizationSupport} from 'vs/editor/common/modes';
import {NullState, nullTokenize} from 'vs/editor/common/modes/nullMode';
export function tokenizeToHtmlContent(text: string, mode: IMode): IHTMLContentElement {
return _tokenizeToHtmlContent(text, _getSafeTokenizationSupport(mode));
}
export function tokenizeToString(text: string, mode: IMode, extraTokenClass?: string): string {
return _tokenizeToString(text, _getSafeTokenizationSupport(mode), extraTokenClass);
}
function _getSafeTokenizationSupport(mode: IMode): ITokenizationSupport {
if (mode && mode.tokenizationSupport) {
return mode.tokenizationSupport;
}
return {
getInitialState: () => new NullState(null, null),
tokenize: (buffer:string, state: IState, deltaOffset:number = 0, stopAtOffset?:number) => nullTokenize(null, buffer, state, deltaOffset, stopAtOffset)
};
}
function _tokenizeToHtmlContent(text: string, tokenizationSupport: ITokenizationSupport): IHTMLContentElement {
var result: IHTMLContentElement = {
tagName: 'div',
style: 'white-space: pre-wrap',
children: []
};
var emitToken = (className: string, tokenText: string) => {
result.children.push({
tagName: 'span',
className: className,
text: tokenText
});
};
var emitNewLine = () => {
result.children.push({
tagName: 'br'
});
};
_tokenizeLines(text, tokenizationSupport, emitToken, emitNewLine);
return result;
}
function _tokenizeToString(text: string, tokenizationSupport: ITokenizationSupport, extraTokenClass: string = ''): string {
if (extraTokenClass && extraTokenClass.length > 0) {
extraTokenClass = ' ' + extraTokenClass;
}
var result = '';
var emitToken = (className: string, tokenText: string) => {
result += '<span class="' + className + extraTokenClass + '">' + strings.escape(tokenText) + '</span>';
};
var emitNewLine = () => {
result += '<br/>';
};
result = '<div style="white-space: pre-wrap;">';
_tokenizeLines(text, tokenizationSupport, emitToken, emitNewLine);
result += '</div>';
return result;
}
interface IEmitTokenFunc {
(className: string, innerText: string): void;
}
interface IEmitNewLineFunc {
(): void;
}
function _tokenizeLines(text: string, tokenizationSupport: ITokenizationSupport, emitToken: IEmitTokenFunc, emitNewLine: IEmitNewLineFunc): void {
var lines = text.split(/\r\n|\r|\n/);
var currentState = tokenizationSupport.getInitialState();
for (var i = 0; i < lines.length; i++) {
currentState = _tokenizeLine(lines[i], tokenizationSupport, emitToken, currentState);
// Keep new lines
if (i < lines.length - 1) {
emitNewLine();
}
}
}
function _tokenizeLine(line: string, tokenizationSupport:ITokenizationSupport, emitToken: IEmitTokenFunc, startState: IState): IState {
var tokenized = tokenizationSupport.tokenize(line, startState),
endState = tokenized.endState,
tokens = tokenized.tokens,
offset = 0,
tokenText: string;
// For each token inject spans with proper class names based on token type
for (var j = 0; j < tokens.length; j++) {
var token = tokens[j];
// Tokens only provide a startIndex from where they are valid from. As such, we need to
// look ahead the value of the token by advancing until the next tokens start inex or the
// end of the line.
if (j < tokens.length - 1) {
tokenText = line.substring(offset, tokens[j + 1].startIndex);
offset = tokens[j + 1].startIndex;
} else {
tokenText = line.substr(offset);
}
var className = 'token';
var safeType = token.type.replace(/[^a-z0-9\-]/gi, ' ');
if (safeType.length > 0) {
className += ' ' + safeType;
}
emitToken(className, tokenText);
}
return endState;
}
| src/vs/editor/common/modes/textToHtmlTokenizer.ts | 0 | https://github.com/microsoft/vscode/commit/e12eb3dc06b131a8c00fbe61c77ae98311f103e9 | [
0.00017832043522503227,
0.00017378927441313863,
0.0001664752053329721,
0.0001740972074912861,
0.000003350350880282349
] |
{
"id": 6,
"code_window": [
"\tsetup(() => {\n",
"\t\trestoreStubs= [];\n",
"\t\tinstantiationService= new TestInstantiationService();\n",
"\t\tinstantiationService.stub(ITelemetryService);\n",
"\t});\n",
"\n",
"\tteardown(() => {\n",
"\t\trestoreStubs.forEach(element => {\n",
"\t\t\telement.restore();\n"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\tinstantiationService.stub(IModelService, createMockModelService(instantiationService));\n"
],
"file_path": "src/vs/workbench/parts/search/test/common/searchModel.test.ts",
"type": "add",
"edit_start_line_idx": 28
} | <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16"><style type="text/css">.st0{opacity:0;fill:#F6F6F6;} .st1{fill:#F6F6F6;} .st2{fill:#424242;}</style><g id="outline"><rect class="st0" width="16" height="16"/><path class="st1" d="M14.176 5.592c-.555-.6-1.336-.904-2.322-.904-.258 0-.521.024-.784.072-.246.044-.479.101-.7.169-.228.07-.432.147-.613.229-.22.099-.389.196-.512.284l-.419.299v2.701c-.086.108-.162.223-.229.344l-2.45-6.354h-2.394l-3.753 9.804v.598h3.025l.838-2.35h2.167l.891 2.35h3.237l-.001-.003c.305.092.633.15.993.15.344 0 .671-.049.978-.146h2.853v-4.903c-.001-.975-.271-1.763-.805-2.34z"/></g><g id="icon_x5F_bg"><path class="st2" d="M7.611 11.834l-.891-2.35h-3.562l-.838 2.35h-1.095l3.217-8.402h1.02l3.24 8.402h-1.091zm-2.531-6.814l-.044-.135-.038-.156-.029-.152-.024-.126h-.023l-.021.126-.032.152-.038.156-.044.135-1.307 3.574h2.918l-1.318-3.574z"/><path class="st2" d="M13.02 11.834v-.938h-.023c-.199.352-.456.62-.771.806s-.673.278-1.075.278c-.313 0-.588-.045-.826-.135s-.438-.212-.598-.366-.281-.338-.363-.551-.124-.442-.124-.688c0-.262.039-.502.117-.721s.198-.412.36-.58.367-.308.615-.419.544-.19.888-.237l1.811-.252c0-.273-.029-.507-.088-.7s-.143-.351-.252-.472-.241-.21-.396-.267-.325-.085-.513-.085c-.363 0-.714.064-1.052.193s-.638.31-.904.54v-.984c.082-.059.196-.121.343-.188s.312-.128.495-.185.378-.104.583-.141.407-.056.606-.056c.699 0 1.229.194 1.588.583s.539.942.539 1.661v3.902h-.96zm-1.454-2.83c-.273.035-.498.085-.674.149s-.313.144-.41.237-.165.205-.202.334-.055.276-.055.44c0 .141.025.271.076.393s.124.227.22.316.215.16.357.211.308.076.495.076c.242 0 .465-.045.668-.135s.378-.214.524-.372.261-.344.343-.557.123-.442.123-.688v-.609l-1.465.205z"/></g></svg> | src/vs/base/browser/ui/findinput/case-sensitive.svg | 0 | https://github.com/microsoft/vscode/commit/e12eb3dc06b131a8c00fbe61c77ae98311f103e9 | [
0.00018337041547056288,
0.00018337041547056288,
0.00018337041547056288,
0.00018337041547056288,
0
] |
{
"id": 6,
"code_window": [
"\tsetup(() => {\n",
"\t\trestoreStubs= [];\n",
"\t\tinstantiationService= new TestInstantiationService();\n",
"\t\tinstantiationService.stub(ITelemetryService);\n",
"\t});\n",
"\n",
"\tteardown(() => {\n",
"\t\trestoreStubs.forEach(element => {\n",
"\t\t\telement.restore();\n"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\tinstantiationService.stub(IModelService, createMockModelService(instantiationService));\n"
],
"file_path": "src/vs/workbench/parts/search/test/common/searchModel.test.ts",
"type": "add",
"edit_start_line_idx": 28
} | declare module 'vscode-extension-telemetry' {
export default class TelemetryReporter {
constructor(extensionId: string,extensionVersion: string, key: string);
sendTelemetryEvent(eventName: string, properties?: { [key: string]: string }, measures?: { [key: string]: number }): void;
}
} | extensions/markdown/src/typings/vscode-extension-telemetry.d.ts | 0 | https://github.com/microsoft/vscode/commit/e12eb3dc06b131a8c00fbe61c77ae98311f103e9 | [
0.00019215822976548225,
0.00019215822976548225,
0.00019215822976548225,
0.00019215822976548225,
0
] |
{
"id": 7,
"code_window": [
"import {IFileMatch, ILineMatch} from 'vs/platform/search/common/search';\n",
"import { ITelemetryService } from 'vs/platform/telemetry/common/telemetry';\n",
"import { Range } from 'vs/editor/common/core/range';\n",
"\n",
"suite('SearchResult', () => {\n",
"\n",
"\tlet instantiationService: TestInstantiationService;\n",
"\n"
],
"labels": [
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"import { createMockModelService } from 'vs/test/utils/servicesTestUtils';\n",
"import { IModelService } from 'vs/editor/common/services/modelService';\n"
],
"file_path": "src/vs/workbench/parts/search/test/common/searchResult.test.ts",
"type": "add",
"edit_start_line_idx": 14
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
'use strict';
import * as assert from 'assert';
import uri from 'vs/base/common/uri';
import {Match, FileMatch, SearchResult} from 'vs/workbench/parts/search/common/searchModel';
import { TestInstantiationService } from 'vs/test/utils/instantiationTestUtils';
import {SearchSorter, SearchDataSource} from 'vs/workbench/parts/search/browser/searchResultsView';
import {IFileMatch, ILineMatch} from 'vs/platform/search/common/search';
function aFileMatch(path: string, searchResult?: SearchResult, ...lineMatches: ILineMatch[]): FileMatch {
let rawMatch: IFileMatch= {
resource: uri.file('C:\\' + path),
lineMatches: lineMatches
};
return new FileMatch(null, searchResult, rawMatch, null, null);
}
suite('Search - Viewlet', () => {
let instantiation: TestInstantiationService;
setup(() => {
instantiation = new TestInstantiationService();
});
test('Data Source', function () {
let ds = new SearchDataSource();
let result = instantiation.createInstance(SearchResult, null);
result.add([{
resource: uri.parse('file:///c:/foo'),
lineMatches: [{ lineNumber: 1, preview: 'bar', offsetAndLengths: [[0, 1]] }]
}]);
let fileMatch = result.matches()[0];
let lineMatch = fileMatch.matches()[0];
assert.equal(ds.getId(null, result), 'root');
assert.equal(ds.getId(null, fileMatch), 'file:///c%3A/foo');
assert.equal(ds.getId(null, lineMatch), 'file:///c%3A/foo>1>0');
assert(!ds.hasChildren(null, 'foo'));
assert(ds.hasChildren(null, result));
assert(ds.hasChildren(null, fileMatch));
assert(!ds.hasChildren(null, lineMatch));
});
test('Sorter', function () {
let fileMatch1 = aFileMatch('C:\\foo');
let fileMatch2 = aFileMatch('C:\\with\\path');
let fileMatch3 = aFileMatch('C:\\with\\path\\foo');
let lineMatch1 = new Match(fileMatch1, 'bar', 1, 1, 1);
let lineMatch2 = new Match(fileMatch1, 'bar', 2, 1, 1);
let lineMatch3 = new Match(fileMatch1, 'bar', 2, 1, 1);
let s = new SearchSorter();
assert(s.compare(null, fileMatch1, fileMatch2) < 0);
assert(s.compare(null, fileMatch2, fileMatch1) > 0);
assert(s.compare(null, fileMatch1, fileMatch1) === 0);
assert(s.compare(null, fileMatch2, fileMatch3) < 0);
assert(s.compare(null, lineMatch1, lineMatch2) < 0);
assert(s.compare(null, lineMatch2, lineMatch1) > 0);
assert(s.compare(null, lineMatch2, lineMatch3) === 0);
});
}); | src/vs/workbench/parts/search/test/browser/searchViewlet.test.ts | 1 | https://github.com/microsoft/vscode/commit/e12eb3dc06b131a8c00fbe61c77ae98311f103e9 | [
0.996450662612915,
0.1427154839038849,
0.0001662930881138891,
0.00020560453413054347,
0.3485361337661743
] |
{
"id": 7,
"code_window": [
"import {IFileMatch, ILineMatch} from 'vs/platform/search/common/search';\n",
"import { ITelemetryService } from 'vs/platform/telemetry/common/telemetry';\n",
"import { Range } from 'vs/editor/common/core/range';\n",
"\n",
"suite('SearchResult', () => {\n",
"\n",
"\tlet instantiationService: TestInstantiationService;\n",
"\n"
],
"labels": [
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"import { createMockModelService } from 'vs/test/utils/servicesTestUtils';\n",
"import { IModelService } from 'vs/editor/common/services/modelService';\n"
],
"file_path": "src/vs/workbench/parts/search/test/common/searchResult.test.ts",
"type": "add",
"edit_start_line_idx": 14
} | {
} | extensions/vscode-api-tests/testWorkspace/bower.json | 0 | https://github.com/microsoft/vscode/commit/e12eb3dc06b131a8c00fbe61c77ae98311f103e9 | [
0.0001752639509504661,
0.0001752639509504661,
0.0001752639509504661,
0.0001752639509504661,
0
] |
{
"id": 7,
"code_window": [
"import {IFileMatch, ILineMatch} from 'vs/platform/search/common/search';\n",
"import { ITelemetryService } from 'vs/platform/telemetry/common/telemetry';\n",
"import { Range } from 'vs/editor/common/core/range';\n",
"\n",
"suite('SearchResult', () => {\n",
"\n",
"\tlet instantiationService: TestInstantiationService;\n",
"\n"
],
"labels": [
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"import { createMockModelService } from 'vs/test/utils/servicesTestUtils';\n",
"import { IModelService } from 'vs/editor/common/services/modelService';\n"
],
"file_path": "src/vs/workbench/parts/search/test/common/searchResult.test.ts",
"type": "add",
"edit_start_line_idx": 14
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
// Do not edit this file. It is machine generated.
{
"outputPanelAriaLabel": "輸出面板",
"outputPanelWithInputAriaLabel": "{0},輸出面板"
} | i18n/cht/src/vs/workbench/parts/output/browser/outputPanel.i18n.json | 0 | https://github.com/microsoft/vscode/commit/e12eb3dc06b131a8c00fbe61c77ae98311f103e9 | [
0.000175309760379605,
0.000175309760379605,
0.000175309760379605,
0.000175309760379605,
0
] |
{
"id": 7,
"code_window": [
"import {IFileMatch, ILineMatch} from 'vs/platform/search/common/search';\n",
"import { ITelemetryService } from 'vs/platform/telemetry/common/telemetry';\n",
"import { Range } from 'vs/editor/common/core/range';\n",
"\n",
"suite('SearchResult', () => {\n",
"\n",
"\tlet instantiationService: TestInstantiationService;\n",
"\n"
],
"labels": [
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"import { createMockModelService } from 'vs/test/utils/servicesTestUtils';\n",
"import { IModelService } from 'vs/editor/common/services/modelService';\n"
],
"file_path": "src/vs/workbench/parts/search/test/common/searchResult.test.ts",
"type": "add",
"edit_start_line_idx": 14
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
'use strict';
import * as assert from 'assert';
import { guessMimeTypes, registerTextMime } from 'vs/base/common/mime';
suite('Mime', () => {
test('Dynamically Register Text Mime', () => {
var guess = guessMimeTypes('foo.monaco');
assert.deepEqual(guess, ['application/unknown']);
registerTextMime({ extension: '.monaco', mime: 'text/monaco' });
guess = guessMimeTypes('foo.monaco');
assert.deepEqual(guess, ['text/monaco', 'text/plain']);
guess = guessMimeTypes('.monaco');
assert.deepEqual(guess, ['text/monaco', 'text/plain']);
registerTextMime({ filename: 'Codefile', mime: 'text/code' });
guess = guessMimeTypes('Codefile');
assert.deepEqual(guess, ['text/code', 'text/plain']);
guess = guessMimeTypes('foo.Codefile');
assert.deepEqual(guess, ['application/unknown']);
registerTextMime({ filepattern: 'Docker*', mime: 'text/docker' });
guess = guessMimeTypes('Docker-debug');
assert.deepEqual(guess, ['text/docker', 'text/plain']);
guess = guessMimeTypes('docker-PROD');
assert.deepEqual(guess, ['text/docker', 'text/plain']);
registerTextMime({ mime: 'text/nice-regex', firstline: /RegexesAreNice/ });
guess = guessMimeTypes('Randomfile.noregistration', 'RegexesAreNice');
assert.deepEqual(guess, ['text/nice-regex', 'text/plain']);
guess = guessMimeTypes('Randomfile.noregistration', 'RegexesAreNiceee');
assert.deepEqual(guess, ['application/unknown']);
guess = guessMimeTypes('Codefile', 'RegexesAreNice');
assert.deepEqual(guess, ['text/code', 'text/plain']);
});
test('Mimes Priority', () => {
registerTextMime({ extension: '.monaco', mime: 'text/monaco' });
registerTextMime({ mime: 'text/foobar', firstline: /foobar/ });
var guess = guessMimeTypes('foo.monaco');
assert.deepEqual(guess, ['text/monaco', 'text/plain']);
guess = guessMimeTypes('foo.monaco', 'foobar');
assert.deepEqual(guess, ['text/monaco', 'text/plain']);
registerTextMime({ filename: 'dockerfile', mime: 'text/winner' });
registerTextMime({ filepattern: 'dockerfile*', mime: 'text/looser' });
guess = guessMimeTypes('dockerfile');
assert.deepEqual(guess, ['text/winner', 'text/plain']);
});
test('Specificity priority 1', () => {
registerTextMime({ extension: '.monaco2', mime: 'text/monaco2' });
registerTextMime({ filename: 'specific.monaco2', mime: 'text/specific-monaco2' });
assert.deepEqual(guessMimeTypes('specific.monaco2'), ['text/specific-monaco2', 'text/plain']);
assert.deepEqual(guessMimeTypes('foo.monaco2'), ['text/monaco2', 'text/plain']);
});
test('Specificity priority 2', () => {
registerTextMime({ filename: 'specific.monaco3', mime: 'text/specific-monaco3' });
registerTextMime({ extension: '.monaco3', mime: 'text/monaco3' });
assert.deepEqual(guessMimeTypes('specific.monaco3'), ['text/specific-monaco3', 'text/plain']);
assert.deepEqual(guessMimeTypes('foo.monaco3'), ['text/monaco3', 'text/plain']);
});
test('Mimes Priority - Longest Extension wins', () => {
registerTextMime({ extension: '.monaco', mime: 'text/monaco' });
registerTextMime({ extension: '.monaco.xml', mime: 'text/monaco-xml' });
registerTextMime({ extension: '.monaco.xml.build', mime: 'text/monaco-xml-build' });
var guess = guessMimeTypes('foo.monaco');
assert.deepEqual(guess, ['text/monaco', 'text/plain']);
guess = guessMimeTypes('foo.monaco.xml');
assert.deepEqual(guess, ['text/monaco-xml', 'text/plain']);
guess = guessMimeTypes('foo.monaco.xml.build');
assert.deepEqual(guess, ['text/monaco-xml-build', 'text/plain']);
});
test('Mimes Priority - User configured wins', () => {
registerTextMime({ extension: '.monaco.xnl', mime: 'text/monaco', userConfigured: true });
registerTextMime({ extension: '.monaco.xml', mime: 'text/monaco-xml' });
var guess = guessMimeTypes('foo.monaco.xnl');
assert.deepEqual(guess, ['text/monaco', 'text/plain']);
});
test('Mimes Priority - Pattern matches on path if specified', () => {
registerTextMime({ filepattern: '**/dot.monaco.xml', mime: 'text/monaco' });
registerTextMime({ filepattern: '*ot.other.xml', mime: 'text/other' });
var guess = guessMimeTypes('/some/path/dot.monaco.xml');
assert.deepEqual(guess, ['text/monaco', 'text/plain']);
});
});
| src/vs/base/test/common/mime.test.ts | 0 | https://github.com/microsoft/vscode/commit/e12eb3dc06b131a8c00fbe61c77ae98311f103e9 | [
0.00018014476518146694,
0.00017713129636831582,
0.0001700814755167812,
0.00017777123139239848,
0.000002704459348024102
] |
{
"id": 8,
"code_window": [
"\tsetup(() => {\n",
"\t\tinstantiationService= new TestInstantiationService();\n",
"\t\tinstantiationService.stub(ITelemetryService);\n",
"\t});\n",
"\n",
"\ttest('Line Match', function () {\n"
],
"labels": [
"keep",
"keep",
"add",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\tinstantiationService.stub(IModelService, createMockModelService(instantiationService));\n"
],
"file_path": "src/vs/workbench/parts/search/test/common/searchResult.test.ts",
"type": "add",
"edit_start_line_idx": 22
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
'use strict';
import * as assert from 'assert';
import * as sinon from 'sinon';
import { TestInstantiationService } from 'vs/test/utils/instantiationTestUtils';
import { DeferredPPromise } from 'vs/test/utils/promiseTestUtils';
import { PPromise } from 'vs/base/common/winjs.base';
import { nullEvent } from 'vs/base/common/timer';
import { SearchModel } from 'vs/workbench/parts/search/common/searchModel';
import URI from 'vs/base/common/uri';
import {IFileMatch, ILineMatch} from 'vs/platform/search/common/search';
import { ITelemetryService } from 'vs/platform/telemetry/common/telemetry';
import { ISearchService, ISearchComplete, ISearchProgressItem } from 'vs/platform/search/common/search';
import { Range } from 'vs/editor/common/core/range';
suite('SearchModel', () => {
let instantiationService: TestInstantiationService;
let restoreStubs;
setup(() => {
restoreStubs= [];
instantiationService= new TestInstantiationService();
instantiationService.stub(ITelemetryService);
});
teardown(() => {
restoreStubs.forEach(element => {
element.restore();
});
});
test('Search Model: Search adds to results', function () {
let results= [aRawMatch('file://c:/1', aLineMatch('preview 1', 1, [[1, 3], [4, 7]])), aRawMatch('file://c:/2', aLineMatch('preview 2'))];
instantiationService.stub(ISearchService, 'search', PPromise.as({results: results}));
let testObject= instantiationService.createInstance(SearchModel);
testObject.search({contentPattern: {pattern: 'somestring'}, type: 1});
let actual= testObject.searchResult.matches();
assert.equal(2, actual.length);
assert.equal('file://c:/1', actual[0].resource().toString());
let actuaMatches= actual[0].matches();
assert.equal(2, actuaMatches.length);
assert.equal('preview 1', actuaMatches[0].text());
assert.ok(new Range(2, 2, 2, 5).equalsRange(actuaMatches[0].range()));
assert.equal('preview 1', actuaMatches[1].text());
assert.ok(new Range(2, 5, 2, 12).equalsRange(actuaMatches[1].range()));
actuaMatches= actual[1].matches();
assert.equal(1, actuaMatches.length);
assert.equal('preview 2', actuaMatches[0].text());
assert.ok(new Range(2, 1, 2, 2).equalsRange(actuaMatches[0].range()));
});
test('Search Model: Search adds to results during progress', function (done) {
let results= [aRawMatch('file://c:/1', aLineMatch('preview 1', 1, [[1, 3], [4, 7]])), aRawMatch('file://c:/2', aLineMatch('preview 2'))];
let promise= new DeferredPPromise<ISearchComplete, ISearchProgressItem>();
instantiationService.stub(ISearchService, 'search', promise);
let testObject= instantiationService.createInstance(SearchModel);
let result= testObject.search({contentPattern: {pattern: 'somestring'}, type: 1});
promise.progress(results[0]);
promise.progress(results[1]);
promise.complete({results: []});
result.done(() => {
let actual= testObject.searchResult.matches();
assert.equal(2, actual.length);
assert.equal('file://c:/1', actual[0].resource().toString());
let actuaMatches= actual[0].matches();
assert.equal(2, actuaMatches.length);
assert.equal('preview 1', actuaMatches[0].text());
assert.ok(new Range(2, 2, 2, 5).equalsRange(actuaMatches[0].range()));
assert.equal('preview 1', actuaMatches[1].text());
assert.ok(new Range(2, 5, 2, 12).equalsRange(actuaMatches[1].range()));
actuaMatches= actual[1].matches();
assert.equal(1, actuaMatches.length);
assert.equal('preview 2', actuaMatches[0].text());
assert.ok(new Range(2, 1, 2, 2).equalsRange(actuaMatches[0].range()));
done();
});
});
test('Search Model: Search reports telemetry on search completed', function () {
let target= instantiationService.spy(ITelemetryService, 'publicLog');
let results= [aRawMatch('file://c:/1', aLineMatch('preview 1', 1, [[1, 3], [4, 7]])), aRawMatch('file://c:/2', aLineMatch('preview 2'))];
instantiationService.stub(ISearchService, 'search', PPromise.as({results: results}));
let testObject= instantiationService.createInstance(SearchModel);
testObject.search({contentPattern: {pattern: 'somestring'}, type: 1});
assert.ok(target.calledOnce);
assert.deepEqual(['searchResultsShown', {count: 3, fileCount: 2}], target.args[0]);
});
test('Search Model: Search reports timed telemetry on search when progress is not called', function () {
let target2= sinon.spy();
stub(nullEvent, 'stop', target2);
let target1= sinon.stub().returns(nullEvent);
instantiationService.stub(ITelemetryService, 'timedPublicLog', target1);
instantiationService.stub(ISearchService, 'search', PPromise.as({results: []}));
let testObject= instantiationService.createInstance(SearchModel);
testObject.search({contentPattern: {pattern: 'somestring'}, type: 1});
assert.ok(target1.calledTwice);
assert.ok(target1.calledWith('searchResultsFirstRender'));
assert.ok(target1.calledWith('searchResultsFinished'));
assert.ok(target2.calledThrice);
});
test('Search Model: Search reports timed telemetry on search when progress is called', function (done) {
let target2= sinon.spy();
stub(nullEvent, 'stop', target2);
let target1= sinon.stub().returns(nullEvent);
instantiationService.stub(ITelemetryService, 'timedPublicLog', target1);
let promise= new DeferredPPromise<ISearchComplete, ISearchProgressItem>();
instantiationService.stub(ISearchService, 'search', promise);
let testObject= instantiationService.createInstance(SearchModel);
let result= testObject.search({contentPattern: {pattern: 'somestring'}, type: 1});
promise.progress(aRawMatch('file://c:/1', aLineMatch('some preview')));
promise.complete({results: []});
result.done(() => {
assert.ok(target1.calledTwice);
assert.ok(target1.calledWith('searchResultsFirstRender'));
assert.ok(target1.calledWith('searchResultsFinished'));
assert.equal(4, target2.callCount);
done();
});
});
test('Search Model: Search reports timed telemetry on search when error is called', function (done) {
let target2= sinon.spy();
stub(nullEvent, 'stop', target2);
let target1= sinon.stub().returns(nullEvent);
instantiationService.stub(ITelemetryService, 'timedPublicLog', target1);
let promise= new DeferredPPromise<ISearchComplete, ISearchProgressItem>();
instantiationService.stub(ISearchService, 'search', promise);
let testObject= instantiationService.createInstance(SearchModel);
let result= testObject.search({contentPattern: {pattern: 'somestring'}, type: 1});
promise.error('error');
result.done(() => {}, () => {
assert.ok(target1.calledTwice);
assert.ok(target1.calledWith('searchResultsFirstRender'));
assert.ok(target1.calledWith('searchResultsFinished'));
assert.ok(target2.calledThrice);
done();
});
});
test('Search Model: Search reports timed telemetry on search when error is cancelled error', function (done) {
let target2= sinon.spy();
stub(nullEvent, 'stop', target2);
let target1= sinon.stub().returns(nullEvent);
instantiationService.stub(ITelemetryService, 'timedPublicLog', target1);
let promise= new DeferredPPromise<ISearchComplete, ISearchProgressItem>();
instantiationService.stub(ISearchService, 'search', promise);
let testObject= instantiationService.createInstance(SearchModel);
let result= testObject.search({contentPattern: {pattern: 'somestring'}, type: 1});
promise.cancel();
result.done(() => {}, () => {
assert.ok(target1.calledTwice);
assert.ok(target1.calledWith('searchResultsFirstRender'));
assert.ok(target1.calledWith('searchResultsFinished'));
assert.ok(target2.calledThrice);
done();
});
});
test('Search Model: Search results are cleared during search', function () {
let results= [aRawMatch('file://c:/1', aLineMatch('preview 1', 1, [[1, 3], [4, 7]])), aRawMatch('file://c:/2', aLineMatch('preview 2'))];
instantiationService.stub(ISearchService, 'search', PPromise.as({results: results}));
let testObject:SearchModel= instantiationService.createInstance(SearchModel);
testObject.search({contentPattern: {pattern: 'somestring'}, type: 1});
assert.ok(!testObject.searchResult.isEmpty());
instantiationService.stub(ISearchService, 'search', new DeferredPPromise<ISearchComplete, ISearchProgressItem>());
testObject.search({contentPattern: {pattern: 'somestring'}, type: 1});
assert.ok(testObject.searchResult.isEmpty());
});
test('Search Model: Previous search is cancelled when new search is called', function () {
let target= sinon.spy();
instantiationService.stub(ISearchService, 'search', new DeferredPPromise((c, e, p) => {}, target));
let testObject:SearchModel= instantiationService.createInstance(SearchModel);
testObject.search({contentPattern: {pattern: 'somestring'}, type: 1});
instantiationService.stub(ISearchService, 'search', new DeferredPPromise<ISearchComplete, ISearchProgressItem>());
testObject.search({contentPattern: {pattern: 'somestring'}, type: 1});
assert.ok(target.calledOnce);
});
test('Search Model: isReplaceActive return false if no replace text is set', function () {
let testObject:SearchModel= instantiationService.createInstance(SearchModel);
assert.ok(!testObject.isReplaceActive());
});
test('Search Model: isReplaceActive return false if replace text is set to null', function () {
let testObject:SearchModel= instantiationService.createInstance(SearchModel);
testObject.replaceText= null;
assert.ok(!testObject.isReplaceActive());
});
test('Search Model: isReplaceActive return false if replace text is set to undefined', function () {
let testObject:SearchModel= instantiationService.createInstance(SearchModel);
testObject.replaceText= void 0;
assert.ok(!testObject.isReplaceActive());
});
test('Search Model: isReplaceActive return true if replace text is set to empty string', function () {
let testObject:SearchModel= instantiationService.createInstance(SearchModel);
testObject.replaceText= '';
assert.ok(testObject.isReplaceActive());
});
test('Search Model: isReplaceActive return true if replace text is set to non empty string', function () {
let testObject:SearchModel= instantiationService.createInstance(SearchModel);
testObject.replaceText= 'some value';
assert.ok(testObject.isReplaceActive());
});
test('Search Model: hasReplaceText return false if no replace text is set', function () {
let testObject:SearchModel= instantiationService.createInstance(SearchModel);
assert.ok(!testObject.hasReplaceText());
});
test('Search Model: hasReplaceText return false if replace text is set to null', function () {
let testObject:SearchModel= instantiationService.createInstance(SearchModel);
testObject.replaceText= null;
assert.ok(!testObject.hasReplaceText());
});
test('Search Model: hasReplaceText return false if replace text is set to undefined', function () {
let testObject:SearchModel= instantiationService.createInstance(SearchModel);
testObject.replaceText= void 0;
assert.ok(!testObject.hasReplaceText());
});
test('Search Model: hasReplaceText return false if replace text is set to empty string', function () {
let testObject:SearchModel= instantiationService.createInstance(SearchModel);
testObject.replaceText= '';
assert.ok(!testObject.hasReplaceText());
});
test('Search Model: hasReplaceText return true if replace text is set to non empty string', function () {
let testObject:SearchModel= instantiationService.createInstance(SearchModel);
testObject.replaceText= 'some value';
assert.ok(testObject.hasReplaceText());
});
function aRawMatch(resource: string, ...lineMatches: ILineMatch[]): IFileMatch {
return { resource: URI.parse(resource), lineMatches };
}
function aLineMatch(preview: string, lineNumber: number = 1, offsetAndLengths: number[][] = [[0, 1]]): ILineMatch {
return { preview, lineNumber, offsetAndLengths };
}
function stub(arg1, arg2, arg3) : sinon.SinonStub {
const stub= sinon.stub(arg1, arg2, arg3);
restoreStubs.push(stub);
return stub;
}
}); | src/vs/workbench/parts/search/test/common/searchModel.test.ts | 1 | https://github.com/microsoft/vscode/commit/e12eb3dc06b131a8c00fbe61c77ae98311f103e9 | [
0.6050094366073608,
0.02293023094534874,
0.00016688843606971204,
0.0005788043490611017,
0.10683675110340118
] |
{
"id": 8,
"code_window": [
"\tsetup(() => {\n",
"\t\tinstantiationService= new TestInstantiationService();\n",
"\t\tinstantiationService.stub(ITelemetryService);\n",
"\t});\n",
"\n",
"\ttest('Line Match', function () {\n"
],
"labels": [
"keep",
"keep",
"add",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\tinstantiationService.stub(IModelService, createMockModelService(instantiationService));\n"
],
"file_path": "src/vs/workbench/parts/search/test/common/searchResult.test.ts",
"type": "add",
"edit_start_line_idx": 22
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
// Do not edit this file. It is machine generated.
{
"fileLink": "Fare clic per aprire (CTRL+clic apre lateralmente)",
"fileLinkMac": "Fare clic per aprire (CMD+clic apre lateralmente)",
"replExpressionAriaLabel": "Il valore dell'espressione {0} è {1}, Read Eval Print Loop, debug",
"replKeyValueOutputAriaLabel": "Il valore della variabile di output {0} è {1}, Read Eval Print Loop, debug",
"replValueOutputAriaLabel": "{0}, Read Eval Print Loop, debug",
"replVariableAriaLabel": "Il valore della variabile {0} è {1}, Read Eval Print Loop, debug",
"stateCapture": "Lo stato dell'oggetto viene acquisito dalla prima valutazione"
} | i18n/ita/src/vs/workbench/parts/debug/browser/replViewer.i18n.json | 0 | https://github.com/microsoft/vscode/commit/e12eb3dc06b131a8c00fbe61c77ae98311f103e9 | [
0.00017431631567887962,
0.00017109009786508977,
0.00016786388005129993,
0.00017109009786508977,
0.0000032262178137898445
] |
{
"id": 8,
"code_window": [
"\tsetup(() => {\n",
"\t\tinstantiationService= new TestInstantiationService();\n",
"\t\tinstantiationService.stub(ITelemetryService);\n",
"\t});\n",
"\n",
"\ttest('Line Match', function () {\n"
],
"labels": [
"keep",
"keep",
"add",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\tinstantiationService.stub(IModelService, createMockModelService(instantiationService));\n"
],
"file_path": "src/vs/workbench/parts/search/test/common/searchResult.test.ts",
"type": "add",
"edit_start_line_idx": 22
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
'use strict';
import {TPromise} from 'vs/base/common/winjs.base';
import {isMacintosh} from 'vs/base/common/platform';
import {isFunction} from 'vs/base/common/types';
import {Action} from 'vs/base/common/actions';
import {DropdownMenu, IDropdownMenuOptions} from 'vs/base/browser/ui/dropdown/dropdown';
export interface ILinksDropdownMenuOptions extends IDropdownMenuOptions {
tooltip: string;
}
export class LinksDropdownMenu extends DropdownMenu {
constructor(container: HTMLElement, options: ILinksDropdownMenuOptions) {
super(container, options);
this.tooltip = options.tooltip;
}
/*protected*/ public onEvent(e: Event, activeElement: HTMLElement): void {
if (e instanceof KeyboardEvent && ((<KeyboardEvent>e).ctrlKey || (isMacintosh && (<KeyboardEvent>e).metaKey))) {
return; // allow to use Ctrl/Meta in workspace dropdown menu
}
this.hide();
}
}
export class LinkDropdownAction extends Action {
constructor(id: string, name: string, clazz: string, url: () => string, forceOpenInNewTab?: boolean);
constructor(id: string, name: string, clazz: string, url: string, forceOpenInNewTab?: boolean);
constructor(id: string, name: string, clazz: string, url: any, forceOpenInNewTab?: boolean) {
super(id, name, clazz, true, (e: Event) => {
let urlString = url;
if (isFunction(url)) {
urlString = url();
}
if (forceOpenInNewTab || (e instanceof MouseEvent && ((<MouseEvent>e).ctrlKey || (isMacintosh && (<MouseEvent>e).metaKey)))) {
window.open(urlString, '_blank');
} else {
window.location.href = urlString;
}
return TPromise.as(true);
});
}
} | src/vs/base/browser/ui/dropdown/linksDropdown.ts | 0 | https://github.com/microsoft/vscode/commit/e12eb3dc06b131a8c00fbe61c77ae98311f103e9 | [
0.00017723911150824279,
0.00017328957619611174,
0.00016914652951527387,
0.00017332262359559536,
0.0000028186584586364916
] |
{
"id": 8,
"code_window": [
"\tsetup(() => {\n",
"\t\tinstantiationService= new TestInstantiationService();\n",
"\t\tinstantiationService.stub(ITelemetryService);\n",
"\t});\n",
"\n",
"\ttest('Line Match', function () {\n"
],
"labels": [
"keep",
"keep",
"add",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\tinstantiationService.stub(IModelService, createMockModelService(instantiationService));\n"
],
"file_path": "src/vs/workbench/parts/search/test/common/searchResult.test.ts",
"type": "add",
"edit_start_line_idx": 22
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
// Do not edit this file. It is machine generated.
{
"extensions": "Erweiterungen"
} | i18n/deu/src/vs/platform/extensionManagement/common/extensionManagement.i18n.json | 0 | https://github.com/microsoft/vscode/commit/e12eb3dc06b131a8c00fbe61c77ae98311f103e9 | [
0.00017878452490549535,
0.00017878452490549535,
0.00017878452490549535,
0.00017878452490549535,
0
] |
{
"id": 9,
"code_window": [
"\t});\n",
"\n",
"\ttest('Line Match', function () {\n",
"\t\tlet fileMatch = aFileMatch('folder\\\\file.txt');\n",
"\t\tlet lineMatch = new Match(fileMatch, 'foo bar', 1, 0, 3);\n",
"\t\tassert.equal(lineMatch.text(), 'foo bar');\n",
"\t\tassert.equal(lineMatch.range().startLineNumber, 2);\n",
"\t\tassert.equal(lineMatch.range().endLineNumber, 2);\n",
"\t\tassert.equal(lineMatch.range().startColumn, 1);\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\tlet fileMatch = aFileMatch('folder\\\\file.txt', null);\n"
],
"file_path": "src/vs/workbench/parts/search/test/common/searchResult.test.ts",
"type": "replace",
"edit_start_line_idx": 25
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
'use strict';
import * as assert from 'assert';
import * as sinon from 'sinon';
import { TestInstantiationService } from 'vs/test/utils/instantiationTestUtils';
import { Match, FileMatch, SearchResult, SearchModel } from 'vs/workbench/parts/search/common/searchModel';
import URI from 'vs/base/common/uri';
import {IFileMatch, ILineMatch} from 'vs/platform/search/common/search';
import { ITelemetryService } from 'vs/platform/telemetry/common/telemetry';
import { Range } from 'vs/editor/common/core/range';
suite('SearchResult', () => {
let instantiationService: TestInstantiationService;
setup(() => {
instantiationService= new TestInstantiationService();
instantiationService.stub(ITelemetryService);
});
test('Line Match', function () {
let fileMatch = aFileMatch('folder\\file.txt');
let lineMatch = new Match(fileMatch, 'foo bar', 1, 0, 3);
assert.equal(lineMatch.text(), 'foo bar');
assert.equal(lineMatch.range().startLineNumber, 2);
assert.equal(lineMatch.range().endLineNumber, 2);
assert.equal(lineMatch.range().startColumn, 1);
assert.equal(lineMatch.range().endColumn, 4);
});
test('Line Match - Remove', function () {
let fileMatch = aFileMatch('folder\\file.txt', null, ...[{
preview: 'foo bar',
lineNumber: 1,
offsetAndLengths: [[0, 3]]
}]);
let lineMatch = fileMatch.matches()[0];
fileMatch.remove(lineMatch);
assert.equal(fileMatch.matches().length, 0);
});
test('File Match', function () {
let fileMatch = aFileMatch('folder\\file.txt');
assert.equal(fileMatch.matches(), 0);
assert.equal(fileMatch.resource().toString(), 'file:///c%3A/folder/file.txt');
assert.equal(fileMatch.name(), 'file.txt');
fileMatch = aFileMatch('file.txt');
assert.equal(fileMatch.matches(), 0);
assert.equal(fileMatch.resource().toString(), 'file:///c%3A/file.txt');
assert.equal(fileMatch.name(), 'file.txt');
});
test('Alle Drei Zusammen', function () {
let searchResult = instantiationService.createInstance(SearchResult, null);
let fileMatch = aFileMatch('far\\boo', searchResult);
let lineMatch = new Match(fileMatch, 'foo bar', 1, 0, 3);
assert(lineMatch.parent() === fileMatch);
assert(fileMatch.parent() === searchResult);
});
test('Search Result: Adding a raw match will add a file match with line matches', function () {
let testObject = aSearchResult();
let target= [aRawMatch('file://c:/', aLineMatch('preview 1', 1, [[1, 3], [4, 7]]), aLineMatch('preview 2'))];
testObject.add(target);
assert.equal(3, testObject.count());
let actual= testObject.matches();
assert.equal(1, actual.length);
assert.equal('file://c:/', actual[0].resource().toString());
let actuaMatches= actual[0].matches();
assert.equal(3, actuaMatches.length);
assert.equal('preview 1', actuaMatches[0].text());
assert.ok(new Range(2, 2, 2, 5).equalsRange(actuaMatches[0].range()));
assert.equal('preview 1', actuaMatches[1].text());
assert.ok(new Range(2, 5, 2, 12).equalsRange(actuaMatches[1].range()));
assert.equal('preview 2', actuaMatches[2].text());
assert.ok(new Range(2, 1, 2, 2).equalsRange(actuaMatches[2].range()));
});
test('Search Result: Adding multiple raw matches', function () {
let testObject = aSearchResult();
let target= [aRawMatch('file://c:/1', aLineMatch('preview 1', 1, [[1, 3], [4, 7]])), aRawMatch('file://c:/2', aLineMatch('preview 2'))];
testObject.add(target);
assert.equal(3, testObject.count());
let actual= testObject.matches();
assert.equal(2, actual.length);
assert.equal('file://c:/1', actual[0].resource().toString());
let actuaMatches= actual[0].matches();
assert.equal(2, actuaMatches.length);
assert.equal('preview 1', actuaMatches[0].text());
assert.ok(new Range(2, 2, 2, 5).equalsRange(actuaMatches[0].range()));
assert.equal('preview 1', actuaMatches[1].text());
assert.ok(new Range(2, 5, 2, 12).equalsRange(actuaMatches[1].range()));
actuaMatches= actual[1].matches();
assert.equal(1, actuaMatches.length);
assert.equal('preview 2', actuaMatches[0].text());
assert.ok(new Range(2, 1, 2, 2).equalsRange(actuaMatches[0].range()));
});
test('Search Result: Dispose disposes matches', function () {
let target1= sinon.spy();
let target2= sinon.spy();
let testObject = aSearchResult();
testObject.add([aRawMatch('file://c:/1', aLineMatch('preview 1')), aRawMatch('file://c:/2', aLineMatch('preview 2'))]);
testObject.matches()[0].onDispose(target1);
testObject.matches()[1].onDispose(target2);
testObject.dispose();
assert.ok(testObject.isEmpty());
assert.ok(target1.calledOnce);
assert.ok(target2.calledOnce);
});
test('Search Result: Removing all line matches and adding back will add file back to result', function () {
let testObject = aSearchResult();
testObject.add([aRawMatch('file://c:/1', aLineMatch('preview 1'))]);
let target= testObject.matches()[0];
let matchToRemove= target.matches()[0];
target.remove(matchToRemove);
assert.ok(testObject.isEmpty());
target.add(matchToRemove, true);
assert.equal(1, testObject.fileCount());
assert.equal(target, testObject.matches()[0]);
});
//// ----- utils
//function lineHasDecorations(model: editor.IModel, lineNumber: number, decorations: { start: number; end: number; }[]): void {
// let lineDecorations:typeof decorations = [];
// let decs = model.getLineDecorations(lineNumber);
// for (let i = 0, len = decs.length; i < len; i++) {
// lineDecorations.push({
// start: decs[i].range.startColumn,
// end: decs[i].range.endColumn
// });
// }
// assert.deepEqual(lineDecorations, decorations);
//}
//
//function lineHasNoDecoration(model: editor.IModel, lineNumber: number): void {
// lineHasDecorations(model, lineNumber, []);
//}
//
//function lineHasDecoration(model: editor.IModel, lineNumber: number, start: number, end: number): void {
// lineHasDecorations(model, lineNumber, [{
// start: start,
// end: end
// }]);
//}
//// ----- end utils
//
//test('Model Highlights', function () {
//
// let fileMatch = instantiation.createInstance(FileMatch, null, toUri('folder\\file.txt'));
// fileMatch.add(new Match(fileMatch, 'line2', 1, 0, 2));
// fileMatch.connect();
// lineHasDecoration(oneModel, 2, 1, 3);
//});
//
//test('Dispose', function () {
//
// let fileMatch = instantiation.createInstance(FileMatch, null, toUri('folder\\file.txt'));
// fileMatch.add(new Match(fileMatch, 'line2', 1, 0, 2));
// fileMatch.connect();
// lineHasDecoration(oneModel, 2, 1, 3);
//
// fileMatch.dispose();
// lineHasNoDecoration(oneModel, 2);
//});
function aFileMatch(path: string, searchResult?: SearchResult, ...lineMatches: ILineMatch[]): FileMatch {
let rawMatch: IFileMatch = {
resource: URI.file('C:\\' + path),
lineMatches: lineMatches
};
return new FileMatch(null, searchResult, rawMatch, null, null);
}
function aSearchResult(): SearchResult {
let searchModel = instantiationService.createInstance(SearchModel);
return searchModel.searchResult;
}
function aRawMatch(resource: string, ...lineMatches: ILineMatch[]): IFileMatch {
return { resource: URI.parse(resource), lineMatches };
}
function aLineMatch(preview: string, lineNumber: number = 1, offsetAndLengths: number[][] = [[0, 1]]): ILineMatch {
return { preview, lineNumber, offsetAndLengths };
}
}); | src/vs/workbench/parts/search/test/common/searchResult.test.ts | 1 | https://github.com/microsoft/vscode/commit/e12eb3dc06b131a8c00fbe61c77ae98311f103e9 | [
0.9984868764877319,
0.3076193034648895,
0.00016543493256904185,
0.0014190832152962685,
0.4391114413738251
] |
{
"id": 9,
"code_window": [
"\t});\n",
"\n",
"\ttest('Line Match', function () {\n",
"\t\tlet fileMatch = aFileMatch('folder\\\\file.txt');\n",
"\t\tlet lineMatch = new Match(fileMatch, 'foo bar', 1, 0, 3);\n",
"\t\tassert.equal(lineMatch.text(), 'foo bar');\n",
"\t\tassert.equal(lineMatch.range().startLineNumber, 2);\n",
"\t\tassert.equal(lineMatch.range().endLineNumber, 2);\n",
"\t\tassert.equal(lineMatch.range().startColumn, 1);\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\tlet fileMatch = aFileMatch('folder\\\\file.txt', null);\n"
],
"file_path": "src/vs/workbench/parts/search/test/common/searchResult.test.ts",
"type": "replace",
"edit_start_line_idx": 25
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
// Do not edit this file. It is machine generated.
{
"mutlicursor.insertAbove": "在上面添加光标",
"mutlicursor.insertAtEndOfEachLineSelected": "从所选行创建多个光标",
"mutlicursor.insertBelow": "在下面添加光标"
} | i18n/chs/src/vs/editor/contrib/multicursor/common/multicursor.i18n.json | 0 | https://github.com/microsoft/vscode/commit/e12eb3dc06b131a8c00fbe61c77ae98311f103e9 | [
0.00017495424253866076,
0.00017304671928286552,
0.0001711392105789855,
0.00017304671928286552,
0.0000019075159798376262
] |
{
"id": 9,
"code_window": [
"\t});\n",
"\n",
"\ttest('Line Match', function () {\n",
"\t\tlet fileMatch = aFileMatch('folder\\\\file.txt');\n",
"\t\tlet lineMatch = new Match(fileMatch, 'foo bar', 1, 0, 3);\n",
"\t\tassert.equal(lineMatch.text(), 'foo bar');\n",
"\t\tassert.equal(lineMatch.range().startLineNumber, 2);\n",
"\t\tassert.equal(lineMatch.range().endLineNumber, 2);\n",
"\t\tassert.equal(lineMatch.range().startColumn, 1);\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\tlet fileMatch = aFileMatch('folder\\\\file.txt', null);\n"
],
"file_path": "src/vs/workbench/parts/search/test/common/searchResult.test.ts",
"type": "replace",
"edit_start_line_idx": 25
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
'use strict';
import * as assert from 'assert';
import {WhitespaceComputer} from 'vs/editor/common/viewLayout/whitespaceComputer';
suite('Editor ViewLayout - WhitespaceComputer', () => {
test('WhitespaceComputer', () => {
var whitespaceComputer = new WhitespaceComputer();
// Insert a whitespace after line number 2, of height 10
var a = whitespaceComputer.insertWhitespace(2, 0, 10);
// whitespaces: a(2, 10)
assert.equal(whitespaceComputer.getCount(), 1);
assert.equal(whitespaceComputer.getAfterLineNumberForWhitespaceIndex(0), 2);
assert.equal(whitespaceComputer.getHeightForWhitespaceIndex(0), 10);
assert.equal(whitespaceComputer.getAccumulatedHeight(0), 10);
assert.equal(whitespaceComputer.getTotalHeight(), 10);
assert.equal(whitespaceComputer.getAccumulatedHeightBeforeLineNumber(1), 0);
assert.equal(whitespaceComputer.getAccumulatedHeightBeforeLineNumber(2), 0);
assert.equal(whitespaceComputer.getAccumulatedHeightBeforeLineNumber(3), 10);
assert.equal(whitespaceComputer.getAccumulatedHeightBeforeLineNumber(4), 10);
// Insert a whitespace again after line number 2, of height 20
var b = whitespaceComputer.insertWhitespace(2, 0, 20);
// whitespaces: a(2, 10), b(2, 20)
assert.equal(whitespaceComputer.getCount(), 2);
assert.equal(whitespaceComputer.getAfterLineNumberForWhitespaceIndex(0), 2);
assert.equal(whitespaceComputer.getHeightForWhitespaceIndex(0), 10);
assert.equal(whitespaceComputer.getAfterLineNumberForWhitespaceIndex(1), 2);
assert.equal(whitespaceComputer.getHeightForWhitespaceIndex(1), 20);
assert.equal(whitespaceComputer.getAccumulatedHeight(0), 10);
assert.equal(whitespaceComputer.getAccumulatedHeight(1), 30);
assert.equal(whitespaceComputer.getTotalHeight(), 30);
assert.equal(whitespaceComputer.getAccumulatedHeightBeforeLineNumber(1), 0);
assert.equal(whitespaceComputer.getAccumulatedHeightBeforeLineNumber(2), 0);
assert.equal(whitespaceComputer.getAccumulatedHeightBeforeLineNumber(3), 30);
assert.equal(whitespaceComputer.getAccumulatedHeightBeforeLineNumber(4), 30);
// Change last inserted whitespace height to 30
whitespaceComputer.changeWhitespaceHeight(b, 30);
// whitespaces: a(2, 10), b(2, 30)
assert.equal(whitespaceComputer.getCount(), 2);
assert.equal(whitespaceComputer.getAfterLineNumberForWhitespaceIndex(0), 2);
assert.equal(whitespaceComputer.getHeightForWhitespaceIndex(0), 10);
assert.equal(whitespaceComputer.getAfterLineNumberForWhitespaceIndex(1), 2);
assert.equal(whitespaceComputer.getHeightForWhitespaceIndex(1), 30);
assert.equal(whitespaceComputer.getAccumulatedHeight(0), 10);
assert.equal(whitespaceComputer.getAccumulatedHeight(1), 40);
assert.equal(whitespaceComputer.getTotalHeight(), 40);
assert.equal(whitespaceComputer.getAccumulatedHeightBeforeLineNumber(1), 0);
assert.equal(whitespaceComputer.getAccumulatedHeightBeforeLineNumber(2), 0);
assert.equal(whitespaceComputer.getAccumulatedHeightBeforeLineNumber(3), 40);
assert.equal(whitespaceComputer.getAccumulatedHeightBeforeLineNumber(4), 40);
// Remove last inserted whitespace
whitespaceComputer.removeWhitespace(b);
// whitespaces: a(2, 10)
assert.equal(whitespaceComputer.getCount(), 1);
assert.equal(whitespaceComputer.getAfterLineNumberForWhitespaceIndex(0), 2);
assert.equal(whitespaceComputer.getHeightForWhitespaceIndex(0), 10);
assert.equal(whitespaceComputer.getAccumulatedHeight(0), 10);
assert.equal(whitespaceComputer.getTotalHeight(), 10);
assert.equal(whitespaceComputer.getAccumulatedHeightBeforeLineNumber(1), 0);
assert.equal(whitespaceComputer.getAccumulatedHeightBeforeLineNumber(2), 0);
assert.equal(whitespaceComputer.getAccumulatedHeightBeforeLineNumber(3), 10);
assert.equal(whitespaceComputer.getAccumulatedHeightBeforeLineNumber(4), 10);
// Add a whitespace before the first line of height 50
b = whitespaceComputer.insertWhitespace(0, 0, 50);
// whitespaces: b(0, 50), a(2, 10)
assert.equal(whitespaceComputer.getCount(), 2);
assert.equal(whitespaceComputer.getAfterLineNumberForWhitespaceIndex(0), 0);
assert.equal(whitespaceComputer.getHeightForWhitespaceIndex(0), 50);
assert.equal(whitespaceComputer.getAfterLineNumberForWhitespaceIndex(1), 2);
assert.equal(whitespaceComputer.getHeightForWhitespaceIndex(1), 10);
assert.equal(whitespaceComputer.getAccumulatedHeight(0), 50);
assert.equal(whitespaceComputer.getAccumulatedHeight(1), 60);
assert.equal(whitespaceComputer.getTotalHeight(), 60);
assert.equal(whitespaceComputer.getAccumulatedHeightBeforeLineNumber(1), 50);
assert.equal(whitespaceComputer.getAccumulatedHeightBeforeLineNumber(2), 50);
assert.equal(whitespaceComputer.getAccumulatedHeightBeforeLineNumber(3), 60);
assert.equal(whitespaceComputer.getAccumulatedHeightBeforeLineNumber(4), 60);
// Add a whitespace after line 4 of height 20
whitespaceComputer.insertWhitespace(4, 0, 20);
// whitespaces: b(0, 50), a(2, 10), c(4, 20)
assert.equal(whitespaceComputer.getCount(), 3);
assert.equal(whitespaceComputer.getAfterLineNumberForWhitespaceIndex(0), 0);
assert.equal(whitespaceComputer.getHeightForWhitespaceIndex(0), 50);
assert.equal(whitespaceComputer.getAfterLineNumberForWhitespaceIndex(1), 2);
assert.equal(whitespaceComputer.getHeightForWhitespaceIndex(1), 10);
assert.equal(whitespaceComputer.getAfterLineNumberForWhitespaceIndex(2), 4);
assert.equal(whitespaceComputer.getHeightForWhitespaceIndex(2), 20);
assert.equal(whitespaceComputer.getAccumulatedHeight(0), 50);
assert.equal(whitespaceComputer.getAccumulatedHeight(1), 60);
assert.equal(whitespaceComputer.getAccumulatedHeight(2), 80);
assert.equal(whitespaceComputer.getTotalHeight(), 80);
assert.equal(whitespaceComputer.getAccumulatedHeightBeforeLineNumber(1), 50);
assert.equal(whitespaceComputer.getAccumulatedHeightBeforeLineNumber(2), 50);
assert.equal(whitespaceComputer.getAccumulatedHeightBeforeLineNumber(3), 60);
assert.equal(whitespaceComputer.getAccumulatedHeightBeforeLineNumber(4), 60);
assert.equal(whitespaceComputer.getAccumulatedHeightBeforeLineNumber(5), 80);
// Add a whitespace after line 3 of height 30
whitespaceComputer.insertWhitespace(3, 0, 30);
// whitespaces: b(0, 50), a(2, 10), d(3, 30), c(4, 20)
assert.equal(whitespaceComputer.getCount(), 4);
assert.equal(whitespaceComputer.getAfterLineNumberForWhitespaceIndex(0), 0);
assert.equal(whitespaceComputer.getHeightForWhitespaceIndex(0), 50);
assert.equal(whitespaceComputer.getAfterLineNumberForWhitespaceIndex(1), 2);
assert.equal(whitespaceComputer.getHeightForWhitespaceIndex(1), 10);
assert.equal(whitespaceComputer.getAfterLineNumberForWhitespaceIndex(2), 3);
assert.equal(whitespaceComputer.getHeightForWhitespaceIndex(2), 30);
assert.equal(whitespaceComputer.getAfterLineNumberForWhitespaceIndex(3), 4);
assert.equal(whitespaceComputer.getHeightForWhitespaceIndex(3), 20);
assert.equal(whitespaceComputer.getAccumulatedHeight(0), 50);
assert.equal(whitespaceComputer.getAccumulatedHeight(1), 60);
assert.equal(whitespaceComputer.getAccumulatedHeight(2), 90);
assert.equal(whitespaceComputer.getAccumulatedHeight(3), 110);
assert.equal(whitespaceComputer.getTotalHeight(), 110);
assert.equal(whitespaceComputer.getAccumulatedHeightBeforeLineNumber(1), 50);
assert.equal(whitespaceComputer.getAccumulatedHeightBeforeLineNumber(2), 50);
assert.equal(whitespaceComputer.getAccumulatedHeightBeforeLineNumber(3), 60);
assert.equal(whitespaceComputer.getAccumulatedHeightBeforeLineNumber(4), 90);
assert.equal(whitespaceComputer.getAccumulatedHeightBeforeLineNumber(5), 110);
// Change whitespace after line 2 to height of 100
whitespaceComputer.changeWhitespaceHeight(a, 100);
// whitespaces: b(0, 50), a(2, 100), d(3, 30), c(4, 20)
assert.equal(whitespaceComputer.getCount(), 4);
assert.equal(whitespaceComputer.getAfterLineNumberForWhitespaceIndex(0), 0);
assert.equal(whitespaceComputer.getHeightForWhitespaceIndex(0), 50);
assert.equal(whitespaceComputer.getAfterLineNumberForWhitespaceIndex(1), 2);
assert.equal(whitespaceComputer.getHeightForWhitespaceIndex(1), 100);
assert.equal(whitespaceComputer.getAfterLineNumberForWhitespaceIndex(2), 3);
assert.equal(whitespaceComputer.getHeightForWhitespaceIndex(2), 30);
assert.equal(whitespaceComputer.getAfterLineNumberForWhitespaceIndex(3), 4);
assert.equal(whitespaceComputer.getHeightForWhitespaceIndex(3), 20);
assert.equal(whitespaceComputer.getAccumulatedHeight(0), 50);
assert.equal(whitespaceComputer.getAccumulatedHeight(1), 150);
assert.equal(whitespaceComputer.getAccumulatedHeight(2), 180);
assert.equal(whitespaceComputer.getAccumulatedHeight(3), 200);
assert.equal(whitespaceComputer.getTotalHeight(), 200);
assert.equal(whitespaceComputer.getAccumulatedHeightBeforeLineNumber(1), 50);
assert.equal(whitespaceComputer.getAccumulatedHeightBeforeLineNumber(2), 50);
assert.equal(whitespaceComputer.getAccumulatedHeightBeforeLineNumber(3), 150);
assert.equal(whitespaceComputer.getAccumulatedHeightBeforeLineNumber(4), 180);
assert.equal(whitespaceComputer.getAccumulatedHeightBeforeLineNumber(5), 200);
// Remove whitespace after line 2
whitespaceComputer.removeWhitespace(a);
// whitespaces: b(0, 50), d(3, 30), c(4, 20)
assert.equal(whitespaceComputer.getCount(), 3);
assert.equal(whitespaceComputer.getAfterLineNumberForWhitespaceIndex(0), 0);
assert.equal(whitespaceComputer.getHeightForWhitespaceIndex(0), 50);
assert.equal(whitespaceComputer.getAfterLineNumberForWhitespaceIndex(1), 3);
assert.equal(whitespaceComputer.getHeightForWhitespaceIndex(1), 30);
assert.equal(whitespaceComputer.getAfterLineNumberForWhitespaceIndex(2), 4);
assert.equal(whitespaceComputer.getHeightForWhitespaceIndex(2), 20);
assert.equal(whitespaceComputer.getAccumulatedHeight(0), 50);
assert.equal(whitespaceComputer.getAccumulatedHeight(1), 80);
assert.equal(whitespaceComputer.getAccumulatedHeight(2), 100);
assert.equal(whitespaceComputer.getTotalHeight(), 100);
assert.equal(whitespaceComputer.getAccumulatedHeightBeforeLineNumber(1), 50);
assert.equal(whitespaceComputer.getAccumulatedHeightBeforeLineNumber(2), 50);
assert.equal(whitespaceComputer.getAccumulatedHeightBeforeLineNumber(3), 50);
assert.equal(whitespaceComputer.getAccumulatedHeightBeforeLineNumber(4), 80);
assert.equal(whitespaceComputer.getAccumulatedHeightBeforeLineNumber(5), 100);
// Remove whitespace before line 1
whitespaceComputer.removeWhitespace(b);
// whitespaces: d(3, 30), c(4, 20)
assert.equal(whitespaceComputer.getCount(), 2);
assert.equal(whitespaceComputer.getAfterLineNumberForWhitespaceIndex(0), 3);
assert.equal(whitespaceComputer.getHeightForWhitespaceIndex(0), 30);
assert.equal(whitespaceComputer.getAfterLineNumberForWhitespaceIndex(1), 4);
assert.equal(whitespaceComputer.getHeightForWhitespaceIndex(1), 20);
assert.equal(whitespaceComputer.getAccumulatedHeight(0), 30);
assert.equal(whitespaceComputer.getAccumulatedHeight(1), 50);
assert.equal(whitespaceComputer.getTotalHeight(), 50);
assert.equal(whitespaceComputer.getAccumulatedHeightBeforeLineNumber(1), 0);
assert.equal(whitespaceComputer.getAccumulatedHeightBeforeLineNumber(2), 0);
assert.equal(whitespaceComputer.getAccumulatedHeightBeforeLineNumber(3), 0);
assert.equal(whitespaceComputer.getAccumulatedHeightBeforeLineNumber(4), 30);
assert.equal(whitespaceComputer.getAccumulatedHeightBeforeLineNumber(5), 50);
// Delete line 1
whitespaceComputer.onModelLinesDeleted(1, 1);
// whitespaces: d(2, 30), c(3, 20)
assert.equal(whitespaceComputer.getCount(), 2);
assert.equal(whitespaceComputer.getAfterLineNumberForWhitespaceIndex(0), 2);
assert.equal(whitespaceComputer.getHeightForWhitespaceIndex(0), 30);
assert.equal(whitespaceComputer.getAfterLineNumberForWhitespaceIndex(1), 3);
assert.equal(whitespaceComputer.getHeightForWhitespaceIndex(1), 20);
assert.equal(whitespaceComputer.getAccumulatedHeight(0), 30);
assert.equal(whitespaceComputer.getAccumulatedHeight(1), 50);
assert.equal(whitespaceComputer.getTotalHeight(), 50);
assert.equal(whitespaceComputer.getAccumulatedHeightBeforeLineNumber(1), 0);
assert.equal(whitespaceComputer.getAccumulatedHeightBeforeLineNumber(2), 0);
assert.equal(whitespaceComputer.getAccumulatedHeightBeforeLineNumber(3), 30);
assert.equal(whitespaceComputer.getAccumulatedHeightBeforeLineNumber(4), 50);
assert.equal(whitespaceComputer.getAccumulatedHeightBeforeLineNumber(5), 50);
// Insert a line before line 1
whitespaceComputer.onModelLinesInserted(1, 1);
// whitespaces: d(3, 30), c(4, 20)
assert.equal(whitespaceComputer.getCount(), 2);
assert.equal(whitespaceComputer.getAfterLineNumberForWhitespaceIndex(0), 3);
assert.equal(whitespaceComputer.getHeightForWhitespaceIndex(0), 30);
assert.equal(whitespaceComputer.getAfterLineNumberForWhitespaceIndex(1), 4);
assert.equal(whitespaceComputer.getHeightForWhitespaceIndex(1), 20);
assert.equal(whitespaceComputer.getAccumulatedHeight(0), 30);
assert.equal(whitespaceComputer.getAccumulatedHeight(1), 50);
assert.equal(whitespaceComputer.getTotalHeight(), 50);
assert.equal(whitespaceComputer.getAccumulatedHeightBeforeLineNumber(1), 0);
assert.equal(whitespaceComputer.getAccumulatedHeightBeforeLineNumber(2), 0);
assert.equal(whitespaceComputer.getAccumulatedHeightBeforeLineNumber(3), 0);
assert.equal(whitespaceComputer.getAccumulatedHeightBeforeLineNumber(4), 30);
assert.equal(whitespaceComputer.getAccumulatedHeightBeforeLineNumber(5), 50);
// Delete line 4
whitespaceComputer.onModelLinesDeleted(4, 4);
// whitespaces: d(3, 30), c(3, 20)
assert.equal(whitespaceComputer.getCount(), 2);
assert.equal(whitespaceComputer.getAfterLineNumberForWhitespaceIndex(0), 3);
assert.equal(whitespaceComputer.getHeightForWhitespaceIndex(0), 30);
assert.equal(whitespaceComputer.getAfterLineNumberForWhitespaceIndex(1), 3);
assert.equal(whitespaceComputer.getHeightForWhitespaceIndex(1), 20);
assert.equal(whitespaceComputer.getAccumulatedHeight(0), 30);
assert.equal(whitespaceComputer.getAccumulatedHeight(1), 50);
assert.equal(whitespaceComputer.getTotalHeight(), 50);
assert.equal(whitespaceComputer.getAccumulatedHeightBeforeLineNumber(1), 0);
assert.equal(whitespaceComputer.getAccumulatedHeightBeforeLineNumber(2), 0);
assert.equal(whitespaceComputer.getAccumulatedHeightBeforeLineNumber(3), 0);
assert.equal(whitespaceComputer.getAccumulatedHeightBeforeLineNumber(4), 50);
assert.equal(whitespaceComputer.getAccumulatedHeightBeforeLineNumber(5), 50);
});
test('WhitespaceComputer findInsertionIndex', () => {
var makeArray = (size:number, fillValue:number) => {
var r:number[] = [];
for (var i = 0; i < size; i++) {
r[i] = fillValue;
}
return r;
};
var arr:number[];
var ordinals:number[];
arr = [];
ordinals = makeArray(arr.length, 0);
assert.equal(WhitespaceComputer.findInsertionIndex(arr, 0, ordinals, 0), 0);
assert.equal(WhitespaceComputer.findInsertionIndex(arr, 1, ordinals, 0), 0);
assert.equal(WhitespaceComputer.findInsertionIndex(arr, 2, ordinals, 0), 0);
arr = [1];
ordinals = makeArray(arr.length, 0);
assert.equal(WhitespaceComputer.findInsertionIndex(arr, 0, ordinals, 0), 0);
assert.equal(WhitespaceComputer.findInsertionIndex(arr, 1, ordinals, 0), 1);
assert.equal(WhitespaceComputer.findInsertionIndex(arr, 2, ordinals, 0), 1);
arr = [1, 3];
ordinals = makeArray(arr.length, 0);
assert.equal(WhitespaceComputer.findInsertionIndex(arr, 0, ordinals, 0), 0);
assert.equal(WhitespaceComputer.findInsertionIndex(arr, 1, ordinals, 0), 1);
assert.equal(WhitespaceComputer.findInsertionIndex(arr, 2, ordinals, 0), 1);
assert.equal(WhitespaceComputer.findInsertionIndex(arr, 3, ordinals, 0), 2);
assert.equal(WhitespaceComputer.findInsertionIndex(arr, 4, ordinals, 0), 2);
arr = [1, 3, 5];
ordinals = makeArray(arr.length, 0);
assert.equal(WhitespaceComputer.findInsertionIndex(arr, 0, ordinals, 0), 0);
assert.equal(WhitespaceComputer.findInsertionIndex(arr, 1, ordinals, 0), 1);
assert.equal(WhitespaceComputer.findInsertionIndex(arr, 2, ordinals, 0), 1);
assert.equal(WhitespaceComputer.findInsertionIndex(arr, 3, ordinals, 0), 2);
assert.equal(WhitespaceComputer.findInsertionIndex(arr, 4, ordinals, 0), 2);
assert.equal(WhitespaceComputer.findInsertionIndex(arr, 5, ordinals, 0), 3);
assert.equal(WhitespaceComputer.findInsertionIndex(arr, 6, ordinals, 0), 3);
arr = [1, 3, 5];
ordinals = makeArray(arr.length, 3);
assert.equal(WhitespaceComputer.findInsertionIndex(arr, 0, ordinals, 0), 0);
assert.equal(WhitespaceComputer.findInsertionIndex(arr, 1, ordinals, 0), 0);
assert.equal(WhitespaceComputer.findInsertionIndex(arr, 2, ordinals, 0), 1);
assert.equal(WhitespaceComputer.findInsertionIndex(arr, 3, ordinals, 0), 1);
assert.equal(WhitespaceComputer.findInsertionIndex(arr, 4, ordinals, 0), 2);
assert.equal(WhitespaceComputer.findInsertionIndex(arr, 5, ordinals, 0), 2);
assert.equal(WhitespaceComputer.findInsertionIndex(arr, 6, ordinals, 0), 3);
arr = [1, 3, 5, 7];
ordinals = makeArray(arr.length, 0);
assert.equal(WhitespaceComputer.findInsertionIndex(arr, 0, ordinals, 0), 0);
assert.equal(WhitespaceComputer.findInsertionIndex(arr, 1, ordinals, 0), 1);
assert.equal(WhitespaceComputer.findInsertionIndex(arr, 2, ordinals, 0), 1);
assert.equal(WhitespaceComputer.findInsertionIndex(arr, 3, ordinals, 0), 2);
assert.equal(WhitespaceComputer.findInsertionIndex(arr, 4, ordinals, 0), 2);
assert.equal(WhitespaceComputer.findInsertionIndex(arr, 5, ordinals, 0), 3);
assert.equal(WhitespaceComputer.findInsertionIndex(arr, 6, ordinals, 0), 3);
assert.equal(WhitespaceComputer.findInsertionIndex(arr, 7, ordinals, 0), 4);
assert.equal(WhitespaceComputer.findInsertionIndex(arr, 8, ordinals, 0), 4);
arr = [1, 3, 5, 7, 9];
ordinals = makeArray(arr.length, 0);
assert.equal(WhitespaceComputer.findInsertionIndex(arr, 0, ordinals, 0), 0);
assert.equal(WhitespaceComputer.findInsertionIndex(arr, 1, ordinals, 0), 1);
assert.equal(WhitespaceComputer.findInsertionIndex(arr, 2, ordinals, 0), 1);
assert.equal(WhitespaceComputer.findInsertionIndex(arr, 3, ordinals, 0), 2);
assert.equal(WhitespaceComputer.findInsertionIndex(arr, 4, ordinals, 0), 2);
assert.equal(WhitespaceComputer.findInsertionIndex(arr, 5, ordinals, 0), 3);
assert.equal(WhitespaceComputer.findInsertionIndex(arr, 6, ordinals, 0), 3);
assert.equal(WhitespaceComputer.findInsertionIndex(arr, 7, ordinals, 0), 4);
assert.equal(WhitespaceComputer.findInsertionIndex(arr, 8, ordinals, 0), 4);
assert.equal(WhitespaceComputer.findInsertionIndex(arr, 9, ordinals, 0), 5);
assert.equal(WhitespaceComputer.findInsertionIndex(arr, 10, ordinals, 0), 5);
arr = [1, 3, 5, 7, 9, 11];
ordinals = makeArray(arr.length, 0);
assert.equal(WhitespaceComputer.findInsertionIndex(arr, 0, ordinals, 0), 0);
assert.equal(WhitespaceComputer.findInsertionIndex(arr, 1, ordinals, 0), 1);
assert.equal(WhitespaceComputer.findInsertionIndex(arr, 2, ordinals, 0), 1);
assert.equal(WhitespaceComputer.findInsertionIndex(arr, 3, ordinals, 0), 2);
assert.equal(WhitespaceComputer.findInsertionIndex(arr, 4, ordinals, 0), 2);
assert.equal(WhitespaceComputer.findInsertionIndex(arr, 5, ordinals, 0), 3);
assert.equal(WhitespaceComputer.findInsertionIndex(arr, 6, ordinals, 0), 3);
assert.equal(WhitespaceComputer.findInsertionIndex(arr, 7, ordinals, 0), 4);
assert.equal(WhitespaceComputer.findInsertionIndex(arr, 8, ordinals, 0), 4);
assert.equal(WhitespaceComputer.findInsertionIndex(arr, 9, ordinals, 0), 5);
assert.equal(WhitespaceComputer.findInsertionIndex(arr, 10, ordinals, 0), 5);
assert.equal(WhitespaceComputer.findInsertionIndex(arr, 11, ordinals, 0), 6);
assert.equal(WhitespaceComputer.findInsertionIndex(arr, 12, ordinals, 0), 6);
arr = [1, 3, 5, 7, 9, 11, 13];
ordinals = makeArray(arr.length, 0);
assert.equal(WhitespaceComputer.findInsertionIndex(arr, 0, ordinals, 0), 0);
assert.equal(WhitespaceComputer.findInsertionIndex(arr, 1, ordinals, 0), 1);
assert.equal(WhitespaceComputer.findInsertionIndex(arr, 2, ordinals, 0), 1);
assert.equal(WhitespaceComputer.findInsertionIndex(arr, 3, ordinals, 0), 2);
assert.equal(WhitespaceComputer.findInsertionIndex(arr, 4, ordinals, 0), 2);
assert.equal(WhitespaceComputer.findInsertionIndex(arr, 5, ordinals, 0), 3);
assert.equal(WhitespaceComputer.findInsertionIndex(arr, 6, ordinals, 0), 3);
assert.equal(WhitespaceComputer.findInsertionIndex(arr, 7, ordinals, 0), 4);
assert.equal(WhitespaceComputer.findInsertionIndex(arr, 8, ordinals, 0), 4);
assert.equal(WhitespaceComputer.findInsertionIndex(arr, 9, ordinals, 0), 5);
assert.equal(WhitespaceComputer.findInsertionIndex(arr, 10, ordinals, 0), 5);
assert.equal(WhitespaceComputer.findInsertionIndex(arr, 11, ordinals, 0), 6);
assert.equal(WhitespaceComputer.findInsertionIndex(arr, 12, ordinals, 0), 6);
assert.equal(WhitespaceComputer.findInsertionIndex(arr, 13, ordinals, 0), 7);
assert.equal(WhitespaceComputer.findInsertionIndex(arr, 14, ordinals, 0), 7);
arr = [1, 3, 5, 7, 9, 11, 13, 15];
ordinals = makeArray(arr.length, 0);
assert.equal(WhitespaceComputer.findInsertionIndex(arr, 0, ordinals, 0), 0);
assert.equal(WhitespaceComputer.findInsertionIndex(arr, 1, ordinals, 0), 1);
assert.equal(WhitespaceComputer.findInsertionIndex(arr, 2, ordinals, 0), 1);
assert.equal(WhitespaceComputer.findInsertionIndex(arr, 3, ordinals, 0), 2);
assert.equal(WhitespaceComputer.findInsertionIndex(arr, 4, ordinals, 0), 2);
assert.equal(WhitespaceComputer.findInsertionIndex(arr, 5, ordinals, 0), 3);
assert.equal(WhitespaceComputer.findInsertionIndex(arr, 6, ordinals, 0), 3);
assert.equal(WhitespaceComputer.findInsertionIndex(arr, 7, ordinals, 0), 4);
assert.equal(WhitespaceComputer.findInsertionIndex(arr, 8, ordinals, 0), 4);
assert.equal(WhitespaceComputer.findInsertionIndex(arr, 9, ordinals, 0), 5);
assert.equal(WhitespaceComputer.findInsertionIndex(arr, 10, ordinals, 0), 5);
assert.equal(WhitespaceComputer.findInsertionIndex(arr, 11, ordinals, 0), 6);
assert.equal(WhitespaceComputer.findInsertionIndex(arr, 12, ordinals, 0), 6);
assert.equal(WhitespaceComputer.findInsertionIndex(arr, 13, ordinals, 0), 7);
assert.equal(WhitespaceComputer.findInsertionIndex(arr, 14, ordinals, 0), 7);
assert.equal(WhitespaceComputer.findInsertionIndex(arr, 15, ordinals, 0), 8);
assert.equal(WhitespaceComputer.findInsertionIndex(arr, 16, ordinals, 0), 8);
});
test('WhitespaceComputer changeWhitespaceAfterLineNumber & getFirstWhitespaceIndexAfterLineNumber', () => {
var whitespaceComputer = new WhitespaceComputer();
var a = whitespaceComputer.insertWhitespace(0, 0, 1);
var b = whitespaceComputer.insertWhitespace(7, 0, 1);
var c = whitespaceComputer.insertWhitespace(3, 0, 1);
assert.equal(whitespaceComputer.getIdForWhitespaceIndex(0), a); // 0
assert.equal(whitespaceComputer.getAfterLineNumberForWhitespaceIndex(0), 0);
assert.equal(whitespaceComputer.getIdForWhitespaceIndex(1), c); // 3
assert.equal(whitespaceComputer.getAfterLineNumberForWhitespaceIndex(1), 3);
assert.equal(whitespaceComputer.getIdForWhitespaceIndex(2), b); // 7
assert.equal(whitespaceComputer.getAfterLineNumberForWhitespaceIndex(2), 7);
assert.equal(whitespaceComputer.getFirstWhitespaceIndexAfterLineNumber(1), 1); // c
assert.equal(whitespaceComputer.getFirstWhitespaceIndexAfterLineNumber(2), 1); // c
assert.equal(whitespaceComputer.getFirstWhitespaceIndexAfterLineNumber(3), 1); // c
assert.equal(whitespaceComputer.getFirstWhitespaceIndexAfterLineNumber(4), 2); // b
assert.equal(whitespaceComputer.getFirstWhitespaceIndexAfterLineNumber(5), 2); // b
assert.equal(whitespaceComputer.getFirstWhitespaceIndexAfterLineNumber(6), 2); // b
assert.equal(whitespaceComputer.getFirstWhitespaceIndexAfterLineNumber(7), 2); // b
assert.equal(whitespaceComputer.getFirstWhitespaceIndexAfterLineNumber(8), -1); // --
// Do not really move a
whitespaceComputer.changeWhitespaceAfterLineNumber(a, 1);
assert.equal(whitespaceComputer.getIdForWhitespaceIndex(0), a); // 1
assert.equal(whitespaceComputer.getAfterLineNumberForWhitespaceIndex(0), 1);
assert.equal(whitespaceComputer.getIdForWhitespaceIndex(1), c); // 3
assert.equal(whitespaceComputer.getAfterLineNumberForWhitespaceIndex(1), 3);
assert.equal(whitespaceComputer.getIdForWhitespaceIndex(2), b); // 7
assert.equal(whitespaceComputer.getAfterLineNumberForWhitespaceIndex(2), 7);
assert.equal(whitespaceComputer.getFirstWhitespaceIndexAfterLineNumber(1), 0); // a
assert.equal(whitespaceComputer.getFirstWhitespaceIndexAfterLineNumber(2), 1); // c
assert.equal(whitespaceComputer.getFirstWhitespaceIndexAfterLineNumber(3), 1); // c
assert.equal(whitespaceComputer.getFirstWhitespaceIndexAfterLineNumber(4), 2); // b
assert.equal(whitespaceComputer.getFirstWhitespaceIndexAfterLineNumber(5), 2); // b
assert.equal(whitespaceComputer.getFirstWhitespaceIndexAfterLineNumber(6), 2); // b
assert.equal(whitespaceComputer.getFirstWhitespaceIndexAfterLineNumber(7), 2); // b
assert.equal(whitespaceComputer.getFirstWhitespaceIndexAfterLineNumber(8), -1); // --
// Do not really move a
whitespaceComputer.changeWhitespaceAfterLineNumber(a, 2);
assert.equal(whitespaceComputer.getIdForWhitespaceIndex(0), a); // 2
assert.equal(whitespaceComputer.getAfterLineNumberForWhitespaceIndex(0), 2);
assert.equal(whitespaceComputer.getIdForWhitespaceIndex(1), c); // 3
assert.equal(whitespaceComputer.getAfterLineNumberForWhitespaceIndex(1), 3);
assert.equal(whitespaceComputer.getIdForWhitespaceIndex(2), b); // 7
assert.equal(whitespaceComputer.getAfterLineNumberForWhitespaceIndex(2), 7);
assert.equal(whitespaceComputer.getFirstWhitespaceIndexAfterLineNumber(1), 0); // a
assert.equal(whitespaceComputer.getFirstWhitespaceIndexAfterLineNumber(2), 0); // a
assert.equal(whitespaceComputer.getFirstWhitespaceIndexAfterLineNumber(3), 1); // c
assert.equal(whitespaceComputer.getFirstWhitespaceIndexAfterLineNumber(4), 2); // b
assert.equal(whitespaceComputer.getFirstWhitespaceIndexAfterLineNumber(5), 2); // b
assert.equal(whitespaceComputer.getFirstWhitespaceIndexAfterLineNumber(6), 2); // b
assert.equal(whitespaceComputer.getFirstWhitespaceIndexAfterLineNumber(7), 2); // b
assert.equal(whitespaceComputer.getFirstWhitespaceIndexAfterLineNumber(8), -1); // --
// Change a to conflict with c => a gets placed after c
whitespaceComputer.changeWhitespaceAfterLineNumber(a, 3);
assert.equal(whitespaceComputer.getIdForWhitespaceIndex(0), c); // 3
assert.equal(whitespaceComputer.getAfterLineNumberForWhitespaceIndex(0), 3);
assert.equal(whitespaceComputer.getIdForWhitespaceIndex(1), a); // 3
assert.equal(whitespaceComputer.getAfterLineNumberForWhitespaceIndex(1), 3);
assert.equal(whitespaceComputer.getIdForWhitespaceIndex(2), b); // 7
assert.equal(whitespaceComputer.getAfterLineNumberForWhitespaceIndex(2), 7);
assert.equal(whitespaceComputer.getFirstWhitespaceIndexAfterLineNumber(1), 0); // c
assert.equal(whitespaceComputer.getFirstWhitespaceIndexAfterLineNumber(2), 0); // c
assert.equal(whitespaceComputer.getFirstWhitespaceIndexAfterLineNumber(3), 0); // c
assert.equal(whitespaceComputer.getFirstWhitespaceIndexAfterLineNumber(4), 2); // b
assert.equal(whitespaceComputer.getFirstWhitespaceIndexAfterLineNumber(5), 2); // b
assert.equal(whitespaceComputer.getFirstWhitespaceIndexAfterLineNumber(6), 2); // b
assert.equal(whitespaceComputer.getFirstWhitespaceIndexAfterLineNumber(7), 2); // b
assert.equal(whitespaceComputer.getFirstWhitespaceIndexAfterLineNumber(8), -1); // --
// Make a no-op
whitespaceComputer.changeWhitespaceAfterLineNumber(c, 3);
assert.equal(whitespaceComputer.getIdForWhitespaceIndex(0), c); // 3
assert.equal(whitespaceComputer.getAfterLineNumberForWhitespaceIndex(0), 3);
assert.equal(whitespaceComputer.getIdForWhitespaceIndex(1), a); // 3
assert.equal(whitespaceComputer.getAfterLineNumberForWhitespaceIndex(1), 3);
assert.equal(whitespaceComputer.getIdForWhitespaceIndex(2), b); // 7
assert.equal(whitespaceComputer.getAfterLineNumberForWhitespaceIndex(2), 7);
assert.equal(whitespaceComputer.getFirstWhitespaceIndexAfterLineNumber(1), 0); // c
assert.equal(whitespaceComputer.getFirstWhitespaceIndexAfterLineNumber(2), 0); // c
assert.equal(whitespaceComputer.getFirstWhitespaceIndexAfterLineNumber(3), 0); // c
assert.equal(whitespaceComputer.getFirstWhitespaceIndexAfterLineNumber(4), 2); // b
assert.equal(whitespaceComputer.getFirstWhitespaceIndexAfterLineNumber(5), 2); // b
assert.equal(whitespaceComputer.getFirstWhitespaceIndexAfterLineNumber(6), 2); // b
assert.equal(whitespaceComputer.getFirstWhitespaceIndexAfterLineNumber(7), 2); // b
assert.equal(whitespaceComputer.getFirstWhitespaceIndexAfterLineNumber(8), -1); // --
// Conflict c with b => c gets placed after b
whitespaceComputer.changeWhitespaceAfterLineNumber(c, 7);
assert.equal(whitespaceComputer.getIdForWhitespaceIndex(0), a); // 3
assert.equal(whitespaceComputer.getAfterLineNumberForWhitespaceIndex(0), 3);
assert.equal(whitespaceComputer.getIdForWhitespaceIndex(1), b); // 7
assert.equal(whitespaceComputer.getAfterLineNumberForWhitespaceIndex(1), 7);
assert.equal(whitespaceComputer.getIdForWhitespaceIndex(2), c); // 7
assert.equal(whitespaceComputer.getAfterLineNumberForWhitespaceIndex(2), 7);
assert.equal(whitespaceComputer.getFirstWhitespaceIndexAfterLineNumber(1), 0); // a
assert.equal(whitespaceComputer.getFirstWhitespaceIndexAfterLineNumber(2), 0); // a
assert.equal(whitespaceComputer.getFirstWhitespaceIndexAfterLineNumber(3), 0); // a
assert.equal(whitespaceComputer.getFirstWhitespaceIndexAfterLineNumber(4), 1); // b
assert.equal(whitespaceComputer.getFirstWhitespaceIndexAfterLineNumber(5), 1); // b
assert.equal(whitespaceComputer.getFirstWhitespaceIndexAfterLineNumber(6), 1); // b
assert.equal(whitespaceComputer.getFirstWhitespaceIndexAfterLineNumber(7), 1); // b
assert.equal(whitespaceComputer.getFirstWhitespaceIndexAfterLineNumber(8), -1); // --
});
test('WhitespaceComputer Bug', () => {
var whitespaceComputer = new WhitespaceComputer();
var a = whitespaceComputer.insertWhitespace(0, 0, 1);
var b = whitespaceComputer.insertWhitespace(7, 0, 1);
assert.equal(whitespaceComputer.getIdForWhitespaceIndex(0), a); // 0
assert.equal(whitespaceComputer.getIdForWhitespaceIndex(1), b); // 7
var c = whitespaceComputer.insertWhitespace(3, 0, 1);
assert.equal(whitespaceComputer.getIdForWhitespaceIndex(0), a); // 0
assert.equal(whitespaceComputer.getIdForWhitespaceIndex(1), c); // 3
assert.equal(whitespaceComputer.getIdForWhitespaceIndex(2), b); // 7
var d = whitespaceComputer.insertWhitespace(2, 0, 1);
assert.equal(whitespaceComputer.getIdForWhitespaceIndex(0), a); // 0
assert.equal(whitespaceComputer.getIdForWhitespaceIndex(1), d); // 2
assert.equal(whitespaceComputer.getIdForWhitespaceIndex(2), c); // 3
assert.equal(whitespaceComputer.getIdForWhitespaceIndex(3), b); // 7
var e = whitespaceComputer.insertWhitespace(8, 0, 1);
assert.equal(whitespaceComputer.getIdForWhitespaceIndex(0), a); // 0
assert.equal(whitespaceComputer.getIdForWhitespaceIndex(1), d); // 2
assert.equal(whitespaceComputer.getIdForWhitespaceIndex(2), c); // 3
assert.equal(whitespaceComputer.getIdForWhitespaceIndex(3), b); // 7
assert.equal(whitespaceComputer.getIdForWhitespaceIndex(4), e); // 8
var f = whitespaceComputer.insertWhitespace(11, 0, 1);
assert.equal(whitespaceComputer.getIdForWhitespaceIndex(0), a); // 0
assert.equal(whitespaceComputer.getIdForWhitespaceIndex(1), d); // 2
assert.equal(whitespaceComputer.getIdForWhitespaceIndex(2), c); // 3
assert.equal(whitespaceComputer.getIdForWhitespaceIndex(3), b); // 7
assert.equal(whitespaceComputer.getIdForWhitespaceIndex(4), e); // 8
assert.equal(whitespaceComputer.getIdForWhitespaceIndex(5), f); // 11
var g = whitespaceComputer.insertWhitespace(10, 0, 1);
assert.equal(whitespaceComputer.getIdForWhitespaceIndex(0), a); // 0
assert.equal(whitespaceComputer.getIdForWhitespaceIndex(1), d); // 2
assert.equal(whitespaceComputer.getIdForWhitespaceIndex(2), c); // 3
assert.equal(whitespaceComputer.getIdForWhitespaceIndex(3), b); // 7
assert.equal(whitespaceComputer.getIdForWhitespaceIndex(4), e); // 8
assert.equal(whitespaceComputer.getIdForWhitespaceIndex(5), g); // 10
assert.equal(whitespaceComputer.getIdForWhitespaceIndex(6), f); // 11
var h = whitespaceComputer.insertWhitespace(0, 0, 1);
assert.equal(whitespaceComputer.getIdForWhitespaceIndex(0), a); // 0
assert.equal(whitespaceComputer.getIdForWhitespaceIndex(1), h); // 0
assert.equal(whitespaceComputer.getIdForWhitespaceIndex(2), d); // 2
assert.equal(whitespaceComputer.getIdForWhitespaceIndex(3), c); // 3
assert.equal(whitespaceComputer.getIdForWhitespaceIndex(4), b); // 7
assert.equal(whitespaceComputer.getIdForWhitespaceIndex(5), e); // 8
assert.equal(whitespaceComputer.getIdForWhitespaceIndex(6), g); // 10
assert.equal(whitespaceComputer.getIdForWhitespaceIndex(7), f); // 11
});
});
| src/vs/editor/test/common/viewLayout/whitespaceComputer.test.ts | 0 | https://github.com/microsoft/vscode/commit/e12eb3dc06b131a8c00fbe61c77ae98311f103e9 | [
0.00017732074775267392,
0.0001718237908789888,
0.00016595616762060672,
0.0001713109522825107,
0.000003095107103945338
] |
{
"id": 9,
"code_window": [
"\t});\n",
"\n",
"\ttest('Line Match', function () {\n",
"\t\tlet fileMatch = aFileMatch('folder\\\\file.txt');\n",
"\t\tlet lineMatch = new Match(fileMatch, 'foo bar', 1, 0, 3);\n",
"\t\tassert.equal(lineMatch.text(), 'foo bar');\n",
"\t\tassert.equal(lineMatch.range().startLineNumber, 2);\n",
"\t\tassert.equal(lineMatch.range().endLineNumber, 2);\n",
"\t\tassert.equal(lineMatch.range().startColumn, 1);\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\tlet fileMatch = aFileMatch('folder\\\\file.txt', null);\n"
],
"file_path": "src/vs/workbench/parts/search/test/common/searchResult.test.ts",
"type": "replace",
"edit_start_line_idx": 25
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
// Do not edit this file. It is machine generated.
{
"addSelectionToNextFindMatch": "다음 일치 항목 찾기에 선택 항목 추가",
"changeAll.label": "모든 항목 변경",
"findNextMatchAction": "다음 찾기",
"findPreviousMatchAction": "이전 찾기",
"moveSelectionToNextFindMatch": "다음 일치 항목 찾기로 마지막 선택 항목 이동",
"nextSelectionMatchFindAction": "다음 선택 찾기",
"previousSelectionMatchFindAction": "이전 선택 찾기",
"selectAllOccurencesOfFindMatch": "일치 항목 찾기의 모든 항목 선택",
"startFindAction": "찾기",
"startReplace": "바꾸기"
} | i18n/kor/src/vs/editor/contrib/find/common/findController.i18n.json | 0 | https://github.com/microsoft/vscode/commit/e12eb3dc06b131a8c00fbe61c77ae98311f103e9 | [
0.00017164893506560475,
0.0001713668170850724,
0.00017108471365645528,
0.0001713668170850724,
2.8211070457473397e-7
] |
{
"id": 10,
"code_window": [
"\t\tassert.equal(lineMatch.range().endColumn, 4);\n",
"\t});\n",
"\n",
"\ttest('Line Match - Remove', function () {\n",
"\t\tlet fileMatch = aFileMatch('folder\\\\file.txt', null, ...[{\n",
"\t\t\t\t\tpreview: 'foo bar',\n",
"\t\t\t\t\tlineNumber: 1,\n",
"\t\t\t\t\toffsetAndLengths: [[0, 3]]\n",
"\t\t}]);\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\tlet fileMatch = aFileMatch('folder\\\\file.txt', aSearchResult(), ...[{\n"
],
"file_path": "src/vs/workbench/parts/search/test/common/searchResult.test.ts",
"type": "replace",
"edit_start_line_idx": 35
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
'use strict';
import * as assert from 'assert';
import * as sinon from 'sinon';
import { TestInstantiationService } from 'vs/test/utils/instantiationTestUtils';
import { Match, FileMatch, SearchResult, SearchModel } from 'vs/workbench/parts/search/common/searchModel';
import URI from 'vs/base/common/uri';
import {IFileMatch, ILineMatch} from 'vs/platform/search/common/search';
import { ITelemetryService } from 'vs/platform/telemetry/common/telemetry';
import { Range } from 'vs/editor/common/core/range';
suite('SearchResult', () => {
let instantiationService: TestInstantiationService;
setup(() => {
instantiationService= new TestInstantiationService();
instantiationService.stub(ITelemetryService);
});
test('Line Match', function () {
let fileMatch = aFileMatch('folder\\file.txt');
let lineMatch = new Match(fileMatch, 'foo bar', 1, 0, 3);
assert.equal(lineMatch.text(), 'foo bar');
assert.equal(lineMatch.range().startLineNumber, 2);
assert.equal(lineMatch.range().endLineNumber, 2);
assert.equal(lineMatch.range().startColumn, 1);
assert.equal(lineMatch.range().endColumn, 4);
});
test('Line Match - Remove', function () {
let fileMatch = aFileMatch('folder\\file.txt', null, ...[{
preview: 'foo bar',
lineNumber: 1,
offsetAndLengths: [[0, 3]]
}]);
let lineMatch = fileMatch.matches()[0];
fileMatch.remove(lineMatch);
assert.equal(fileMatch.matches().length, 0);
});
test('File Match', function () {
let fileMatch = aFileMatch('folder\\file.txt');
assert.equal(fileMatch.matches(), 0);
assert.equal(fileMatch.resource().toString(), 'file:///c%3A/folder/file.txt');
assert.equal(fileMatch.name(), 'file.txt');
fileMatch = aFileMatch('file.txt');
assert.equal(fileMatch.matches(), 0);
assert.equal(fileMatch.resource().toString(), 'file:///c%3A/file.txt');
assert.equal(fileMatch.name(), 'file.txt');
});
test('Alle Drei Zusammen', function () {
let searchResult = instantiationService.createInstance(SearchResult, null);
let fileMatch = aFileMatch('far\\boo', searchResult);
let lineMatch = new Match(fileMatch, 'foo bar', 1, 0, 3);
assert(lineMatch.parent() === fileMatch);
assert(fileMatch.parent() === searchResult);
});
test('Search Result: Adding a raw match will add a file match with line matches', function () {
let testObject = aSearchResult();
let target= [aRawMatch('file://c:/', aLineMatch('preview 1', 1, [[1, 3], [4, 7]]), aLineMatch('preview 2'))];
testObject.add(target);
assert.equal(3, testObject.count());
let actual= testObject.matches();
assert.equal(1, actual.length);
assert.equal('file://c:/', actual[0].resource().toString());
let actuaMatches= actual[0].matches();
assert.equal(3, actuaMatches.length);
assert.equal('preview 1', actuaMatches[0].text());
assert.ok(new Range(2, 2, 2, 5).equalsRange(actuaMatches[0].range()));
assert.equal('preview 1', actuaMatches[1].text());
assert.ok(new Range(2, 5, 2, 12).equalsRange(actuaMatches[1].range()));
assert.equal('preview 2', actuaMatches[2].text());
assert.ok(new Range(2, 1, 2, 2).equalsRange(actuaMatches[2].range()));
});
test('Search Result: Adding multiple raw matches', function () {
let testObject = aSearchResult();
let target= [aRawMatch('file://c:/1', aLineMatch('preview 1', 1, [[1, 3], [4, 7]])), aRawMatch('file://c:/2', aLineMatch('preview 2'))];
testObject.add(target);
assert.equal(3, testObject.count());
let actual= testObject.matches();
assert.equal(2, actual.length);
assert.equal('file://c:/1', actual[0].resource().toString());
let actuaMatches= actual[0].matches();
assert.equal(2, actuaMatches.length);
assert.equal('preview 1', actuaMatches[0].text());
assert.ok(new Range(2, 2, 2, 5).equalsRange(actuaMatches[0].range()));
assert.equal('preview 1', actuaMatches[1].text());
assert.ok(new Range(2, 5, 2, 12).equalsRange(actuaMatches[1].range()));
actuaMatches= actual[1].matches();
assert.equal(1, actuaMatches.length);
assert.equal('preview 2', actuaMatches[0].text());
assert.ok(new Range(2, 1, 2, 2).equalsRange(actuaMatches[0].range()));
});
test('Search Result: Dispose disposes matches', function () {
let target1= sinon.spy();
let target2= sinon.spy();
let testObject = aSearchResult();
testObject.add([aRawMatch('file://c:/1', aLineMatch('preview 1')), aRawMatch('file://c:/2', aLineMatch('preview 2'))]);
testObject.matches()[0].onDispose(target1);
testObject.matches()[1].onDispose(target2);
testObject.dispose();
assert.ok(testObject.isEmpty());
assert.ok(target1.calledOnce);
assert.ok(target2.calledOnce);
});
test('Search Result: Removing all line matches and adding back will add file back to result', function () {
let testObject = aSearchResult();
testObject.add([aRawMatch('file://c:/1', aLineMatch('preview 1'))]);
let target= testObject.matches()[0];
let matchToRemove= target.matches()[0];
target.remove(matchToRemove);
assert.ok(testObject.isEmpty());
target.add(matchToRemove, true);
assert.equal(1, testObject.fileCount());
assert.equal(target, testObject.matches()[0]);
});
//// ----- utils
//function lineHasDecorations(model: editor.IModel, lineNumber: number, decorations: { start: number; end: number; }[]): void {
// let lineDecorations:typeof decorations = [];
// let decs = model.getLineDecorations(lineNumber);
// for (let i = 0, len = decs.length; i < len; i++) {
// lineDecorations.push({
// start: decs[i].range.startColumn,
// end: decs[i].range.endColumn
// });
// }
// assert.deepEqual(lineDecorations, decorations);
//}
//
//function lineHasNoDecoration(model: editor.IModel, lineNumber: number): void {
// lineHasDecorations(model, lineNumber, []);
//}
//
//function lineHasDecoration(model: editor.IModel, lineNumber: number, start: number, end: number): void {
// lineHasDecorations(model, lineNumber, [{
// start: start,
// end: end
// }]);
//}
//// ----- end utils
//
//test('Model Highlights', function () {
//
// let fileMatch = instantiation.createInstance(FileMatch, null, toUri('folder\\file.txt'));
// fileMatch.add(new Match(fileMatch, 'line2', 1, 0, 2));
// fileMatch.connect();
// lineHasDecoration(oneModel, 2, 1, 3);
//});
//
//test('Dispose', function () {
//
// let fileMatch = instantiation.createInstance(FileMatch, null, toUri('folder\\file.txt'));
// fileMatch.add(new Match(fileMatch, 'line2', 1, 0, 2));
// fileMatch.connect();
// lineHasDecoration(oneModel, 2, 1, 3);
//
// fileMatch.dispose();
// lineHasNoDecoration(oneModel, 2);
//});
function aFileMatch(path: string, searchResult?: SearchResult, ...lineMatches: ILineMatch[]): FileMatch {
let rawMatch: IFileMatch = {
resource: URI.file('C:\\' + path),
lineMatches: lineMatches
};
return new FileMatch(null, searchResult, rawMatch, null, null);
}
function aSearchResult(): SearchResult {
let searchModel = instantiationService.createInstance(SearchModel);
return searchModel.searchResult;
}
function aRawMatch(resource: string, ...lineMatches: ILineMatch[]): IFileMatch {
return { resource: URI.parse(resource), lineMatches };
}
function aLineMatch(preview: string, lineNumber: number = 1, offsetAndLengths: number[][] = [[0, 1]]): ILineMatch {
return { preview, lineNumber, offsetAndLengths };
}
}); | src/vs/workbench/parts/search/test/common/searchResult.test.ts | 1 | https://github.com/microsoft/vscode/commit/e12eb3dc06b131a8c00fbe61c77ae98311f103e9 | [
0.9983854293823242,
0.23868900537490845,
0.00016429742390755564,
0.0006010163924656808,
0.41243603825569153
] |
{
"id": 10,
"code_window": [
"\t\tassert.equal(lineMatch.range().endColumn, 4);\n",
"\t});\n",
"\n",
"\ttest('Line Match - Remove', function () {\n",
"\t\tlet fileMatch = aFileMatch('folder\\\\file.txt', null, ...[{\n",
"\t\t\t\t\tpreview: 'foo bar',\n",
"\t\t\t\t\tlineNumber: 1,\n",
"\t\t\t\t\toffsetAndLengths: [[0, 3]]\n",
"\t\t}]);\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\tlet fileMatch = aFileMatch('folder\\\\file.txt', aSearchResult(), ...[{\n"
],
"file_path": "src/vs/workbench/parts/search/test/common/searchResult.test.ts",
"type": "replace",
"edit_start_line_idx": 35
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
// Do not edit this file. It is machine generated.
{
"focusSideBar": "Enfocar la barra lateral",
"viewCategory": "Ver"
} | i18n/esn/src/vs/workbench/browser/parts/sidebar/sidebarPart.i18n.json | 0 | https://github.com/microsoft/vscode/commit/e12eb3dc06b131a8c00fbe61c77ae98311f103e9 | [
0.00017498260422144085,
0.00017498260422144085,
0.00017498260422144085,
0.00017498260422144085,
0
] |
{
"id": 10,
"code_window": [
"\t\tassert.equal(lineMatch.range().endColumn, 4);\n",
"\t});\n",
"\n",
"\ttest('Line Match - Remove', function () {\n",
"\t\tlet fileMatch = aFileMatch('folder\\\\file.txt', null, ...[{\n",
"\t\t\t\t\tpreview: 'foo bar',\n",
"\t\t\t\t\tlineNumber: 1,\n",
"\t\t\t\t\toffsetAndLengths: [[0, 3]]\n",
"\t\t}]);\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\tlet fileMatch = aFileMatch('folder\\\\file.txt', aSearchResult(), ...[{\n"
],
"file_path": "src/vs/workbench/parts/search/test/common/searchResult.test.ts",
"type": "replace",
"edit_start_line_idx": 35
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
'use strict';
export interface IJSONSchema {
id?: string;
$schema?: string;
type?: string | string[];
title?: string;
default?: any;
definitions?: IJSONSchemaMap;
description?: string;
properties?: IJSONSchemaMap;
patternProperties?: IJSONSchemaMap;
additionalProperties?: boolean | IJSONSchema;
minProperties?: number;
maxProperties?: number;
dependencies?: IJSONSchemaMap | string[];
items?: IJSONSchema | IJSONSchema[];
minItems?: number;
maxItems?: number;
uniqueItems?: boolean;
additionalItems?: boolean;
pattern?: string;
minLength?: number;
maxLength?: number;
minimum?: number;
maximum?: number;
exclusiveMinimum?: boolean;
exclusiveMaximum?: boolean;
multipleOf?: number;
required?: string[];
$ref?: string;
anyOf?: IJSONSchema[];
allOf?: IJSONSchema[];
oneOf?: IJSONSchema[];
not?: IJSONSchema;
enum?: any[];
format?: string;
defaultSnippets?: { label?: string; description?: string; body: any; }[]; // VSCode extension
errorMessage?: string; // VSCode extension
}
export interface IJSONSchemaMap {
[name: string]:IJSONSchema;
}
| src/vs/base/common/jsonSchema.ts | 0 | https://github.com/microsoft/vscode/commit/e12eb3dc06b131a8c00fbe61c77ae98311f103e9 | [
0.00017575295350980014,
0.00017372306319884956,
0.0001677015097811818,
0.00017501229012850672,
0.000003028567107321578
] |
{
"id": 10,
"code_window": [
"\t\tassert.equal(lineMatch.range().endColumn, 4);\n",
"\t});\n",
"\n",
"\ttest('Line Match - Remove', function () {\n",
"\t\tlet fileMatch = aFileMatch('folder\\\\file.txt', null, ...[{\n",
"\t\t\t\t\tpreview: 'foo bar',\n",
"\t\t\t\t\tlineNumber: 1,\n",
"\t\t\t\t\toffsetAndLengths: [[0, 3]]\n",
"\t\t}]);\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\tlet fileMatch = aFileMatch('folder\\\\file.txt', aSearchResult(), ...[{\n"
],
"file_path": "src/vs/workbench/parts/search/test/common/searchResult.test.ts",
"type": "replace",
"edit_start_line_idx": 35
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
// Do not edit this file. It is machine generated.
{
"DefineKeybindingAction": "Definir enlace de teclado",
"defineKeybinding.initial": "Presione la combinación de teclas deseada y ENTRAR",
"defineKeybinding.kbLayoutErrorMessage": "La distribución del teclado actual no permite reproducir esta combinación de teclas.",
"defineKeybinding.kbLayoutInfoMessage": "Para la distribución del teclado actual, presione ",
"defineKeybinding.start": "Definir enlace de teclado"
} | i18n/esn/src/vs/editor/contrib/defineKeybinding/browser/defineKeybinding.i18n.json | 0 | https://github.com/microsoft/vscode/commit/e12eb3dc06b131a8c00fbe61c77ae98311f103e9 | [
0.0001738172140903771,
0.00017342687351629138,
0.0001730365474941209,
0.00017342687351629138,
3.9033329812809825e-7
] |
{
"id": 11,
"code_window": [
"\tfunction aFileMatch(path: string, searchResult?: SearchResult, ...lineMatches: ILineMatch[]): FileMatch {\n",
"\t\tlet rawMatch: IFileMatch = {\n",
"\t\t\tresource: URI.file('C:\\\\' + path),\n",
"\t\t\tlineMatches: lineMatches\n",
"\t\t};\n",
"\t\treturn new FileMatch(null, searchResult, rawMatch, null, null);\n",
"\t}\n",
"\n",
"\tfunction aSearchResult(): SearchResult {\n",
"\t\tlet searchModel = instantiationService.createInstance(SearchModel);\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\treturn instantiationService.createInstance(FileMatch, null, searchResult, rawMatch);\n"
],
"file_path": "src/vs/workbench/parts/search/test/common/searchResult.test.ts",
"type": "replace",
"edit_start_line_idx": 196
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import * as timer from 'vs/base/common/timer';
import paths = require('vs/base/common/paths');
import strings = require('vs/base/common/strings');
import errors = require('vs/base/common/errors');
import { RunOnceScheduler } from 'vs/base/common/async';
import { IDisposable, Disposable } from 'vs/base/common/lifecycle';
import { TPromise, PPromise } from 'vs/base/common/winjs.base';
import URI from 'vs/base/common/uri';
import { SimpleMap } from 'vs/base/common/map';
import { ArraySet } from 'vs/base/common/set';
import Event, { Emitter } from 'vs/base/common/event';
import * as Search from 'vs/platform/search/common/search';
import { ISearchProgressItem, ISearchComplete, ISearchQuery } from 'vs/platform/search/common/search';
import { ITelemetryService } from 'vs/platform/telemetry/common/telemetry';
import { Range } from 'vs/editor/common/core/range';
import { IModel, IModelDeltaDecoration, OverviewRulerLane, TrackedRangeStickiness, IModelDecorationOptions } from 'vs/editor/common/editorCommon';
import { IInstantiationService } from 'vs/platform/instantiation/common/instantiation';
import { IModelService } from 'vs/editor/common/services/modelService';
import { ISearchService } from 'vs/platform/search/common/search';
import { IReplaceService } from 'vs/workbench/parts/search/common/replace';
import { IProgressRunner } from 'vs/platform/progress/common/progress';
export class Match {
private _lineText: string;
private _id: string;
private _range: Range;
constructor(private _parent: FileMatch, text: string, lineNumber: number, offset: number, length: number) {
this._lineText = text;
this._id = this._parent.id() + '>' + lineNumber + '>' + offset;
this._range = new Range(1 + lineNumber, 1 + offset, 1 + lineNumber, 1 + offset + length);
}
public id(): string {
return this._id;
}
public parent(): FileMatch {
return this._parent;
}
public text(): string {
return this._lineText;
}
public range(): Range {
return this._range;
}
public preview(): { before: string; inside: string; after: string; } {
let before = this._lineText.substring(0, this._range.startColumn - 1),
inside = this._lineText.substring(this._range.startColumn - 1, this._range.endColumn - 1),
after = this._lineText.substring(this._range.endColumn - 1, Math.min(this._range.endColumn + 150, this._lineText.length));
before = strings.lcut(before, 26);
return {
before,
inside,
after,
};
}
}
export class FileMatch extends Disposable {
private static DecorationOption: IModelDecorationOptions = {
stickiness: TrackedRangeStickiness.NeverGrowsWhenTypingAtEdges,
className: 'findMatch',
overviewRuler: {
color: 'rgba(246, 185, 77, 0.7)',
darkColor: 'rgba(246, 185, 77, 0.7)',
position: OverviewRulerLane.Center
}
};
private _onChange= this._register(new Emitter<boolean>());
public onChange: Event<boolean> = this._onChange.event;
private _onDispose= this._register(new Emitter<void>());
public onDispose: Event<void> = this._onDispose.event;
private _resource: URI;
private _model: IModel;
private _modelListener: IDisposable;
private _matches: SimpleMap<string, Match>;
private _removedMatches: ArraySet<string>;
private _updateScheduler: RunOnceScheduler;
private _modelDecorations: string[] = [];
constructor(private _query: Search.IPatternInfo, private _parent: SearchResult, private rawMatch: Search.IFileMatch,
@IModelService private modelService: IModelService, @IReplaceService private replaceService: IReplaceService) {
super();
this._resource = this.rawMatch.resource;
this._matches = new SimpleMap<string, Match>();
this._removedMatches= new ArraySet<string>();
this._updateScheduler = new RunOnceScheduler(this.updateMatches.bind(this), 250);
this.createMatches();
this.registerListeners();
}
private createMatches(): void {
let model = this.modelService ? this.modelService.getModel(this._resource) : null;
if (model) {
this.bindModel(model);
this.updateMatches();
} else {
this.rawMatch.lineMatches.forEach((rawLineMatch) => {
rawLineMatch.offsetAndLengths.forEach(offsetAndLength => {
let match = new Match(this, rawLineMatch.preview, rawLineMatch.lineNumber, offsetAndLength[0], offsetAndLength[1]);
this.add(match);
});
});
}
}
private registerListeners(): void {
if (this.modelService) {
this._register(this.modelService.onModelAdded((model: IModel) => {
if (model.uri.toString() === this._resource.toString()) {
this.bindModel(model);
}
}));
}
}
private bindModel(model: IModel): void {
this._model= model;
this._modelListener= this._model.onDidChangeContent(_ => {
this._updateScheduler.schedule();
});
this._model.onWillDispose(() => this.onModelWillDispose());
this.updateHighlights();
}
private onModelWillDispose(): void {
// Update matches because model might have some dirty changes
this.updateMatches();
this.unbindModel();
}
private unbindModel(): void {
if (this._model) {
this._updateScheduler.cancel();
this._model.deltaDecorations(this._modelDecorations, []);
this._model= null;
this._modelListener.dispose();
}
}
private updateMatches(): void {
// this is called from a timeout and might fire
// after the model has been disposed
if (!this._model) {
return;
}
this._matches = new SimpleMap<string, Match>();
let matches = this._model
.findMatches(this._query.pattern, this._model.getFullModelRange(), this._query.isRegExp, this._query.isCaseSensitive, this._query.isWordMatch);
matches.forEach(range => {
let match= new Match(this, this._model.getLineContent(range.startLineNumber), range.startLineNumber - 1, range.startColumn - 1, range.endColumn - range.startColumn);
if (!this._removedMatches.contains(match.id())) {
this.add(match);
}
});
this._onChange.fire(true);
this.updateHighlights();
}
public updateHighlights(): void {
if (!this._model) {
return;
}
if (this.parent().showHighlights) {
this._modelDecorations = this._model.deltaDecorations(this._modelDecorations, this.matches().map(match => <IModelDeltaDecoration>{
range: match.range(),
options: FileMatch.DecorationOption
}));
} else {
this._modelDecorations = this._model.deltaDecorations(this._modelDecorations, []);
}
}
public id(): string {
return this.resource().toString();
}
public parent(): SearchResult {
return this._parent;
}
public matches(): Match[] {
return this._matches.values();
}
public remove(match: Match): void {
this._matches.delete(match.id());
this._removedMatches.set(match.id());
this._onChange.fire(false);
}
public replace(match: Match, replaceText: string): TPromise<any> {
return this.replaceService.replace(match, replaceText).then(() => {
this._matches.delete(match.id());
this._onChange.fire(false);
});
}
public count(): number {
return this.matches().length;
}
public resource(): URI {
return this._resource;
}
public name(): string {
return paths.basename(this.resource().fsPath);
}
public dispose(): void {
this.unbindModel();
this._onDispose.fire();
super.dispose();
}
public add(match: Match, trigger?: boolean) {
this._matches.set(match.id(), match);
if (trigger) {
this._onChange.fire(true);
}
}
}
export interface IChangeEvent {
elements: FileMatch[];
added?: boolean;
removed?: boolean;
}
export class SearchResult extends Disposable {
private _onChange= this._register(new Emitter<IChangeEvent>());
public onChange: Event<IChangeEvent> = this._onChange.event;
private _fileMatches: SimpleMap<URI, FileMatch>;
private _unDisposedFileMatches: SimpleMap<URI, FileMatch>;
private _query: Search.IPatternInfo= null;
private _showHighlights: boolean;
private _replacingAll: boolean= false;
constructor(private _searchModel: SearchModel, @IReplaceService private replaceService: IReplaceService, @ITelemetryService private telemetryService: ITelemetryService,
@IInstantiationService private instantiationService: IInstantiationService) {
super();
this._fileMatches= new SimpleMap<URI, FileMatch>();
this._unDisposedFileMatches= new SimpleMap<URI, FileMatch>();
}
public set query(query: Search.IPatternInfo) {
this._query= query;
}
public get searchModel(): SearchModel {
return this._searchModel;
}
public add(raw: Search.IFileMatch[], silent:boolean= false): void {
let changed: FileMatch[] = [];
raw.forEach((rawFileMatch) => {
if (!this._fileMatches.has(rawFileMatch.resource)){
let fileMatch= this.instantiationService.createInstance(FileMatch, this._query, this, rawFileMatch);
this.doAdd(fileMatch);
changed.push(fileMatch);
let disposable= fileMatch.onChange(() => this.onFileChange(fileMatch));
fileMatch.onDispose(() => disposable.dispose());
}
});
if (!silent) {
this._onChange.fire({elements: changed, added: true});
}
}
public clear(): void {
let changed: FileMatch[]= this.matches();
this.disposeMatches();
this._onChange.fire({elements: changed, removed: true});
}
public remove(match: FileMatch): void {
this.doRemove(match);
this._onChange.fire({elements: [match], removed: true});
}
public replace(match: FileMatch, replaceText: string): TPromise<any> {
return this.replaceService.replace([match], replaceText).then(() => {
this.doRemove(match, false);
});
}
public replaceAll(replaceText: string, progressRunner: IProgressRunner): TPromise<any> {
this._replacingAll= true;
let replaceAllTimer = this.telemetryService.timedPublicLog('replaceAll.started');
return this.replaceService.replace(this.matches(), replaceText, progressRunner).then(() => {
replaceAllTimer.stop();
this._replacingAll= false;
this.clear();
}, () => {
this._replacingAll= false;
replaceAllTimer.stop();
});
}
public matches(): FileMatch[] {
return this._fileMatches.values();
}
public isEmpty(): boolean {
return this.fileCount() === 0;
}
public fileCount(): number {
return this._fileMatches.size;
}
public count(): number {
return this.matches().reduce<number>((prev, match) => prev + match.count(), 0);
}
public get showHighlights(): boolean {
return this._showHighlights;
}
public toggleHighlights(value: boolean): void {
if (this._showHighlights === value) {
return;
}
this._showHighlights = value;
this.matches().forEach((fileMatch: FileMatch) => {
fileMatch.updateHighlights();
});
}
private onFileChange(fileMatch: FileMatch): void {
let added: boolean= false;
let removed: boolean= false;
if (!this._fileMatches.has(fileMatch.resource())) {
this.doAdd(fileMatch);
added= true;
}
if (fileMatch.count() === 0) {
this.doRemove(fileMatch, false);
added= false;
removed= true;
}
if (!this._replacingAll) {
this._onChange.fire({elements: [fileMatch], added: added, removed: removed});
}
}
private doAdd(fileMatch: FileMatch): void {
this._fileMatches.set(fileMatch.resource(), fileMatch);
if (this._unDisposedFileMatches.has(fileMatch.resource())) {
this._unDisposedFileMatches.delete(fileMatch.resource());
}
}
private doRemove(fileMatch: FileMatch, dispose:boolean= true): void {
this._fileMatches.delete(fileMatch.resource());
if (dispose) {
fileMatch.dispose();
} else {
this._unDisposedFileMatches.set(fileMatch.resource(), fileMatch);
}
}
private disposeMatches(): void {
this._fileMatches.values().forEach((fileMatch: FileMatch) => fileMatch.dispose());
this._unDisposedFileMatches.values().forEach((fileMatch: FileMatch) => fileMatch.dispose());
this._fileMatches.clear();
this._unDisposedFileMatches.clear();
}
public dispose():void {
this.disposeMatches();
super.dispose();
}
}
export class SearchModel extends Disposable {
private _searchResult: SearchResult;
private _searchQuery: ISearchQuery= null;
private _replaceText: string= null;
private currentRequest: PPromise<ISearchComplete, ISearchProgressItem>;
private progressTimer: timer.ITimerEvent;
private doneTimer: timer.ITimerEvent;
private timerEvent: timer.ITimerEvent;
constructor(@ISearchService private searchService, @ITelemetryService private telemetryService: ITelemetryService, @IInstantiationService private instantiationService: IInstantiationService) {
super();
this._searchResult= this.instantiationService.createInstance(SearchResult, this);
}
/**
* Return true if replace is enabled otherwise false
*/
public isReplaceActive():boolean {
return this.replaceText !== null && this.replaceText !== void 0;
}
/**
* Returns the text to replace.
* Can be null if replace is not enabled. Use replace() before.
* Can be empty.
*/
public get replaceText(): string {
return this._replaceText;
}
public set replaceText(replace: string) {
this._replaceText= replace;
}
public get searchResult():SearchResult {
return this._searchResult;
}
/**
* Return true if replace is enabled and replace text is not empty, otherwise false.
* This is necessary in cases handling empty replace text when replace is active.
*/
public hasReplaceText():boolean {
return this.isReplaceActive() && !!this.replaceText;
}
public search(query: ISearchQuery): PPromise<ISearchComplete, ISearchProgressItem> {
this.cancelSearch();
this.searchResult.clear();
this._searchQuery= query;
this._searchResult.query= this._searchQuery.contentPattern;
this.progressTimer = this.telemetryService.timedPublicLog('searchResultsFirstRender');
this.doneTimer = this.telemetryService.timedPublicLog('searchResultsFinished');
this.timerEvent = timer.start(timer.Topic.WORKBENCH, 'Search');
this.currentRequest = this.searchService.search(this._searchQuery);
this.currentRequest.then(value => this.onSearchCompleted(value),
e => this.onSearchError(e),
p => this.onSearchProgress(p));
return this.currentRequest;
}
private onSearchCompleted(completed: ISearchComplete): ISearchComplete {
this.progressTimer.stop();
this.timerEvent.stop();
this.doneTimer.stop();
if (completed) {
this._searchResult.add(completed.results, false);
}
this.telemetryService.publicLog('searchResultsShown', { count: this._searchResult.count(), fileCount: this._searchResult.fileCount() });
return completed;
}
private onSearchError(e: any): void {
if (errors.isPromiseCanceledError(e)) {
this.onSearchCompleted(null);
} else {
this.progressTimer.stop();
this.doneTimer.stop();
this.timerEvent.stop();
}
}
private onSearchProgress(p: ISearchProgressItem): void {
if (p.resource) {
this._searchResult.add([p], true);
this.progressTimer.stop();
}
}
public cancelSearch(): boolean {
if (this.currentRequest) {
this.currentRequest.cancel();
this.currentRequest = null;
return true;
}
return false;
}
public dispose(): void {
this.cancelSearch();
this.searchResult.dispose();
super.dispose();
}
}
export type FileMatchOrMatch = FileMatch | Match; | src/vs/workbench/parts/search/common/searchModel.ts | 1 | https://github.com/microsoft/vscode/commit/e12eb3dc06b131a8c00fbe61c77ae98311f103e9 | [
0.5871109366416931,
0.01227971725165844,
0.0001634653308428824,
0.0001952041930053383,
0.08051159232854843
] |
{
"id": 11,
"code_window": [
"\tfunction aFileMatch(path: string, searchResult?: SearchResult, ...lineMatches: ILineMatch[]): FileMatch {\n",
"\t\tlet rawMatch: IFileMatch = {\n",
"\t\t\tresource: URI.file('C:\\\\' + path),\n",
"\t\t\tlineMatches: lineMatches\n",
"\t\t};\n",
"\t\treturn new FileMatch(null, searchResult, rawMatch, null, null);\n",
"\t}\n",
"\n",
"\tfunction aSearchResult(): SearchResult {\n",
"\t\tlet searchModel = instantiationService.createInstance(SearchModel);\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\treturn instantiationService.createInstance(FileMatch, null, searchResult, rawMatch);\n"
],
"file_path": "src/vs/workbench/parts/search/test/common/searchResult.test.ts",
"type": "replace",
"edit_start_line_idx": 196
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
'use strict';
import { HoverProvider, Hover, TextDocument, Position, Range, CancellationToken } from 'vscode';
import * as Proto from '../protocol';
import { ITypescriptServiceClient } from '../typescriptService';
export default class TypeScriptHoverProvider implements HoverProvider {
private client: ITypescriptServiceClient;
public constructor(client: ITypescriptServiceClient) {
this.client = client;
}
public provideHover(document: TextDocument, position: Position, token: CancellationToken): Promise<Hover> {
let args: Proto.FileLocationRequestArgs = {
file: this.client.asAbsolutePath(document.uri),
line: position.line + 1,
offset: position.character + 1
};
if (!args.file) {
return Promise.resolve<Hover>(null);
}
return this.client.execute('quickinfo', args, token).then((response): Hover => {
let data = response.body;
if (data) {
return new Hover(
[data.documentation, { language: 'typescript', value: data.displayString }],
new Range(data.start.line - 1, data.start.offset - 1, data.end.line - 1, data.end.offset - 1));
}
}, (err) => {
return null;
});
}
} | extensions/typescript/src/features/hoverProvider.ts | 0 | https://github.com/microsoft/vscode/commit/e12eb3dc06b131a8c00fbe61c77ae98311f103e9 | [
0.0001771169772837311,
0.00017298686725553125,
0.0001675260136835277,
0.0001742641325108707,
0.0000034075976600433933
] |
{
"id": 11,
"code_window": [
"\tfunction aFileMatch(path: string, searchResult?: SearchResult, ...lineMatches: ILineMatch[]): FileMatch {\n",
"\t\tlet rawMatch: IFileMatch = {\n",
"\t\t\tresource: URI.file('C:\\\\' + path),\n",
"\t\t\tlineMatches: lineMatches\n",
"\t\t};\n",
"\t\treturn new FileMatch(null, searchResult, rawMatch, null, null);\n",
"\t}\n",
"\n",
"\tfunction aSearchResult(): SearchResult {\n",
"\t\tlet searchModel = instantiationService.createInstance(SearchModel);\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\treturn instantiationService.createInstance(FileMatch, null, searchResult, rawMatch);\n"
],
"file_path": "src/vs/workbench/parts/search/test/common/searchResult.test.ts",
"type": "replace",
"edit_start_line_idx": 196
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
var express = require('express');
var glob = require('glob');
var path = require('path');
var fs = require('fs');
var port = 8887;
var root = path.dirname(__dirname);
function template(str, env) {
return str.replace(/{{\s*([\w_\-]+)\s*}}/g, function (all, part) {
return env[part];
});
}
var app = express();
app.use('/out', express.static(path.join(root, 'out')));
app.use('/test', express.static(path.join(root, 'test')));
app.get('/', function (req, res) {
glob('**/test/**/*.js', {
cwd: path.join(root, 'out'),
ignore: ['**/test/{node,electron*}/**/*.js']
}, function (err, files) {
if (err) { return res.sendStatus(500); }
var modules = files
.map(function (file) { return file.replace(/\.js$/, ''); });
fs.readFile(path.join(__dirname, 'index.html'), 'utf8', function (err, templateString) {
if (err) { return res.sendStatus(500); }
res.send(template(templateString, {
modules: JSON.stringify(modules)
}));
});
});
});
app.listen(port, function () {
console.log('http://localhost:8887/');
}); | test/browser.js | 0 | https://github.com/microsoft/vscode/commit/e12eb3dc06b131a8c00fbe61c77ae98311f103e9 | [
0.00017547198513057083,
0.00017141198622994125,
0.0001675183593761176,
0.0001720408909022808,
0.00000324740972246218
] |
{
"id": 11,
"code_window": [
"\tfunction aFileMatch(path: string, searchResult?: SearchResult, ...lineMatches: ILineMatch[]): FileMatch {\n",
"\t\tlet rawMatch: IFileMatch = {\n",
"\t\t\tresource: URI.file('C:\\\\' + path),\n",
"\t\t\tlineMatches: lineMatches\n",
"\t\t};\n",
"\t\treturn new FileMatch(null, searchResult, rawMatch, null, null);\n",
"\t}\n",
"\n",
"\tfunction aSearchResult(): SearchResult {\n",
"\t\tlet searchModel = instantiationService.createInstance(SearchModel);\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\treturn instantiationService.createInstance(FileMatch, null, searchResult, rawMatch);\n"
],
"file_path": "src/vs/workbench/parts/search/test/common/searchResult.test.ts",
"type": "replace",
"edit_start_line_idx": 196
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
// Do not edit this file. It is machine generated.
{
"editorViewAccessibleLabel": "編輯器內容"
} | i18n/cht/src/vs/editor/common/config/defaultConfig.i18n.json | 0 | https://github.com/microsoft/vscode/commit/e12eb3dc06b131a8c00fbe61c77ae98311f103e9 | [
0.00017528618627693504,
0.00017528618627693504,
0.00017528618627693504,
0.00017528618627693504,
0
] |
{
"id": 0,
"code_window": [
" return (\n",
" <div className=\"flex flex-row h-14 gap-2.5 items-center px-4\">\n",
" <div className=\"flex flex-row\">\n",
" <ChooseChannelPopover config={config} onChangeConfig={onChangeConfig} />\n",
" <Button\n",
" size=\"tiny\"\n",
" type={config.enabled ? 'warning' : 'primary'}\n",
" className=\"rounded-l-none border-l-0\"\n"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" <RealtimeTokensPopover config={config} onChangeConfig={onChangeConfig} />\n"
],
"file_path": "apps/studio/components/interfaces/Realtime/Inspector/Header.tsx",
"type": "add",
"edit_start_line_idx": 19
} | import { useState } from 'react'
import { Button, PopoverContent_Shadcn_, PopoverTrigger_Shadcn_, Popover_Shadcn_, cn } from 'ui'
import { User } from 'data/auth/users-query'
import { ChevronDown, User as IconUser } from 'lucide-react'
import { useRoleImpersonationStateSnapshot } from 'state/role-impersonation-state'
import { getAvatarUrl, getDisplayName } from '../Auth/Users/UserListItem.utils'
import RoleImpersonationSelector from './RoleImpersonationSelector'
export interface RoleImpersonationPopoverProps {
serviceRoleLabel?: string
variant?: 'regular' | 'connected-on-right'
align?: 'center' | 'start' | 'end'
}
const RoleImpersonationPopover = ({
serviceRoleLabel,
variant = 'regular',
align = 'end',
}: RoleImpersonationPopoverProps) => {
const state = useRoleImpersonationStateSnapshot()
const [isOpen, setIsOpen] = useState(false)
const currentRole = state.role?.role ?? serviceRoleLabel ?? 'service role'
return (
<Popover_Shadcn_ open={isOpen} onOpenChange={setIsOpen} modal={false}>
<PopoverTrigger_Shadcn_ asChild>
<Button
size="tiny"
type="default"
className={cn(
'h-[26px] pr-3 gap-0',
variant === 'connected-on-right' && 'rounded-r-none border-r-0'
)}
>
<div className="flex items-center gap-1">
<span className="text-foreground-muted">role</span>
<span>{currentRole}</span>
{state.role?.type === 'postgrest' && state.role.role === 'authenticated' && (
<UserRoleButtonSection user={state.role.user} />
)}
<ChevronDown className="text-muted" strokeWidth={1} size={12} />
</div>
</Button>
</PopoverTrigger_Shadcn_>
<PopoverContent_Shadcn_
className="p-0 w-full overflow-hidden bg-overlay"
side="bottom"
align={align}
>
<RoleImpersonationSelector serviceRoleLabel={serviceRoleLabel} />
</PopoverContent_Shadcn_>
</Popover_Shadcn_>
)
}
export default RoleImpersonationPopover
const UserRoleButtonSection = ({ user }: { user: User }) => {
const avatarUrl = getAvatarUrl(user)
const displayName = getDisplayName(user, user.email ?? user.phone ?? user.id ?? 'Unknown')
return (
<div className="flex gap-1 items-center pl-0.5 pr-1.5 h-[21px] bg-surface-200 rounded-full overflow-hidden">
{avatarUrl ? (
<img className="rounded-full w-[18px] h-[18px]" src={avatarUrl} alt={displayName} />
) : (
<div className="rounded-full w-[18px] h-[18px] bg-surface-100 border flex items-center justify-center text-light">
<IconUser size={12} strokeWidth={2} />
</div>
)}
<span className="truncate max-w-[84px]">{displayName}</span>
</div>
)
}
| apps/studio/components/interfaces/RoleImpersonationSelector/RoleImpersonationPopover.tsx | 1 | https://github.com/supabase/supabase/commit/ff2e283430c0171b07442fbde6c74777ce75fcc4 | [
0.004510753788053989,
0.0013535014586523175,
0.00016481774218846112,
0.00027212666464038193,
0.001641843467950821
] |
{
"id": 0,
"code_window": [
" return (\n",
" <div className=\"flex flex-row h-14 gap-2.5 items-center px-4\">\n",
" <div className=\"flex flex-row\">\n",
" <ChooseChannelPopover config={config} onChangeConfig={onChangeConfig} />\n",
" <Button\n",
" size=\"tiny\"\n",
" type={config.enabled ? 'warning' : 'primary'}\n",
" className=\"rounded-l-none border-l-0\"\n"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" <RealtimeTokensPopover config={config} onChangeConfig={onChangeConfig} />\n"
],
"file_path": "apps/studio/components/interfaces/Realtime/Inspector/Header.tsx",
"type": "add",
"edit_start_line_idx": 19
} | import * as Tooltip from '@radix-ui/react-tooltip'
import { PropsWithChildren } from 'react'
import { Button, IconExternalLink } from 'ui'
interface ProductEmptyStateProps {
title?: string
size?: 'medium' | 'large'
ctaButtonLabel?: string
infoButtonLabel?: string
infoButtonUrl?: string
onClickCta?: () => void
loading?: boolean
disabled?: boolean
disabledMessage?: string
}
const ProductEmptyState = ({
title = '',
size = 'medium',
children,
ctaButtonLabel = '',
infoButtonLabel = '',
infoButtonUrl = '',
onClickCta = () => {},
loading = false,
disabled = false,
disabledMessage = '',
}: PropsWithChildren<ProductEmptyStateProps>) => {
const hasAction = (ctaButtonLabel && onClickCta) || (infoButtonUrl && infoButtonLabel)
return (
<div className="flex h-full w-full items-center justify-center">
<div className="flex space-x-4 rounded border border-overlay bg-surface-100 p-6 shadow-md">
{/* A graphic can probably be placed here as a sibling to the div below*/}
<div className="flex flex-col">
<div className={`${size === 'medium' ? 'w-80' : 'w-[400px]'} space-y-4`}>
<h5>{title}</h5>
<div className="flex flex-col space-y-2">{children}</div>
{hasAction && (
<div className="flex items-center space-x-2">
{ctaButtonLabel && onClickCta && (
<Tooltip.Root delayDuration={0}>
<Tooltip.Trigger asChild>
<Button
type="primary"
onClick={onClickCta}
loading={loading}
disabled={loading || disabled}
>
{ctaButtonLabel}
</Button>
</Tooltip.Trigger>
{disabled && disabledMessage.length > 0 && (
<Tooltip.Portal>
<Tooltip.Content side="bottom">
<Tooltip.Arrow className="radix-tooltip-arrow" />
<div
className={[
'rounded bg-alternative py-1 px-2 leading-none shadow',
'border border-background',
].join(' ')}
>
<span className="text-xs text-foreground">{disabledMessage}</span>
</div>
</Tooltip.Content>
</Tooltip.Portal>
)}
</Tooltip.Root>
)}
{infoButtonUrl && infoButtonLabel ? (
<Button type="default" icon={<IconExternalLink size={14} strokeWidth={1.5} />}>
<a target="_blank" rel="noreferrer" href={infoButtonUrl}>
{infoButtonLabel}
</a>
</Button>
) : null}
</div>
)}
</div>
</div>
</div>
</div>
)
}
export default ProductEmptyState
| apps/studio/components/to-be-cleaned/ProductEmptyState.tsx | 0 | https://github.com/supabase/supabase/commit/ff2e283430c0171b07442fbde6c74777ce75fcc4 | [
0.005070085637271404,
0.0008597937412559986,
0.0001661211281316355,
0.00026901657111011446,
0.0015092268586158752
] |