Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat/generic python #1176

Draft
wants to merge 3 commits into
base: main
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
109 changes: 109 additions & 0 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

3 changes: 2 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -394,7 +394,7 @@
"properties": {
"fortran.fortls.path": {
"type": "string",
"default": "fortls",
"default": "",
"markdownDescription": "Path to the Fortran language server (`fortls`).",
"order": 10
},
Expand Down Expand Up @@ -761,6 +761,7 @@
"@typescript-eslint/parser": "^8.24.0",
"@vscode/test-electron": "^2.4.1",
"c8": "^10.1.3",
"copy-webpack-plugin": "^12.0.2",
"eslint": "^9.20.1",
"eslint-plugin-import": "^2.29.1",
"eslint-plugin-jsdoc": "^50.2.2",
Expand Down
30 changes: 30 additions & 0 deletions scripts/get_console_script.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
from __future__ import annotations

import sys
import pkg_resources


def get_console_script_path(package_name: str, script_name: str) -> str | None:
# """
# Get the absolute path of a console script from a package.

# @param package_name: The name of the package.
# @param script_name: The name of the console script.
# @return The absolute path of the console script.
# """
try:
# Get the distribution object for the package
dist = pkg_resources.get_distribution(package_name)
# Get the entry point for the console script
entry_point = dist.get_entry_info("console_scripts", script_name)
# Get the path to the script
script_path = entry_point.module_name.split(":")[0]
# Return the absolute path of the script
return pkg_resources.resource_filename(dist, script_path)
except Exception as e:
# Handle any exceptions that occur
print(f"Error: {e}")
return None


print(get_console_script_path(sys.argv[1], sys.argv[2]))
21 changes: 21 additions & 0 deletions scripts/get_pip_bin_dir.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
import os
import sysconfig


def get_install_bin_dir() -> str:
"""Get the path to the pip install directory for scripts (bin, Scripts).
Works for virtualenv, conda, and system installs.

Returns
-------
str
Path to the pip install directory for scripts (bin, Scripts).
"""
if ("VIRTUAL_ENV" in os.environ) or ("CONDA_PREFIX" in os.environ):
return sysconfig.get_path("scripts")
else:
return sysconfig.get_path("scripts", f"{os.name}_user")


if __name__ == "__main__":
print(get_install_bin_dir())
8 changes: 8 additions & 0 deletions scripts/mod_in_env.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
#! /usr/bin/env python3

import sys
import pkg_resources

# If not present, fails with a DistributionNotFound exception
if pkg_resources.get_distribution(str(sys.argv[1])).version:
exit(0)
2 changes: 1 addition & 1 deletion src/format/provider.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,12 +6,12 @@ import * as vscode from 'vscode';
import which from 'which';

import { Logger } from '../services/logging';
import { spawnAsPromise } from '../util/shell';
import {
FORMATTERS,
EXTENSION_ID,
promptForMissingTool,
getWholeFileRange,
spawnAsPromise,
pathRelToAbs,
} from '../util/tools';

Expand Down
3 changes: 1 addition & 2 deletions src/lint/provider.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,14 +21,13 @@ import {
import { Logger } from '../services/logging';
import { GlobPaths } from '../util/glob-paths';
import { arraysEqual } from '../util/helper';
import { spawnAsPromise, shellTask } from '../util/shell';
import {
EXTENSION_ID,
resolveVariables,
promptForMissingTool,
isFreeForm,
spawnAsPromise,
isFortran,
shellTask,
} from '../util/tools';

import { GNULinter, GNUModernLinter, IntelLinter, LFortranLinter, NAGLinter } from './compilers';
Expand Down
33 changes: 29 additions & 4 deletions src/lsp/client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,13 +10,13 @@ import { LanguageClient, LanguageClientOptions, ServerOptions } from 'vscode-lan

import { RestartLS } from '../commands/commands';
import { Logger } from '../services/logging';
import { Python } from '../util/python';
import {
EXTENSION_ID,
FortranDocumentSelector,
LS_NAME,
isFortran,
getOuterMostWorkspaceFolder,
pipInstall,
resolveVariables,
} from '../util/tools';

Expand All @@ -26,11 +26,16 @@ import {
export const clients: Map<string, LanguageClient> = new Map();

export class FortlsClient {
private readonly python: Python;
private readonly config: vscode.WorkspaceConfiguration;

constructor(
private logger: Logger,
private context?: vscode.ExtensionContext
) {
this.logger.debug('[lsp.client] Fortran Language Server -- constructor');
this.python = new Python();
this.config = workspace.getConfiguration(EXTENSION_ID);

// if context is present
if (context !== undefined) {
Expand Down Expand Up @@ -316,6 +321,7 @@ export class FortlsClient {
const ls = await this.fortlsPath();

// Check for version, if this fails fortls provided is invalid
const pipBin: string = await this.python.getPipBinDir();
const results = spawnSync(ls, ['--version']);
const msg = `It is highly recommended to use the fortls to enable IDE features like hover, peeking, GoTos and many more.
For a full list of features the language server adds see: https://fortls.fortran-lang.org`;
Expand All @@ -326,7 +332,7 @@ export class FortlsClient {
if (opt === 'Install') {
try {
this.logger.info(`[lsp.client] Downloading ${LS_NAME}`);
const msg = await pipInstall(LS_NAME);
const msg = await this.python.pipInstall(LS_NAME);
window.showInformationMessage(msg);
this.logger.info(`[lsp.client] ${LS_NAME} installed`);
resolve(false);
Expand Down Expand Up @@ -378,19 +384,38 @@ export class FortlsClient {
const root = folder ? getOuterMostWorkspaceFolder(folder).uri : vscode.Uri.parse(os.homedir());

const config = workspace.getConfiguration(EXTENSION_ID);
let executablePath = resolveVariables(config.get<string>('fortls.path'));
// TODO: make the default value undefined, make windows use fortls.exe
// get the full path of the Python bin dir, check if file exists
// else we are running a script with a relative path (verify this is the case)
let executablePath = config.get<string>('fortls.path');
if (!executablePath || this.isFortlsPathDefault(executablePath)) {
executablePath = 'fortls' + (os.platform() === 'win32' ? '.exe' : '');
executablePath = path.join(await this.python.getPipBinDir(), executablePath);
} else {
executablePath = resolveVariables(executablePath);
}

// The path can be resolved as a relative path if:
// 1. it does not have the default value `fortls` AND
// 2. is not an absolute path
if (executablePath !== 'fortls' && !path.isAbsolute(executablePath)) {
if (!path.isAbsolute(executablePath)) {
this.logger.debug(`[lsp.client] Assuming relative fortls path is to ${root.fsPath}`);
executablePath = path.join(root.fsPath, executablePath);
}

return executablePath;
}

private async isFortlsPathDefault(path: string): Promise<boolean> {
if (path === 'fortls') {
return true;
}
if (os.platform() === 'win32' && path === 'fortls.exe') {
return true;
}
return false;
}

/**
* Restart the language server
*/
Expand Down
48 changes: 48 additions & 0 deletions src/util/ms-python-api/jupyter/types.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.

'use strict';

import { QuickPickItem } from 'vscode';

interface IJupyterServerUri {
baseUrl: string;
token: string;

authorizationHeader: any; // JSON object for authorization header.
expiration?: Date; // Date/time when header expires and should be refreshed.
displayName: string;
}

type JupyterServerUriHandle = string;

export interface IJupyterUriProvider {
readonly id: string; // Should be a unique string (like a guid)
getQuickPickEntryItems(): QuickPickItem[];
handleQuickPick(
item: QuickPickItem,
backEnabled: boolean
): Promise<JupyterServerUriHandle | 'back' | undefined>;
getServerUri(handle: JupyterServerUriHandle): Promise<IJupyterServerUri>;
}

interface IDataFrameInfo {
columns?: { key: string; type: ColumnType }[];
indexColumn?: string;
rowCount?: number;
}

export interface IDataViewerDataProvider {
dispose(): void;
getDataFrameInfo(): Promise<IDataFrameInfo>;
getAllRows(): Promise<IRowsResponse>;
getRows(start: number, end: number): Promise<IRowsResponse>;
}

enum ColumnType {
String = 'string',
Number = 'number',
Bool = 'bool',
}

type IRowsResponse = any[];
Loading
Loading