This commit is contained in:
Michael Lively
2024-05-13 15:55:25 -07:00
parent 209ce0e81b
commit fcf3bc2d80
16 changed files with 21596 additions and 0 deletions

View File

@ -0,0 +1,24 @@
{
"root": true,
"parser": "@typescript-eslint/parser",
"parserOptions": {
"ecmaVersion": 6,
"sourceType": "module"
},
"plugins": [
"@typescript-eslint"
],
"rules": {
"@typescript-eslint/naming-convention": "warn",
"@typescript-eslint/semi": "warn",
"curly": "warn",
"eqeqeq": "warn",
"no-throw-literal": "warn",
"semi": "off"
},
"ignorePatterns": [
"out",
"dist",
"**/*.d.ts"
]
}

View File

@ -0,0 +1,7 @@
{
// See http://go.microsoft.com/fwlink/?LinkId=827846
// for the documentation about the extensions.json format
"recommendations": [
"dbaeumer.vscode-eslint"
]
}

View File

@ -0,0 +1,34 @@
// A launch configuration that compiles the extension and then opens it inside a new window
// Use IntelliSense to learn about possible attributes.
// Hover to view descriptions of existing attributes.
// For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
{
"version": "0.2.0",
"configurations": [
{
"name": "Run Extension",
"type": "extensionHost",
"request": "launch",
"args": [
"--extensionDevelopmentPath=${workspaceFolder}"
],
"outFiles": [
"${workspaceFolder}/out/**/*.js"
],
"preLaunchTask": "${defaultBuildTask}"
},
{
"name": "Extension Tests",
"type": "extensionHost",
"request": "launch",
"args": [
"--extensionDevelopmentPath=${workspaceFolder}",
"--extensionTestsPath=${workspaceFolder}/out/test/suite/index"
],
"outFiles": [
"${workspaceFolder}/out/test/**/*.js"
],
"preLaunchTask": "${defaultBuildTask}"
}
]
}

View File

@ -0,0 +1,11 @@
// Place your settings in this file to overwrite default and user settings.
{
"files.exclude": {
"out": false // set this to true to hide the "out" folder with the compiled JS files
},
"search.exclude": {
"out": true // set this to false to include "out" folder in search results
},
// Turn off tsc task auto detection since we have the necessary tasks as npm scripts
"typescript.tsc.autoDetect": "off"
}

View File

@ -0,0 +1,20 @@
// See https://go.microsoft.com/fwlink/?LinkId=733558
// for the documentation about the tasks.json format
{
"version": "2.0.0",
"tasks": [
{
"type": "npm",
"script": "watch",
"problemMatcher": "$tsc-watch",
"isBackground": true,
"presentation": {
"reveal": "never"
},
"group": {
"kind": "build",
"isDefault": true
}
}
]
}

View File

@ -0,0 +1,10 @@
.vscode/**
.vscode-test/**
src/**
.gitignore
.yarnrc
vsc-extension-quickstart.md
**/tsconfig.json
**/.eslintrc.json
**/*.map
**/*.ts

View File

@ -0,0 +1,9 @@
# Change Log
All notable changes to the "nb-codeactions" extension will be documented in this file.
Check [Keep a Changelog](http://keepachangelog.com/) for recommendations on how to structure this file.
## [Unreleased]
- Initial release

View File

@ -0,0 +1 @@
# nb-codeactions README

View File

@ -0,0 +1,33 @@
{
"cells": [
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"import time\n",
"\n",
"for i in range(10):\n",
" time.sleep(0.1)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"current_dir = os.getcwd()\n",
"print(\"Current working directory:\", current_dir)"
]
}
],
"metadata": {
"language_info": {
"name": "python"
}
},
"nbformat": 4,
"nbformat_minor": 2
}

View File

@ -0,0 +1,48 @@
{
"cells": [
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"import time\n",
"\n",
"for i in range(10):\n",
" time.sleep(0.1)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"import os\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"current_dir = os.getcwd()\n",
"print(\"Current working directory:\", current_dir)"
]
}
],
"metadata": {
"kernelspec": {
"display_name": "Python 3",
"language": "python",
"name": "python3"
},
"language_info": {
"name": "python",
"version": "3.11.9"
}
},
"nbformat": 4,
"nbformat_minor": 2
}

View File

@ -0,0 +1,48 @@
{
"cells": [
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"import time\n",
"\n",
"for i in range(10):\n",
" time.sleep(0.1)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"import os\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"current_dir = os.getcwd()\n",
"print(\"Current working directory:\", current_dir)"
]
}
],
"metadata": {
"kernelspec": {
"display_name": "Python 3",
"language": "python",
"name": "python3"
},
"language_info": {
"name": "python",
"version": "3.11.9"
}
},
"nbformat": 4,
"nbformat_minor": 2
}

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,41 @@
{
"name": "notebook-format-code-action-sample",
"displayName": "Notebook Format Code Action Sample",
"description": "Provide Format Code Actions for Notebooks",
"version": "0.0.1",
"engines": {
"vscode": "^1.89.0"
},
"categories": [
"Other"
],
"activationEvents": [
"onStartupFinished"
],
"main": "./out/extension.js",
"scripts": {
"vscode:prepublish": "npm run compile",
"compile": "tsc -p ./",
"watch": "tsc -watch -p ./",
"pretest": "npm run compile && npm run lint",
"lint": "eslint src --ext ts",
"test": "node ./out/test/runTest.js"
},
"devDependencies": {
"@types/glob": "^8.1.0",
"@types/mocha": "^10.0.1",
"@types/node": "16.x",
"@typescript-eslint/eslint-plugin": "^5.56.0",
"@typescript-eslint/parser": "^5.56.0",
"@vscode/test-electron": "^2.3.0",
"eslint": "^8.36.0",
"glob": "^8.1.0",
"mocha": "^10.2.0",
"typescript": "^4.9.5",
"vscode": "^1.1.37"
},
"repository": {
"type": "git",
"url": ""
}
}

View File

@ -0,0 +1,250 @@
/*---------------------------------------------------------
* Copyright (C) Microsoft Corporation. All rights reserved.
*--------------------------------------------------------*/
import * as vscode from 'vscode';
import { CodeActionKind } from 'vscode';
export async function activate(context: vscode.ExtensionContext) {
const notebookSelector: vscode.DocumentSelector = {
notebookType: 'jupyter-notebook',
};
// Notebook Format Code Action Provider
context.subscriptions.push(
vscode.languages.registerCodeActionsProvider(
notebookSelector,
new ExtractNotebookImports(),
{
providedCodeActionKinds: [ExtractNotebookImports.providedKind],
}
)
);
}
/**
* Notebook Format Code Action Provider
* Takes all mentions of import "xx" and extracts them to a new top code cell.
*/
export class ExtractNotebookImports implements vscode.CodeActionProvider {
static readonly providedKind = CodeActionKind.Notebook.append('format.yoyokrazy');
public provideCodeActions(
document: vscode.TextDocument,
_range: vscode.Range | vscode.Selection,
_context: vscode.CodeActionContext,
_token: vscode.CancellationToken
): vscode.CodeAction[] | undefined {
// console.log(`PROVIDED -- ${document.uri}`);
const notebookDocument = this.getNotebookDocument(document);
if (!notebookDocument) {
return;
}
const edits: (vscode.NotebookEdit | vscode.TextEdit)[] =
this.extractImportsAndCreateCellEdits(notebookDocument);
if (!edits) {
return;
}
const fix = new vscode.CodeAction(
'Extract cell level imports to single cell.',
ExtractNotebookImports.providedKind
);
fix.edit = new vscode.WorkspaceEdit();
for (const edit of edits) {
if (edit instanceof vscode.NotebookEdit) {
fix.edit.set(notebookDocument.uri, [edit]);
} else {
fix.edit.set(document.uri, [edit]);
}
}
return [fix];
}
// private extractImportsAndCreateCellEdits(
// notebookDocument: vscode.NotebookDocument
// ): (vscode.NotebookEdit | vscode.TextEdit)[] {
// const nbEdits: (vscode.NotebookEdit | vscode.TextEdit)[] = [];
// const importStatements: vscode.TextLine[] = [];
// for (const cell of notebookDocument.getCells()) {
// if (cell.kind !== vscode.NotebookCellKind.Code) {
// continue;
// }
// const cellTextDocument: vscode.TextDocument = cell.document;
// let i = 0;
// let nonImportText = '';
// while (i < cellTextDocument.lineCount) {
// const l = cellTextDocument.lineAt(i);
// if (l) {
// if (l.text.startsWith('import') || l.text.startsWith('from')) {
// if (!importStatements.includes(l)) {
// importStatements.push(l);
// }
// } else {
// nonImportText += l.text + '\n';
// }
// }
// i++;
// }
// // text edits replacements are better perf. use nb edit sparingly for deletions/additions
// // could lose outputs if you only replace cells
// // create the edit to remove the imports from the cell
// const newCell = new vscode.NotebookCellData(
// vscode.NotebookCellKind.Code,
// nonImportText,
// 'python'
// );
// nbEdits.push(
// vscode.NotebookEdit.replaceCells(
// new vscode.NotebookRange(cell.index, cell.index + 1),
// [newCell]
// )
// );
// }
// if (!importStatements.length) {
// return [];
// }
// // create the edit to create a new top cell containing all imports
// const newCell = new vscode.NotebookCellData(
// vscode.NotebookCellKind.Code,
// importStatements.map((l) => l.text).join('\n') + '\n',
// 'python'
// );
// nbEdits.push(new vscode.NotebookEdit(new vscode.NotebookRange(0, 0), [newCell]));
// return nbEdits;
// }
// private extractImportsAndCreateCellEdits(
// notebookDocument: vscode.NotebookDocument
// ): (vscode.NotebookEdit | vscode.TextEdit)[] {
// const nbEdits: (vscode.NotebookEdit | vscode.TextEdit)[] = [];
// let importStatements: string[] = [];
// notebookDocument.getCells().forEach((cell, index) => {
// if (cell.kind !== vscode.NotebookCellKind.Code) {
// return;
// }
// let cellHasImports = false;
// let nonImportText = '';
// cell.document
// .getText()
// .split('\n')
// .forEach((line) => {
// if (line.startsWith('import') || line.startsWith('from')) {
// importStatements.push(line);
// cellHasImports = true;
// } else {
// nonImportText += line + '\n';
// }
// });
// if (cellHasImports) {
// if (nonImportText.trim()) {
// // Replace cell content without imports
// const range = new vscode.Range(0, 0, cell.document.lineCount, 0);
// nbEdits.push(new vscode.TextEdit(range, nonImportText));
// } else {
// // Cell is empty after removing imports, mark for deletion
// nbEdits.push(
// vscode.NotebookEdit.replaceCells(
// new vscode.NotebookRange(index, index + 1),
// []
// )
// );
// }
// }
// });
// if (importStatements.length > 0) {
// // Create a new top cell with all import statements
// const newCell = new vscode.NotebookCellData(
// vscode.NotebookCellKind.Code,
// importStatements.join('\n') + '\n',
// 'python'
// );
// nbEdits.push(
// vscode.NotebookEdit.insertCells(new vscode.NotebookRange(0, 0), [newCell])
// );
// }
// return nbEdits;
// }
private extractImportsAndCreateCellEdits(
notebookDocument: vscode.NotebookDocument
): (vscode.NotebookEdit | vscode.TextEdit)[] {
const nbEdits: (vscode.NotebookEdit | vscode.TextEdit)[] = [];
let importStatements: string[] = [];
notebookDocument.getCells().forEach((cell, index) => {
if (cell.kind !== vscode.NotebookCellKind.Code) {
return [];
}
let cellHasImports = false;
let nonImportText = '';
cell.document
.getText()
.split('\n')
.forEach((line) => {
if (line.startsWith('import') || line.startsWith('from')) {
importStatements.push(line);
cellHasImports = true;
} else {
nonImportText += line + '\n';
}
});
if (cellHasImports) {
if (nonImportText.trim()) {
// Replace cell content without imports
const range = new vscode.Range(0, 0, cell.document.lineCount, 0);
nbEdits.push(new vscode.TextEdit(range, nonImportText));
} else {
// Cell is empty after removing imports, mark for deletion
nbEdits.push(
vscode.NotebookEdit.replaceCells(
new vscode.NotebookRange(index, index + 1),
[]
)
);
}
}
});
if (importStatements.length > 0) {
// Create a new top cell with all import statements
const newCell = new vscode.NotebookCellData(
vscode.NotebookCellKind.Code,
importStatements.join('\n') + '\n',
'python'
);
nbEdits.push(
vscode.NotebookEdit.insertCells(0, [newCell])
);
}
return nbEdits;
}
private getNotebookDocument(
document: vscode.TextDocument
): vscode.NotebookDocument | undefined {
for (const nb of vscode.workspace.notebookDocuments) {
if (nb.uri.path === document.uri.path) {
return nb;
}
}
return undefined;
}
}

View File

@ -0,0 +1,17 @@
{
"compilerOptions": {
"module": "commonjs",
"target": "ES2020",
"outDir": "out",
"lib": [
"ES2020"
],
"sourceMap": true,
"rootDir": "src",
"strict": true /* enable all strict type-checking options */
/* Additional Checks */
// "noImplicitReturns": true, /* Report error when not all code paths in function return a value. */
// "noFallthroughCasesInSwitch": true, /* Report errors for fallthrough cases in switch statement. */
// "noUnusedParameters": true, /* Report errors on unused parameters. */
}
}

File diff suppressed because it is too large Load Diff