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

Master py ext add json config loha #114

Draft
wants to merge 12 commits into
base: master
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.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
1 change: 0 additions & 1 deletion server/core/odoo.py
Original file line number Diff line number Diff line change
Expand Up @@ -193,7 +193,6 @@ def reload_database(ls):
Odoo.get().reset(ls)
FileMgr.files = {}
ls.show_message_log("Building new database", MessageType.Log)
ls.show_message("Reloading Odoo database", MessageType.Info)
ls.launch_thread(target=Odoo.initialize, args=(ls,))


Expand Down
2 changes: 2 additions & 0 deletions vscode/build_package.sh
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
#!/bin/bash

PACKAGE_VERSION=$(cat package.json \
| grep version \
| head -1 \
Expand Down
File renamed without changes.
11 changes: 11 additions & 0 deletions vscode/client/common/constants.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.

import * as path from 'path';

const folderName = path.basename(__dirname);
export const EXTENSION_ROOT_DIR =
folderName === 'common' ? path.dirname(path.dirname(__dirname)) : path.dirname(__dirname);
export const BUNDLED_PYTHON_SCRIPTS_DIR = path.join(EXTENSION_ROOT_DIR, 'server');
export const SERVER_SCRIPT_PATH = path.join(BUNDLED_PYTHON_SCRIPTS_DIR, '__main__.py');
export const DEBUG_SERVER_SCRIPT_PATH = path.join(BUNDLED_PYTHON_SCRIPTS_DIR, `_debug_server.py`);
Original file line number Diff line number Diff line change
Expand Up @@ -2,3 +2,4 @@ import {EventEmitter} from "vscode";

export const selectedConfigurationChange = new EventEmitter();
export const ConfigurationsChange = new EventEmitter();
export const clientStopped = new EventEmitter();
87 changes: 87 additions & 0 deletions vscode/client/common/python.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,87 @@
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.

/* eslint-disable @typescript-eslint/naming-convention */
import { commands, Disposable, Event, EventEmitter, Uri } from 'vscode';
import { PythonExtension, ResolvedEnvironment, VersionInfo } from '@vscode/python-extension';

export interface IInterpreterDetails {
path?: string[];
resource?: Uri;
}

export const onDidChangePythonInterpreterEvent = new EventEmitter<IInterpreterDetails>();
export const onDidChangePythonInterpreter: Event<IInterpreterDetails> = onDidChangePythonInterpreterEvent.event;

let _api: PythonExtension | undefined;
async function getPythonExtensionAPI(): Promise<PythonExtension | undefined> {
if (_api) {
return _api;
}
_api = await PythonExtension.api();
return _api;
}

export async function initializePython(disposables: Disposable[]): Promise<void> {
try {
const api = await getPythonExtensionAPI();

if (api) {
disposables.push(
api.environments.onDidChangeActiveEnvironmentPath((e) => {
onDidChangePythonInterpreterEvent.fire({ path: [e.path], resource: e.resource?.uri });
}),
);

console.log('Waiting for interpreter from python extension.');
onDidChangePythonInterpreterEvent.fire(await getInterpreterDetails());
}
} catch (error) {
console.error('Error initializing python: ', error);
}
}

export async function resolveInterpreter(interpreter: string[]): Promise<ResolvedEnvironment | undefined> {
const api = await getPythonExtensionAPI();
return api?.environments.resolveEnvironment(interpreter[0]);
}

export async function getInterpreterDetails(resource?: Uri): Promise<IInterpreterDetails> {
const api = await getPythonExtensionAPI();
const environment = await api?.environments.resolveEnvironment(
api?.environments.getActiveEnvironmentPath(resource),
);
if (environment?.executable.uri && checkVersion(environment)) {
return { path: [environment?.executable.uri.fsPath], resource };
}
return { path: undefined, resource };
}

export async function getDebuggerPath(): Promise<string | undefined> {
const api = await getPythonExtensionAPI();
return api?.debug.getDebuggerPackagePath();
}

export async function runPythonExtensionCommand(command: string, ...rest: any[]) {
await getPythonExtensionAPI();
return await commands.executeCommand(command, ...rest);
}

export function checkVersion(resolved: ResolvedEnvironment | undefined): boolean {
const version = resolved?.version;
if (version?.major === 3 && version?.minor >= 8) {
return true;
}
console.error(`Python version ${version?.major}.${version?.minor} is not supported.`);
console.error(`Selected python path: ${resolved?.executable.uri?.fsPath}`);
console.error('Supported versions are 3.8 and above.');
return false;
}

export async function getPythonVersion(): Promise<VersionInfo> {
let interpreterDetails = await getInterpreterDetails();
let resolved = await resolveInterpreter(interpreterDetails.path);
let version = resolved.version;

return version;
}
96 changes: 96 additions & 0 deletions vscode/client/common/utils.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,96 @@
import { ExtensionContext, Uri, Webview, workspace} from "vscode";
import * as fs from 'fs';
import { URI } from "vscode-languageclient";
import untildify from 'untildify';
import * as readline from 'readline';


/**
* A helper function which will get the webview URI of a given file or resource.
*
* @remarks This URI can be used within a webview's HTML as a link to the
* given file/resource.
*
* @param webview A reference to the extension webview
* @param extensionUri The URI of the directory containing the extension
* @param pathList An array of strings representing the path to a file/resource
* @returns A URI pointing to the file/resource
*/
export function getUri(webview: Webview, extensionUri: Uri, pathList: string[]) {
return webview.asWebviewUri(Uri.joinPath(extensionUri, ...pathList));
}

export function getNonce() {
let text = '';
const possible = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
for (let i = 0; i < 32; i++) {
text += possible.charAt(Math.floor(Math.random() * possible.length));
}
return text;
}

// Config related utils

export async function getCurrentConfig(context: ExtensionContext) {
const configs = JSON.parse(JSON.stringify(workspace.getConfiguration().get("Odoo.configurations")));
const activeConfig: number = Number(context.workspaceState.get('Odoo.selectedConfiguration'));
return (configs && activeConfig > -1 ? configs[activeConfig] : null);
}

export async function evaluateOdooPath(odooPath){
const workspaceFolders = workspace.workspaceFolders;

const fillTemplate = (template, vars = {}) => {
const handler = new Function('vars', [
'const tagged = ( ' + Object.keys(vars).join(', ') + ' ) =>',
'`' + template + '`',
'return tagged(...Object.values(vars))'
].join('\n'));
const res = handler(vars)
return res;
};


for (const i in workspaceFolders){
const folder = workspaceFolders[i];
let PATH_VAR_LOCAL = global.PATH_VARIABLES;
PATH_VAR_LOCAL["workspaceFolder"] = folder.uri.path;
odooPath = fillTemplate(odooPath,PATH_VAR_LOCAL);
const version = await getOdooVersion(odooPath);
if (version){
global.PATH_VARIABLES["workspaceFolder"] = folder.uri.path;
return {"path": odooPath,"version": version};
}
}
return null;
}

export async function getOdooVersion(odooPath: URI) {
let versionString = null;
const releasePath = untildify(odooPath) + '/odoo/release.py';
if (fs.existsSync(releasePath)) {
const rl = readline.createInterface({
input: fs.createReadStream(releasePath),
crlfDelay: Infinity,
});

for await (const line of rl) {
if (line.startsWith('version_info')) {
versionString = line;
// Folder is invalid if we don't find any version info
if (!versionString) {
return null;
} else {
// Folder is valid if a version was found
const versionRegEx = /\(([^)]+)\)/; // Regex to obtain the info in the parentheses
const versionArray = versionRegEx.exec(versionString)[1].split(', ');
const version = `${versionArray[0]}.${versionArray[1]}.${versionArray[2]}` + (versionArray[3] == 'FINAL' ? '' : ` ${versionArray[3]}${versionArray[4]}`);
return version;
}
}
}
} else {
// Folder is invalid if odoo/release.py was never found
return null;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,5 @@ export function getConfigurationStructure(id: number = 0) {
"name": `New Configuration ${id}`,
"odooPath": "",
"addons": [],
"pythonPath": "python3",
}
}