Example #1
1
File: file.js Project: cjxgm/etc
 return __awaiter(this, void 0, void 0, function* () {
     if (!this._arguments.name) {
         // Open an empty file
         if (this._arguments.position === FilePosition.CurrentWindow) {
             yield vscode.commands.executeCommand("workbench.action.files.newUntitledFile");
         }
         else {
             yield vscode.commands.executeCommand("workbench.action.splitEditor");
         }
         return;
     }
     let currentFilePath = vscode.window.activeTextEditor.document.uri.path;
     let newFilePath = path.isAbsolute(this._arguments.name) ?
         this._arguments.name :
         path.join(path.dirname(currentFilePath), this._arguments.name);
     if (newFilePath !== currentFilePath) {
         const newFileDoesntExist = !(yield this.fileExists(newFilePath));
         const newFileHasNoExtname = path.extname(newFilePath) === '';
         if (newFileDoesntExist && newFileHasNoExtname) {
             const pathWithExtname = newFilePath + path.extname(currentFilePath);
             if (yield this.fileExists(pathWithExtname)) {
                 newFilePath = pathWithExtname;
             }
         }
         let folder = vscode.Uri.file(newFilePath);
         yield vscode.commands.executeCommand("vscode.open", folder, this._arguments.position === FilePosition.NewWindow ? this.getViewColumnToRight() : this.getActiveViewColumn());
     }
 });
 resources.forEach(function (resource) {
     // sln files
     if (hasCsProjFiles && /\.sln$/.test(resource.fsPath)) {
         targets.push({
             label: paths.basename(resource.fsPath),
             description: vscode_1.workspace.asRelativePath(paths.dirname(resource.fsPath)),
             resource: resource,
             target: resource,
             directory: vscode_1.Uri.file(paths.dirname(resource.fsPath))
         });
     }
     // project.json files
     if (/project.json$/.test(resource.fsPath)) {
         var dirname = paths.dirname(resource.fsPath);
         hasProjectJson = true;
         hasProjectJsonAtRoot = hasProjectJsonAtRoot || dirname === root.fsPath;
         targets.push({
             label: paths.basename(resource.fsPath),
             description: vscode_1.workspace.asRelativePath(paths.dirname(resource.fsPath)),
             resource: resource,
             target: vscode_1.Uri.file(dirname),
             directory: vscode_1.Uri.file(dirname)
         });
     }
 });
Example #3
0
 vscode.window.showQuickPick(itemsSorted, options).then(function (selection) {
     if (typeof selection === "undefined") {
         if (activeTextEditorPath === "") {
             return;
         }
         else {
             var uriDocument = vscode.Uri.file(activeTextEditorPath);
             vscode.workspace.openTextDocument(uriDocument).then(function (doc) {
                 vscode.window.showTextDocument(doc).then(function (editor) {
                     revealLine(currentLine - 1);
                     return;
                 });
             });
         }
     }
     if (typeof selection === "undefined") {
         return;
     }
     if (!selection.detail) {
         revealLine(parseInt(selection.label, 10) - 1);
     }
     else {
         var newPath = vscode.workspace.rootPath + selection.detail.toString();
         var uriDocument = vscode.Uri.file(newPath);
         vscode.workspace.openTextDocument(uriDocument).then(function (doc) {
             vscode.window.showTextDocument(doc).then(function (editor) {
                 revealLine(parseInt(selection.label, 10) - 1);
             });
         });
     }
 });
Example #4
0
o.diff = function(left, right, title){
  if(fileUtil.existSync(left) && fileUtil.existSync(right))
  {
    if(!title)
    {
      title = "Local : " + pathUtil.getFileName(left) + " ↔ Remote : " + pathUtil.getFileName(right);
    }
    vscode.commands.executeCommand("vscode.diff", vscode.Uri.file(left), vscode.Uri.file(right), title);
  }
  else this.msg("Need the two files.");
};
 return serverUtils.runCodeAction(this._server, req).then(response => {
     if (response && Array.isArray(response.Changes)) {
         let edit = new vscode.WorkspaceEdit();
         let fileToOpen = null;
         let renamedFiles = [];
         for (let change of response.Changes) {
             if (change.ModificationType == protocol_1.FileModificationType.Renamed) {
                 // The file was renamed. Omnisharp has already persisted
                 // the right changes to disk. We don't need to try to
                 // apply text changes (and will skip this file if we see an edit)
                 renamedFiles.push(vscode_1.Uri.file(change.FileName));
             }
         }
         for (let change of response.Changes) {
             if (change.ModificationType == protocol_1.FileModificationType.Opened) {
                 // The CodeAction requested that we open a file. 
                 // Record that file name and keep processing CodeActions.
                 // If a CodeAction requests that we open multiple files 
                 // we only open the last one (what would it mean to open multiple files?)
                 fileToOpen = vscode.Uri.file(change.FileName);
             }
             if (change.ModificationType == protocol_1.FileModificationType.Modified) {
                 let uri = vscode.Uri.file(change.FileName);
                 if (renamedFiles.some(r => r == uri)) {
                     // This file got renamed. Omnisharp has already
                     // persisted the new file with any applicable changes.
                     continue;
                 }
                 let edits = [];
                 for (let textChange of change.Changes) {
                     edits.push(vscode.TextEdit.replace(typeConversion_1.toRange2(textChange), textChange.NewText));
                 }
                 edit.set(uri, edits);
             }
         }
         let applyEditPromise = vscode.workspace.applyEdit(edit);
         // Unfortunately, the textEditor.Close() API has been deprecated
         // and replaced with a command that can only close the active editor.
         // If files were renamed that weren't the active editor, their tabs will
         // be left open and marked as "deleted" by VS Code
         let next = applyEditPromise;
         if (renamedFiles.some(r => r.fsPath == vscode.window.activeTextEditor.document.uri.fsPath)) {
             next = applyEditPromise.then(_ => {
                 return vscode.commands.executeCommand("workbench.action.closeActiveEditor");
             });
         }
         return fileToOpen != null
             ? next.then(_ => {
                 return vscode.commands.executeCommand("vscode.open", fileToOpen);
             })
             : next;
     }
 }, (error) => __awaiter(this, void 0, void 0, function* () {
Example #6
0
 constructor(webviewName, logData) {
     this.logData = logData;
     this.panel = vscode.window.createWebviewPanel('log Viewer', webviewName, vscode.ViewColumn.One, { enableScripts: true, retainContextWhenHidden: true });
     //Get path to resource on disk
     const extensionPath = extensionVariables_1.ext.context.extensionPath;
     const scriptFile = vscode.Uri.file(path.join(extensionPath, 'commands', 'azureCommands', 'acr-logs-utils', 'logScripts.js')).with({ scheme: 'vscode-resource' });
     const styleFile = vscode.Uri.file(path.join(extensionPath, 'commands', 'azureCommands', 'acr-logs-utils', 'style', 'stylesheet.css')).with({ scheme: 'vscode-resource' });
     const iconStyle = vscode.Uri.file(path.join(extensionPath, 'commands', 'azureCommands', 'acr-logs-utils', 'style', 'fabric-components', 'css', 'vscmdl2-icons.css')).with({ scheme: 'vscode-resource' });
     //Populate Webview
     this.panel.webview.html = this.getBaseHtml(scriptFile, styleFile, iconStyle);
     this.setupIncomingListeners();
     this.addLogsToWebView();
 }
Example #7
0
 return __awaiter(this, void 0, void 0, function* () {
     if (options.token && options.token.isCancellationRequested) {
         return;
     }
     const cwdUri = options.cwd ? vscode_1.Uri.file(options.cwd) : undefined;
     const workspaceService = this.serviceContainer.get(types_1.IWorkspaceService);
     if (!workspaceService.hasWorkspaceFolders) {
         throw new Error('Please open a workspace');
     }
     let workspaceFolder = workspaceService.getWorkspaceFolder(cwdUri);
     if (!workspaceFolder) {
         workspaceFolder = workspaceService.workspaceFolders[0];
     }
     const cwd = cwdUri ? cwdUri.fsPath : workspaceFolder.uri.fsPath;
     const configurationService = this.serviceContainer.get(types_2.IConfigurationService).getSettings(vscode_1.Uri.file(cwd));
     const useExperimentalDebugger = configurationService.unitTest.useExperimentalDebugger === true;
     const debugManager = this.serviceContainer.get(types_1.IDebugService);
     const debuggerType = useExperimentalDebugger ? 'pythonExperimental' : 'python';
     const debugArgs = this.fixArgs(options.args, options.testProvider, useExperimentalDebugger);
     const program = this.getTestLauncherScript(options.testProvider, useExperimentalDebugger);
     return debugManager.startDebugging(workspaceFolder, {
         name: 'Debug Unit Test',
         type: debuggerType,
         request: 'launch',
         program,
         cwd,
         args: debugArgs,
         console: 'none',
         debugOptions: [Contracts_1.DebugOptions.RedirectOutput]
     }).then(() => void (0));
 });
function getLinkItems(document) {
	const INCLUDE_REGEXP = /(include\s+['"]?)(\S+)(?:$|['";])/g;

	/** @type {string} */
	let code = document.getText(), baseFile = document.fileName;

	/** @type {RegExpMatchArray} */
	let matched = null;
	let result = [];

	try {
		while ((matched = INCLUDE_REGEXP.exec(code)) != null) {
			let p = matched[2];
			if (baseFile && !isAbsolute(p))
				p = resolve(join(dirname(baseFile), p));
			if (!existsSync(p) || !statSync(p).isFile())
				continue;

			let offset1 = matched.index + matched[1].length, offset2 = offset1 + matched[2].length;
			result.push(new vscode.DocumentLink(
				new vscode.Range(document.positionAt(offset1), document.positionAt(offset2)),
				vscode.Uri.file(p)));
		}
	} catch (ex) { console.error(ex); }
	return result;
}
Example #9
0
 errors.forEach(error => {
     let canonicalFile = vscode.Uri.file(error.file).toString();
     let startColumn = 0;
     let endColumn = 1;
     if (document && document.uri.toString() === canonicalFile) {
         let range = new vscode.Range(error.line - 1, 0, error.line - 1, document.lineAt(error.line - 1).range.end.character + 1);
         let text = document.getText(range);
         let [_, leading, trailing] = /^(\s*).*(\s*)$/.exec(text);
         if (!error.col) {
             startColumn = leading.length;
         }
         else {
             startColumn = error.col - 1; // range is 0-indexed
         }
         endColumn = text.length - trailing.length;
     }
     let range = new vscode.Range(error.line - 1, startColumn, error.line - 1, endColumn);
     let severity = mapSeverityToVSCodeSeverity(error.severity);
     let diagnostic = new vscode.Diagnostic(range, error.msg, severity);
     let diagnostics = diagnosticMap.get(canonicalFile);
     if (!diagnostics) {
         diagnostics = new Map();
     }
     if (!diagnostics[severity]) {
         diagnostics[severity] = [];
     }
     diagnostics[severity].push(diagnostic);
     diagnosticMap.set(canonicalFile, diagnostics);
 });
Example #10
0
 onDidSelectItem: function (item) {
     var filePath;
     // no detail - previously active document
     if (!item.detail) {
         filePath = activeTextEditorPath;
     }
     else {
         // with octicon - document outside project
         if (item.detail.toString().indexOf("$(file-directory) ") === 0) {
             filePath = item.detail.toString().split("$(file-directory) ").pop();
         }
         else {
             filePath = vscode.workspace.rootPath + item.detail.toString();
         }
     }
     if (vscode.window.activeTextEditor && vscode.window.activeTextEditor.document.uri.fsPath.toLowerCase() === filePath.toLowerCase()) {
         revealLine(parseInt(item.label, 10) - 1);
     }
     else {
         var uriDocument = vscode.Uri.file(filePath);
         vscode.workspace.openTextDocument(uriDocument).then(function (doc) {
             vscode.window.showTextDocument(doc, undefined, true).then(function (editor) {
                 revealLine(parseInt(item.label, 10) - 1);
             });
         });
     }
 }
export function generateCodeLenses(packageCollection, document) {
  const documentUrl = Uri.file(document.fileName);
  return Promise.all(packageCollection)
    .then(results => {
      const codeLenses = [];
      results.forEach(entryOrEntries => {
        if (Array.isArray(entryOrEntries)) {
          entryOrEntries.forEach(
            (entry, order) => {
              entry.package.order = order;
              codeLenses.push(createCodeLensFromEntry(entry, document, documentUrl));
            }
          );
          return;
        }

        codeLenses.push(
          createCodeLensFromEntry(
            {
              node: entryOrEntries.node,
              package: createPackageFromNode(entryOrEntries.node)
            },
            document,
            documentUrl
          )
        );

      });

      return codeLenses;
    });
}
 serverUtils.codeCheck(this._server, { FileName: null }, this._projectValidation.token).then(value => {
     let quickFixes = value.QuickFixes
         .filter(DiagnosticsProvider._shouldInclude)
         .sort((a, b) => a.FileName.localeCompare(b.FileName));
     let entries = [];
     let lastEntry;
     for (let quickFix of quickFixes) {
         let diag = DiagnosticsProvider._asDiagnostic(quickFix);
         let uri = vscode.Uri.file(quickFix.FileName);
         if (lastEntry && lastEntry[0].toString() === uri.toString()) {
             lastEntry[1].push(diag);
         }
         else {
             // We're replacing all diagnostics in this file. Pushing an entry with undefined for
             // the diagnostics first ensures that the previous diagnostics for this file are
             // cleared. Otherwise, new entries will be merged with the old ones.
             entries.push([uri, undefined]);
             lastEntry = [uri, [diag]];
             entries.push(lastEntry);
         }
     }
     // Clear diagnostics for files that no longer have any diagnostics.
     this._diagnostics.forEach((uri, diagnostics) => {
         if (!entries.find(tuple => tuple[0].toString() === uri.toString())) {
             this._diagnostics.delete(uri);
         }
     });
     // replace all entries
     this._diagnostics.set(entries);
 });
Example #13
0
     .then(data => {
     const html = data[0];
     const htmlFileName = data[1];
     const htmlContent = `
             <!DOCTYPE html>
             <head><style type="text/css"> html, body{ height:100%; width:100%; } </style>
             <script type="text/javascript">
                 function start(){
                     var color = '';
                     var fontFamily = '';
                     var fontSize = '';
                     try {
                         computedStyle = window.getComputedStyle(document.body);
                         color = computedStyle.color + '';
                         fontFamily = computedStyle.fontFamily;
                         fontSize = computedStyle.fontSize;
                     }
                     catch(ex){
                     }
                     document.getElementById('myframe').src = '${vscode.Uri.file(htmlFileName).toString()}?color=' + encodeURIComponent(color) + "&fontFamily=" + encodeURIComponent(fontFamily) + "&fontSize=" + encodeURIComponent(fontSize);
                 }
             </script>
             </head>
             <body onload="start()">
             <iframe id="myframe" frameborder="0" style="border: 0px solid transparent;height:100%;width:100%;"
             src="" seamless></iframe></body></html>`;
     let def = helpers.createDeferred();
     fs.writeFile(htmlFileName, html, err => {
         if (err) {
             return def.reject(err);
         }
         def.resolve(htmlContent);
     });
     return def.promise;
 });
 serverUtils.codeCheck(_this._server, { Filename: null }, _this._projectValidation.token).then(function (value) {
     var quickFixes = value.QuickFixes.sort(function (a, b) { return a.FileName.localeCompare(b.FileName); });
     var entries = [];
     var lastEntry;
     for (var _i = 0, quickFixes_1 = quickFixes; _i < quickFixes_1.length; _i++) {
         var quickFix = quickFixes_1[_i];
         var diag = DiagnosticsProvider._asDiagnostic(quickFix);
         var uri = vscode_1.Uri.file(quickFix.FileName);
         if (lastEntry && lastEntry[0].toString() === uri.toString()) {
             lastEntry[1].push(diag);
         }
         else {
             // We're replacing all diagnostics in this file. Pushing an entry with undefined for
             // the diagnostics first ensures that the previous diagnostics for this file are
             // cleared. Otherwise, new entries will be merged with the old ones.
             entries.push([uri, undefined]);
             lastEntry = [uri, [diag]];
             entries.push(lastEntry);
         }
     }
     // Clear diagnostics for files that no longer have any diagnostics.
     _this._diagnostics.forEach(function (uri, diagnostics) {
         if (!entries.find(function (tuple) { return tuple[0] === uri; })) {
             _this._diagnostics.delete(uri);
         }
     });
     // replace all entries
     _this._diagnostics.set(entries);
 });
            cmd.stdout.on('data', function(data) {
                //Logs output to console
                console.log(String(data));

                //If error is found in output, display an error to user
                if (String(data).toLowerCase().indexOf("error") > 0) {
                    //Show error
                    vscode.window.setStatusBarMessage("Can't create PDF, see " + getFileName(pathFull) + ".vscodeLog", 12000);

                    if (vscode.workspace.getConfiguration('latexCompile').openLogAfterError) {
                        var consoleLogFile = vscode.Uri.file(path + fileName + ".vscodeLog");

                        vscode.workspace.openTextDocument(consoleLogFile).then(function(d) {
                            vscode.window.showTextDocument(d);
                            // Open file, add console string, save file.
                            var fd = fs.openSync(path + fileName + ".vscodeLog", 'w+');
                            var buffer = new Buffer(String(data));
                            fs.writeSync(fd, buffer, 0, buffer.length);
                            fs.close(fd);

                        });

                    }

                }
            });
Example #16
0
 fs.readFile(resourceJson, 'utf8', function (err, data) {
     let glob = '**/*.css';
     if (err) {
         vsc.workspace.findFiles(glob, '').then(function (uris) {
             for (let i = 0; i < uris.length; i++) {
                 parse(uris[i]);
             }
         });
     }
     else {
         let resources = JSON.parse(data);
         for (let key in resources.css) {
             for (let resource of resources.css[key]) {
                 let uri = vsc.Uri.file(path.resolve(vsc.workspace.rootPath, resource));
                 resourceJsonPaths.push(uri.fsPath);
                 parse(uri);
             }
         }
     }
     let watcher = vsc.workspace.createFileSystemWatcher(glob);
     watcher.onDidCreate(function (uri) {
         if (resourceJsonPaths.length === 0 || resourceJsonPaths.indexOf(uri.fsPath) !== -1) {
             parse(uri);
         }
     });
     watcher.onDidChange(function (uri) {
         if (resourceJsonPaths.length === 0 || resourceJsonPaths.indexOf(uri.fsPath) !== -1) {
             parse(uri);
         }
     });
     watcher.onDidDelete(function (uri) {
         delete map[uri.fsPath];
     });
     context.subscriptions.push(watcher);
 });
Example #17
0
 constructor(workspaceInfo, workspaceFolder = undefined) {
     if (workspaceFolder) {
         this.workspaceFolder = workspaceFolder;
     }
     else {
         let resourcePath = undefined;
         if (!resourcePath && workspaceInfo.Cake) {
             resourcePath = workspaceInfo.Cake.Path;
         }
         if (!resourcePath && workspaceInfo.ScriptCs) {
             resourcePath = workspaceInfo.ScriptCs.Path;
         }
         if (!resourcePath && workspaceInfo.DotNet && workspaceInfo.DotNet.Projects.length > 0) {
             resourcePath = workspaceInfo.DotNet.Projects[0].Path;
         }
         if (!resourcePath && workspaceInfo.MsBuild) {
             resourcePath = workspaceInfo.MsBuild.SolutionPath;
         }
         this.workspaceFolder = vscode.workspace.getWorkspaceFolder(vscode.Uri.file(resourcePath));
     }
     this.vscodeFolder = path.join(this.workspaceFolder.uri.fsPath, '.vscode');
     this.tasksJsonPath = path.join(this.vscodeFolder, 'tasks.json');
     this.launchJsonPath = path.join(this.vscodeFolder, 'launch.json');
     this.initializeProjectData(workspaceInfo);
 }
Example #18
0
 return definitionLocation(document, position, this.goConfig, token).then(definitionInfo => {
     if (definitionInfo == null || definitionInfo.file == null)
         return null;
     let definitionResource = vscode.Uri.file(definitionInfo.file);
     let pos = new vscode.Position(definitionInfo.line, definitionInfo.column);
     return new vscode.Location(definitionResource, pos);
 }, err => {
Example #19
0
 return __awaiter(this, void 0, void 0, function* () {
     const settings = configSettings_1.PythonSettings.getInstance(vscode.Uri.file(rootDir));
     if (settings.unitTest.pyTestEnabled ||
         settings.unitTest.nosetestsEnabled ||
         settings.unitTest.unittestEnabled) {
         return;
     }
     if (!settings.unitTest.promptToConfigure) {
         return;
     }
     const yes = 'Yes';
     const no = 'Later';
     const noNotAgain = 'No, don\'t ask again';
     const hasTests = checkForExistenceOfTests(rootDir);
     if (!hasTests) {
         return;
     }
     const item = yield vscode.window.showInformationMessage('You seem to have tests, would you like to enable a test framework?', yes, no, noNotAgain);
     if (!item || item === no) {
         return;
     }
     if (item === yes) {
         yield promptToEnableAndConfigureTestFramework(vscode.workspace.getWorkspaceFolder(vscode.Uri.file(rootDir)).uri, installer, outputChannel);
     }
     else {
         const pythonConfig = vscode.workspace.getConfiguration('python');
         yield pythonConfig.update('unitTest.promptToConfigure', false);
     }
 });
     .then(function (output) {
     console.log(output);
     try {
         var bucket = new Array();
         if (output != null) {
             output.toString().split(/\r?\n/)
                 .forEach(function (value, index, array) {
                 var result = self._global.parseLine(value);
                 if (result == null)
                     return;
                 result.label = result.path;
                 result.description = result.info;
                 console.log(result.path);
                 bucket.push(result);
             });
         }
         if (bucket.length == 1) {
             return new vscode.Location(vscode.Uri.file(bucket[0].path), new vscode.Position(bucket[0].line, 0));
         }
         else if (bucket.length == 0) {
             return null;
         }
         var matches = new Array();
         bucket.forEach(function (value, index, array) {
             matches.push(new vscode.Location(vscode.Uri.file(value.path), new vscode.Position(value.line, 0)));
         });
         return matches;
     }
     catch (ex) {
         console.error("Error: " + ex);
     }
     return null;
 });
Example #21
0
 _applyShowQuickRepoHistoryCommand(title, lens, blame, commit) {
     lens.command = {
         title: title,
         command: configuration_1.CodeLensCommand.ShowQuickRepoHistory,
         arguments: [vscode_1.Uri.file(lens.uri.fsPath)]
     };
     return lens;
 }
Example #22
0
 _applyShowQuickCommitFileDetailsCommand(title, lens, blame, commit) {
     lens.command = {
         title: title,
         command: configuration_1.CodeLensCommand.ShowQuickCommitFileDetails,
         arguments: [vscode_1.Uri.file(lens.uri.fsPath), commit.sha, commit]
     };
     return lens;
 }
Example #23
0
 _applyBlameAnnotateCommand(title, lens, blame) {
     lens.command = {
         title: title,
         command: commands_1.Commands.ToggleBlame,
         arguments: [vscode_1.Uri.file(lens.uri.fsPath)]
     };
     return lens;
 }
Example #24
0
 constructor() {
     this.booleanEvent = new vscode.EventEmitter();
     this.stringEvent = new vscode.EventEmitter();
     this.RootPath = "/";
     this.RootUri = vscode.Uri.file("/");
     this.Name = "(empty)";
     this.TrackedDocuments = new Set();
 }
function parseData(data) {
    if (data) {
        var definitionResource = vscode.Uri.file(data.definition.fileName);
        var range = new vscode.Range(data.definition.lineIndex, data.definition.columnIndex, data.definition.lineIndex, data.definition.columnIndex);
        return new vscode.Location(definitionResource, range);
    }
    return null;
}
Example #26
0
 filePatches.forEach(patch => {
     const indexOfAtAt = patch.indexOf('@@');
     if (indexOfAtAt === -1) {
         return;
     }
     const fileNameLines = patch.substring(0, indexOfAtAt).split(/\r?\n/g)
         .map(line => line.trim())
         .filter(line => line.length > 0 &&
         line.toLowerCase().endsWith('.py') &&
         line.indexOf(' a') > 0);
     if (patch.startsWith('---')) {
         // Strip the first two lines
         patch = patch.substring(indexOfAtAt);
     }
     if (patch.length === 0) {
         return;
     }
     // We can't find the find name
     if (fileNameLines.length === 0) {
         return;
     }
     let fileName = fileNameLines[0].substring(fileNameLines[0].indexOf(' a') + 3).trim();
     fileName = workspaceRoot && !path.isAbsolute(fileName) ? path.resolve(workspaceRoot, fileName) : fileName;
     if (!fs.existsSync(fileName)) {
         return;
     }
     // Remove the text added by unified_diff
     // # Work around missing newline (http://bugs.python.org/issue2142).
     patch = patch.replace(/\\ No newline at end of file[\r\n]/, '');
     const d = new dmp.diff_match_patch();
     const patches = patch_fromText.call(d, patch);
     if (!Array.isArray(patches) || patches.length === 0) {
         throw new Error('Unable to parse Patch string');
     }
     const fileSource = fs.readFileSync(fileName).toString('utf8');
     const fileUri = vscode.Uri.file(fileName);
     // Add line feeds and build the text edits
     patches.forEach(p => {
         p.diffs.forEach(diff => {
             diff[1] += os_1.EOL;
         });
         getTextEditsInternal(fileSource, p.diffs, p.start1).forEach(edit => {
             switch (edit.action) {
                 case EditAction.Delete:
                     workspaceEdit.delete(fileUri, new vscode_1.Range(edit.start, edit.end));
                     break;
                 case EditAction.Insert:
                     workspaceEdit.insert(fileUri, edit.start, edit.text);
                     break;
                 case EditAction.Replace:
                     workspaceEdit.replace(fileUri, new vscode_1.Range(edit.start, edit.end), edit.text);
                     break;
                 default:
                     break;
             }
         });
     });
 });
Example #27
0
 return __awaiter(this, void 0, void 0, function* () {
     if (this._inputs.length > 0) {
         const result = this._inputs.shift();
         if (result) {
             return [vscode.Uri.file(result)];
         }
     }
     throw new Error(`Unexpected call to showOpenDialog. Message: ${options.openLabel}`);
 });
Example #28
0
 getWorkspaceFolder(folder, config) {
     if (folder) {
         return folder.uri;
     }
     const program = this.getProgram(config);
     const workspaceService = this.serviceContainer.get(types_1.IWorkspaceService);
     if (!Array.isArray(workspaceService.workspaceFolders) || workspaceService.workspaceFolders.length === 0) {
         return program ? vscode_1.Uri.file(path.dirname(program)) : undefined;
     }
     if (workspaceService.workspaceFolders.length === 1) {
         return workspaceService.workspaceFolders[0].uri;
     }
     if (program) {
         const workspaceFolder = workspaceService.getWorkspaceFolder(vscode_1.Uri.file(program));
         if (workspaceFolder) {
             return workspaceFolder.uri;
         }
     }
 }
 data['suggestions'].forEach((s) => {
     if (s['location']) {
         var match = s['location'].match(/^(.*?):([0-9]*?):([0-9]*)$/);
         var uri = vscode.Uri.file(match[1]);
         if (uri) {
             var location = new vscode.Location(uri, new vscode.Position(parseInt(match[2]), parseInt(match[3])));
             result.push(location);
         }
     }
 });
Example #30
0
 static parseData(data, possibleWord) {
     if (data && Array.isArray(data.definitions) && data.definitions.length > 0) {
         const definitions = data.definitions.filter(d => d.text === possibleWord);
         const definition = definitions.length > 0 ? definitions[0] : data.definitions[data.definitions.length - 1];
         const definitionResource = vscode.Uri.file(definition.fileName);
         const range = new vscode.Range(definition.range.startLine, definition.range.startColumn, definition.range.endLine, definition.range.endColumn);
         return new vscode.Location(definitionResource, range);
     }
     return null;
 }