vscode#WorkspaceFolder TypeScript Examples
The following examples show how to use
vscode#WorkspaceFolder.
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: workspace-util.ts From vscode-code-review with MIT License | 7 votes |
getWorkspaceFolder = (folders: WorkspaceFolder[] | undefined, activeTextEditor?: TextEditor): string => {
if (!folders || !folders[0] || !folders[0].uri || !folders[0].uri.fsPath) {
// Edge-Case (See Issue #108): Handle the case we are not actually in an workspace but a single file has been picked for review in VSCode
// In this case, the review file will be stored next to this file in the same directory
const currentFile = activeTextEditor?.document.fileName;
return currentFile ? path.dirname(currentFile) : '';
}
return folders[0].uri.fsPath;
}
Example #2
Source File: dbtProjectContainer.ts From vscode-dbt-power-user with MIT License | 6 votes |
private unregisterWorkspaceFolder(workspaceFolder: WorkspaceFolder): void {
const folderToDelete = this.findDBTWorkspaceFolder(workspaceFolder.uri);
if (folderToDelete === undefined) {
throw Error("dbtWorkspaceFolder not registered");
}
this.dbtWorkspaceFolders.splice(
this.dbtWorkspaceFolders.indexOf(folderToDelete)
);
folderToDelete.dispose();
}
Example #3
Source File: file-watcher.ts From karma-test-explorer with MIT License | 6 votes |
public constructor(
private readonly workspaceFolder: WorkspaceFolder,
private readonly projectRootPath: string,
private readonly testFilePatterns: readonly string[],
private readonly reloadTriggerFiles: readonly string[],
private readonly testLocator: TestLocator,
private readonly testStore: TestStore,
private readonly testRetireEventEmitter: EventEmitter<RetireEvent>,
private readonly projectCommands: Commands<ProjectCommand>,
private readonly logger: Logger,
fileWatcherOptions: FileWatcherOptions = {}
) {
this.fileWatcherOptions = { ...defaultFileWatcherOptions, ...fileWatcherOptions };
this.disposables.push(logger);
this.disposables.push(...this.createFileWatchers());
}
Example #4
Source File: karma-test-explorer.ts From karma-test-explorer with MIT License | 6 votes |
constructor(
public readonly workspaceFolder: WorkspaceFolder,
private readonly config: NonDisposable<ExtensionConfig>, // FIXME: get from factory
private readonly testManager: TestManager,
private readonly testLocator: TestLocator,
private readonly testStore: NonDisposable<TestStore>,
private readonly processHandler: ProcessHandler,
private readonly testDebugger: NonDisposable<Debugger>,
private readonly testLoadEmitter: NonDisposable<EventEmitter<TestLoadEvent>>,
private readonly testRunEmitter: NonDisposable<EventEmitter<TestRunEvent | TestResultEvent>>,
private readonly retireEmitter: NonDisposable<EventEmitter<RetireEvent>>,
private readonly notificationHandler: NonDisposable<NotificationHandler>,
private readonly logger: SimpleLogger
) {
this.disposables.push(logger);
}
Example #5
Source File: config-change-manager.ts From karma-test-explorer with MIT License | 6 votes |
public watchForConfigChange(
workspaceFolder: WorkspaceFolder,
watchedSettings: readonly T[],
changeHandler: ConfigChangeHandler<T>,
changeNotificationOptions?: ConfigChangeNotificationOptions
) {
const configChangeSubscription: ConfigChangeSubscription<T> = {
workspaceFolder,
watchedSettings,
changeHandler,
changeNotificationOptions
};
this.configChangeSubscriptions.push(configChangeSubscription);
}
Example #6
Source File: Configuration.ts From vscode-alxmldocumentation with MIT License | 6 votes |
/**
* Get Configuration related for the actual file opened.
* @param fileUri URI to actual file or undefined.
*/
private static GetConfiguration(fileUri: Uri | undefined = undefined): WorkspaceConfiguration | undefined {
let config: WorkspaceConfiguration | undefined;
if (fileUri === undefined) {
let activeDocument = (window.activeTextEditor !== undefined) ? window.activeTextEditor.document : undefined;
let workspaceFolder: WorkspaceFolder | undefined = undefined;
if (activeDocument !== undefined) {
workspaceFolder = workspace.getWorkspaceFolder(activeDocument.uri);
config = workspace.getConfiguration(ALXmlDocConfigurationPrefix, workspaceFolder);
} else {
config = workspace.getConfiguration(ALXmlDocConfigurationPrefix);
}
} else {
let workspaceFolder = workspace.getWorkspaceFolder(fileUri);
config = workspace.getConfiguration(ALXmlDocConfigurationPrefix, workspaceFolder);
}
return config;
}
Example #7
Source File: WorkspaceManager.ts From al-objid with MIT License | 6 votes |
private onDidChangeWorkspaceFolders({ added, removed }: WorkspaceFoldersChangeEvent) {
// Remove any ALApp instances that are no longer in workspace
const alRemoved: ALApp[] = [];
this._apps = this._apps.filter(app => {
const stillExists = !removed.find(folder => app.isFolder(folder));
if (!stillExists) {
alRemoved.push(app);
delete this._appMap[app.uri.fsPath];
delete this._appHashMap[app.hash];
}
return stillExists;
});
this._folders = this._folders.filter(
oldFolder => !removed.find(removedFolder => removedFolder.uri.fsPath === oldFolder.uri.fsPath)
);
// Add any folders that are added to the workspace
const alAdded: ALApp[] = [];
this.addFoldersToWatch(added as WorkspaceFolder[], alAdded);
// Fire the event with any AL Apps added or removed
if (alRemoved.length || alAdded.length) {
this._onDidChangeALFolders.fire({ added: alAdded, removed: alRemoved });
}
// Dispose of removed apps
for (let app of alRemoved) {
app.dispose();
}
}
Example #8
Source File: WorkspaceManager.ts From al-objid with MIT License | 6 votes |
private addFoldersToWatch(folders: WorkspaceFolder[], addedApps?: ALApp[]) {
for (let folder of folders) {
const app = ALApp.tryCreate(folder);
if (!app) {
continue;
}
this._apps.push(app);
this._appMap[app.uri.fsPath] = app;
this._appHashMap[app.hash] = app;
addedApps?.push(app);
}
this._folders.push(...folders);
}
Example #9
Source File: dbtWorkspaceFolder.ts From vscode-dbt-power-user with MIT License | 6 votes |
constructor(
@inject("DBTProjectFactory")
private dbtProjectFactory: (
path: Uri,
_onManifestChanged: EventEmitter<ManifestCacheChangedEvent>
) => DBTProject,
workspaceFolder: WorkspaceFolder,
_onManifestChanged: EventEmitter<ManifestCacheChangedEvent>
) {
this.workspaceFolder = workspaceFolder;
this.watcher = this.createConfigWatcher();
this.disposables.push(this.watcher);
this._onManifestChanged = _onManifestChanged;
}
Example #10
Source File: dbtProjectContainer.ts From vscode-dbt-power-user with MIT License | 6 votes |
constructor(
private dbtClient: DBTClient,
@inject("Factory<DBTWorkspaceFolder>")
private dbtWorkspaceFolderFactory: (
workspaceFolder: WorkspaceFolder,
_onManifestChanged: EventEmitter<ManifestCacheChangedEvent>
) => DBTWorkspaceFolder
) {
this.disposables.push(
workspace.onDidChangeWorkspaceFolders(async (event) => {
const { added, removed } = event;
await Promise.all(
added.map(
async (folder) => await this.registerWorkspaceFolder(folder)
)
);
removed.forEach((removedWorkspaceFolder) =>
this.unregisterWorkspaceFolder(removedWorkspaceFolder)
);
})
);
}
Example #11
Source File: dbtProjectContainer.ts From vscode-dbt-power-user with MIT License | 6 votes |
private async registerWorkspaceFolder(
workspaceFolder: WorkspaceFolder
): Promise<void> {
const dbtProjectWorkspaceFolder = this.dbtWorkspaceFolderFactory(
workspaceFolder,
this._onManifestChanged
);
this.dbtWorkspaceFolders.push(dbtProjectWorkspaceFolder);
await dbtProjectWorkspaceFolder.discoverProjects();
}
Example #12
Source File: inversify.config.ts From vscode-dbt-power-user with MIT License | 6 votes |
container
.bind<interfaces.Factory<DBTWorkspaceFolder>>("Factory<DBTWorkspaceFolder>")
.toFactory<DBTWorkspaceFolder>((context: interfaces.Context) => {
return (
workspaceFolder: WorkspaceFolder,
_onManifestChanged: EventEmitter<ManifestCacheChangedEvent>
) => {
const { container } = context;
return new DBTWorkspaceFolder(
container.get("Factory<DBTProject>"),
workspaceFolder,
_onManifestChanged,
);
};
});
Example #13
Source File: extension.ts From vscode-riscv-venus with MIT License | 6 votes |
/**
* Massage a debug configuration just before a debug session is being launched,
* e.g. add all missing attributes to the debug configuration.
*/
resolveDebugConfiguration(folder: WorkspaceFolder | undefined, config: DebugConfiguration, token?: CancellationToken): ProviderResult<DebugConfiguration> {
// if launch.json is missing or empty
if (!config.type && !config.request && !config.name) {
const editor = vscode.window.activeTextEditor;
if (editor && editor.document.languageId === 'riscv') {
config.type = 'venus';
config.name = 'Launch';
config.request = 'launch';
config.program = '${file}';
config.stopOnEntry = true;
}
}
if (!config.program) {
return vscode.window.showInformationMessage("Cannot find a program to debug").then(_ => {
return undefined; // abort launch
});
}
return config;
}
Example #14
Source File: extension.ts From vscode-code-review with MIT License | 6 votes |
// this method is called when your extension is activated
// your extension is activated the very first time the command is executed
export function activate(context: ExtensionContext) {
let workspaceRoot: string = getWorkspaceFolder(
workspace.workspaceFolders as WorkspaceFolder[],
window.activeTextEditor,
);
const workspaceContext = new WorkspaceContext(context, workspaceRoot);
workspaceContext.registerCommands();
/**
* detect when active editor changes and the workspace too
*/
const activeTextEditorWorkspaceChangesRegistration = window.onDidChangeActiveTextEditor((editor) => {
if (editor?.document.uri) {
const newWorkspaceRoot = getWorkspaceFolder(
[workspace.getWorkspaceFolder(editor.document.uri)] as WorkspaceFolder[],
window.activeTextEditor,
);
if (workspaceContext.workspaceRoot === newWorkspaceRoot) {
// Prevent refresh everything when workspace stays the same as before
return;
}
if (isProperSubpathOf(newWorkspaceRoot, workspaceContext.workspaceRoot)) {
// Prevents workspace refresh when commenting on a file in a diff view which, apparently, points to a
// (temporary?) workspace inside the current one.
return;
}
workspaceContext.workspaceRoot = newWorkspaceRoot;
workspaceContext.refreshCommands();
}
});
context.subscriptions.push(activeTextEditorWorkspaceChangesRegistration);
}
Example #15
Source File: ALApp.ts From al-objid with MIT License | 6 votes |
public static tryCreate(folder: WorkspaceFolder): ALApp | undefined {
const uri = folder.uri;
const manifestUri = Uri.file(path.join(uri.fsPath, APP_FILE_NAME));
if (!fs.existsSync(manifestUri.fsPath)) {
return;
}
const manifest = ALAppManifest.tryCreate(manifestUri);
return manifest && new ALApp(uri, folder.name, manifest);
}
Example #16
Source File: projectInfo.ts From vscode-lean4 with Apache License 2.0 | 5 votes |
// Find the root of a Lean project and return an optional WorkspaceFolder for it,
// the Uri for the package root and the Uri for the 'leanpkg.toml' or 'lean-toolchain' file found there.
export async function findLeanPackageRoot(uri: Uri) : Promise<[WorkspaceFolder | undefined, Uri | null, Uri | null]> {
if (!uri) return [undefined, null, null];
const toolchainFileName = 'lean-toolchain';
const tomlFileName = 'leanpkg.toml';
if (uri.scheme === 'untitled'){
// then return a Uri representing all untitled files.
return [undefined, Uri.from({scheme: 'untitled'}), null];
}
let path = uri;
let wsFolder = workspace.getWorkspaceFolder(uri);
if (!wsFolder && workspace.workspaceFolders) {
workspace.workspaceFolders.forEach((f) => {
if (f.uri?.scheme === 'file' && f.uri.fsPath && uri.fsPath.startsWith(f.uri.fsPath)) {
wsFolder = f;
}
});
}
let searchUpwards = false;
if (wsFolder){
// jump to the real workspace folder if we have a Workspace for this file.
path = wsFolder.uri;
} else if (path.scheme === 'file') {
// then start searching from the directory containing this document.
// The given uri may already be a folder Uri in some cases.
if (fs.lstatSync(path.fsPath).isFile()) {
path = Uri.joinPath(uri, '..');
}
searchUpwards = true;
}
const startFolder = path;
if (path.scheme === 'file') {
// search parent folders for a leanpkg.toml file, or a Lake lean-toolchain file.
while (true) {
// give preference to 'lean-toolchain' files if any.
const leanToolchain = Uri.joinPath(path, toolchainFileName);
if (await fileExists(leanToolchain.fsPath)) {
return [wsFolder, path, leanToolchain];
}
else {
const leanPkg = Uri.joinPath(path, tomlFileName);
if (await fileExists(leanPkg.fsPath)) {
return [wsFolder, path, leanPkg];
}
else if (await isCoreLean4Directory(path)) {
return [wsFolder, path, null];
}
else if (searchUpwards) {
const parent = Uri.joinPath(path, '..');
if (parent === path) {
// no project file found.
break;
}
path = parent;
}
else {
// don't search above a WorkspaceFolder barrier.
break;
}
}
}
}
return [wsFolder, startFolder, null];
}
Example #17
Source File: WorkspaceManager.ts From al-objid with MIT License | 5 votes |
private constructor() {
this._workspaceFoldersChangeEvent = workspace.onDidChangeWorkspaceFolders(
this.onDidChangeWorkspaceFolders.bind(this)
);
this.addFoldersToWatch((workspace.workspaceFolders || []) as WorkspaceFolder[]);
}
Example #18
Source File: WorkspaceManager.ts From al-objid with MIT License | 5 votes |
private _folders: WorkspaceFolder[] = [];
Example #19
Source File: project-factory.ts From karma-test-explorer with MIT License | 5 votes |
public createProjectsForWorkspaceFolders(...workspaceFolders: WorkspaceFolder[]): WorkspaceProject[] {
const projects = workspaceFolders
.map(workspaceFolder => this.createProjectsForWorkspaceFolder(workspaceFolder))
.reduce((runningProjectList, currentFolderProjects) => [...runningProjectList, ...currentFolderProjects], []);
return projects;
}
Example #20
Source File: main-factory.ts From karma-test-explorer with MIT License | 5 votes |
constructor(
private readonly workspaceFolder: WorkspaceFolder,
private readonly projectDisplayName: string,
private readonly projectNameSpace: string | undefined,
private readonly config: ExtensionConfig,
private readonly testDebugger: Debugger,
private readonly portAcquisitionClient: PortAcquisitionClient,
private readonly projectCommands: Commands<ProjectCommand>,
private readonly notificationHandler: NotificationHandler,
private readonly testLoadEventEmitter: EventEmitter<TestLoadEvent>,
private readonly testRunEventEmitter: EventEmitter<TestRunEvent>,
private readonly testResultEventEmitter: EventEmitter<TestResultEvent>,
private readonly testRetireEventEmitter: EventEmitter<RetireEvent>,
private readonly logger: SimpleLogger
) {
this.disposables.push(logger);
this.angularProject =
config.projectType !== ProjectType.Karma
? getDefaultAngularProject(this.config.projectRootPath, this.config.selectedAngularProject)
: undefined;
this.fileHandler = new FileHandler(this.createLogger(FileHandler.name), {
cwd: this.config.projectRootPath
});
const karmaConfigPath = this.angularProject?.karmaConfigPath ?? this.config.userKarmaConfFilePath;
const configuredTestFramework: TestFramework | undefined =
this.config.testFramework === TestFrameworkName.MochaBDD
? MochaTestFrameworkBdd
: this.config.testFramework === TestFrameworkName.MochaTDD
? MochaTestFrameworkTdd
: this.config.testFramework === TestFrameworkName.Jasmine
? JasmineTestFramework
: undefined;
this.testFramework = configuredTestFramework ?? this.detectTestFramework(karmaConfigPath, this.fileHandler);
this.logger.info(
() => `Using test framework: ${this.testFramework.name} ${!config.testFramework ? `(auto-detected)` : ''}`
);
this.logger.debug(() => 'Creating test helper');
this.testHelper = new TestHelper(this.createLogger(TestHelper.name), {
showTestDefinitionTypeIndicators: this.config.showTestDefinitionTypeIndicators
});
this.disposables.push(this.testHelper);
this.logger.debug(() => 'Creating process handler');
this.processHandler = new ProcessHandler(this.createLogger(ProcessHandler.name));
this.disposables.push(this.processHandler);
this.logger.debug(() => 'Creating test locator');
this.testLocator = this.createTestLocator(this.fileHandler);
this.disposables.push(this.testLocator);
this.logger.debug(() => 'Creating test store');
this.testStore = new TestStore(this.createLogger(TestStore.name));
this.disposables.push(this.testStore);
const outputChannelNamespaceLabel = this.projectNameSpace ? ` (${this.projectNameSpace})` : '';
this.testServerLog = new OutputChannelLog(`${KARMA_SERVER_OUTPUT_CHANNEL_NAME}${outputChannelNamespaceLabel}`, {
enabled: config.karmaLogLevel !== KarmaLogLevel.DISABLE
});
this.disposables.push(this.testServerLog);
}
Example #21
Source File: ALApp.ts From al-objid with MIT License | 5 votes |
/**
* Checks if this ALApp instance represents the specified workspace folder.
* @param folder Workspace folder for which to check if this ALApp instance represents it.
* @returns Boolean value indicating whether this ALApp instance represents the specified workspace folder.
*/
public isFolder(folder: WorkspaceFolder): boolean {
return folder.uri.fsPath == this._uri.fsPath;
}
Example #22
Source File: ObjIdConfig.ts From al-objid with MIT License | 5 votes |
private readonly _folder: WorkspaceFolder;
Example #23
Source File: debugger.ts From karma-test-explorer with MIT License | 5 votes |
public startDebugSession(
workspaceFolder: WorkspaceFolder,
debuggerNameOrConfig: string | DebugConfiguration,
sessionStartTimeout: number
): Execution<DebugSession> {
const deferredDebugSessionExecution: DeferredExecution<DebugSession> = new DeferredExecution();
const debugSessionExecution = deferredDebugSessionExecution.execution();
const debuggerNamespaceTag = this.options?.debuggerNamespace ? ` - ${this.options?.debuggerNamespace}` : '';
const actualDebuggerNameOrConfig =
typeof debuggerNameOrConfig === 'string'
? debuggerNameOrConfig
: { ...debuggerNameOrConfig, name: `${debuggerNameOrConfig.name}${debuggerNamespaceTag}` };
const debuggerConfigName =
typeof actualDebuggerNameOrConfig === 'string' ? actualDebuggerNameOrConfig : actualDebuggerNameOrConfig.name;
try {
const activeDebugSession = debug.activeDebugSession;
if (activeDebugSession && activeDebugSession.name === debuggerConfigName) {
this.logger.info(() => `Debug session '${activeDebugSession.name}' is alredy active`);
deferredDebugSessionExecution.start(activeDebugSession);
this.activeDebugSession = activeDebugSession;
} else {
const debugStartSubscription: Disposable = debug.onDidStartDebugSession(session => {
if (session.name === debuggerConfigName) {
this.logger.info(() => `Debug session '${session.name}' has started`);
deferredDebugSessionExecution.start(session);
this.activeDebugSession = session;
}
});
debugSessionExecution.started().finally(() => debugStartSubscription.dispose());
debug.startDebugging(workspaceFolder, actualDebuggerNameOrConfig).then(
isSessionStarted => {
if (!isSessionStarted) {
deferredDebugSessionExecution.fail(`Debug session '${debuggerConfigName}' failed to start`);
}
},
reason =>
deferredDebugSessionExecution.fail(
`Debug session '${debuggerConfigName}' failed to start: ${reason.message ?? reason}`
)
);
deferredDebugSessionExecution.failIfNotStarted(
sessionStartTimeout,
`Timeout after waiting ${sessionStartTimeout} ms for debug session '${debuggerConfigName}' to start`
);
}
debugSessionExecution.started().then(debugSession => {
const debugStopSubscription = debug.onDidTerminateDebugSession(session => {
if (session === debugSession) {
this.logger.info(() => `Debug session '${session.name}' has ended`);
deferredDebugSessionExecution.end();
this.activeDebugSession = undefined;
debugStopSubscription.dispose();
}
});
});
} catch (error) {
deferredDebugSessionExecution.fail(`Debug session '${debuggerConfigName}' failed to start: ${error}`);
}
return debugSessionExecution;
}
Example #24
Source File: adapter.ts From karma-test-explorer with MIT License | 5 votes |
constructor(
public readonly workspaceFolder: WorkspaceFolder,
private readonly projectDisplayName: string,
portAcquisitionManager: PortAcquisitionManager,
projectStatusDisplay: StatusDisplay,
private readonly options?: AdapterOptions
) {
let channelLog = options?.outputChannelLog;
if (!channelLog) {
const channelNamespaceLabel = options?.projectNamespace ? ` (${options.projectNamespace})` : '';
channelLog = new OutputChannelLog(`${EXTENSION_OUTPUT_CHANNEL_NAME}${channelNamespaceLabel}`);
this.disposables.push(channelLog);
}
this.outputChannelLog = channelLog;
const config = this.createConfig();
this.logger = new SimpleLogger(this.outputChannelLog, Adapter.name, config.logLevel);
this.logger.debug(() => 'Creating port acquisition client');
this.portAcquisitionClient = new PortAcquisitionClient(
portAcquisitionManager,
this.createLogger(PortAcquisitionClient.name)
);
this.logger.debug(() => 'Creating debugger');
this.debugger = new Debugger(this.createLogger(Debugger.name), {
debuggerNamespace: options?.projectNamespace ? projectDisplayName : undefined
});
this.disposables.push(this.debugger);
this.logger.debug(() => 'Creating project commands handler');
const commandsNamespace = options?.projectNamespace ? `.${options.projectNamespace}` : '';
this.projectCommands = new Commands<ProjectCommand>(
this.createLogger(Commands.name),
`${EXTENSION_CONFIG_PREFIX}${commandsNamespace}`
);
this.projectCommands.register(ProjectCommand.ShowLog, () => this.outputChannelLog.show());
this.projectCommands.register(ProjectCommand.Reset, () => this.reset());
this.disposables.push(this.projectCommands);
this.logger.debug(() => 'Creating notifications handler');
this.notificationHandler = new NotificationHandler(
projectStatusDisplay,
this.createLogger(NotificationHandler.name),
{
showLogCommand: this.projectCommands.getCommandName(ProjectCommand.ShowLog)
}
);
this.disposables.push(this.notificationHandler);
this.logger.debug(() => 'Creating test emitters');
this.testLoadEmitter = new EventEmitter();
this.testRunEmitter = new EventEmitter();
this.retireEmitter = new EventEmitter();
this.disposables.push(this.testLoadEmitter, this.testRunEmitter, this.retireEmitter);
const { testExplorer, testExplorerDisposables } = this.createTestExplorer(config);
this.karmaTestExplorer = testExplorer;
this.testExplorerDisposables = testExplorerDisposables;
}
Example #25
Source File: leanclient.ts From vscode-lean4 with Apache License 2.0 | 5 votes |
private workspaceFolder: WorkspaceFolder | undefined;
Example #26
Source File: leanclient.ts From vscode-lean4 with Apache License 2.0 | 5 votes |
constructor(workspaceFolder: WorkspaceFolder | undefined, folderUri: Uri, storageManager : LocalStorageService, outputChannel : OutputChannel) {
this.storageManager = storageManager;
this.outputChannel = outputChannel;
this.workspaceFolder = workspaceFolder; // can be null when opening adhoc files.
this.folderUri = folderUri;
this.subscriptions.push(workspace.onDidChangeConfiguration((e) => this.configChanged(e)));
}
Example #27
Source File: dbtWorkspaceFolder.ts From vscode-dbt-power-user with MIT License | 5 votes |
private workspaceFolder: WorkspaceFolder;
Example #28
Source File: testUtilsV3.ts From dendron with GNU Affero General Public License v3.0 | 5 votes |
// ^bq7n7azzkpj2
export async function setupLegacyWorkspaceMulti(
opts: SetupLegacyWorkspaceMultiOpts
) {
const copts = _.defaults(opts, {
setupWsOverride: {
skipConfirmation: true,
emptyWs: true,
},
workspaceType: WorkspaceType.CODE,
preSetupHook: async () => {},
postSetupHook: async () => {},
wsSettingsOverride: {},
});
const { preSetupHook, postSetupHook, wsSettingsOverride } = copts;
if (!opts.configOverride) opts.configOverride = {};
// Always override the self contained config, otherwise it picks up the
// setting in the developer's machine during testing.
opts.configOverride[
DENDRON_VSCODE_CONFIG_KEYS.ENABLE_SELF_CONTAINED_VAULTS_WORKSPACE
] = !!opts.selfContained;
let workspaceFile: Uri | undefined;
// check where the keyboard shortcut is configured
let workspaceFolders: readonly WorkspaceFolder[] | undefined;
const { wsRoot, vaults } = await EngineTestUtilsV4.setupWS();
new StateService(opts.ctx!); // eslint-disable-line no-new
setupCodeConfiguration(opts);
if (copts.workspaceType === WorkspaceType.CODE) {
stubWorkspace({ wsRoot, vaults });
workspaceFile = DendronExtension.workspaceFile();
workspaceFolders = DendronExtension.workspaceFolders();
WorkspaceConfig.write(wsRoot, vaults, {
overrides: wsSettingsOverride,
vaults,
});
} else {
stubWorkspaceFolders(wsRoot, vaults);
}
await preSetupHook({
wsRoot,
vaults,
});
// update vscode settings
if (copts.workspaceType === WorkspaceType.CODE) {
await WorkspaceUtils.updateCodeWorkspaceSettings({
wsRoot,
updateCb: (settings) => {
const folders: WorkspaceFolderRaw[] = vaults.map((ent) => ({
path: ent.fsPath,
}));
settings = assignJSONWithComment({ folders }, settings);
return settings;
},
});
}
// update config
let config = DConfig.getOrCreate(wsRoot);
if (isNotUndefined(copts.modConfigCb)) {
config = TestConfigUtils.withConfig(copts.modConfigCb, { wsRoot });
}
ConfigUtils.setVaults(config, vaults);
await DConfig.writeConfig({ wsRoot, config });
await postSetupHook({
wsRoot,
vaults,
});
return { wsRoot, vaults, workspaceFile, workspaceFolders };
}
Example #29
Source File: workspace-util.test.ts From vscode-code-review with MIT License | 5 votes |
suite('Workspace Utils', () => {
suite('removeTrailingSlash', () => {
test('should remove a trailing slash from a string', () => {
assert.strictEqual(removeTrailingSlash('/foo/bar/'), '/foo/bar');
assert.strictEqual(removeTrailingSlash('/foo/bar\\'), '/foo/bar');
});
});
suite('removeLeadingSlash', () => {
test('should remove a trailing slash from a string', () => {
assert.strictEqual(removeLeadingSlash('/foo/bar/'), 'foo/bar/');
assert.strictEqual(removeLeadingSlash('\\foo/bar/'), 'foo/bar/');
});
});
suite('removeLeadingAndTrailingSlash', () => {
test('should remove a trailing slash from a string', () => {
assert.strictEqual(removeLeadingAndTrailingSlash('/foo/bar/'), 'foo/bar');
assert.strictEqual(removeLeadingAndTrailingSlash('\\foo/bar\\'), 'foo/bar');
});
});
suite('isProperSubpathOf', () => {
test('should be true for proper subpaths', () => {
assert.strictEqual(isProperSubpathOf('/home/user/workspace/file', '/home/user/workspace'), true);
assert.strictEqual(isProperSubpathOf('/home/user/workspace/file', '/'), true);
});
test('should be false for improper subpaths', () => {
assert.strictEqual(isProperSubpathOf('/home/user/workspace/file', '/home/user/workspace/file'), false);
});
test('should be false for non-subpaths', () => {
assert.strictEqual(isProperSubpathOf('/home/user/workspace', '/home/user/workspace/file'), false);
});
});
suite('getWorkspaceFolder', () => {
test('should return an empty string when undefined', () => {
assert.strictEqual(getWorkspaceFolder(undefined), '');
});
test('should return the workspace folder string', () => {
const workspaceFolders: WorkspaceFolder[] = [
{
uri: Uri.parse('/foo/bar/baz.js'),
name: 'baz.js',
index: 1,
},
];
const folders = workspaceFolders as WorkspaceFolder[];
assert.strictEqual(getWorkspaceFolder(folders), path.normalize('/foo/bar/baz.js'));
});
test('should fallback to activeTextEditor when defined', () => {
assert.strictEqual(getWorkspaceFolder([]), '');
assert.strictEqual(getWorkspaceFolder([], { document: {} } as TextEditor), '');
assert.strictEqual(getWorkspaceFolder([], { document: { fileName: '' } } as TextEditor), '');
assert.strictEqual(
getWorkspaceFolder([], { document: { fileName: '/foo/bar/baz.txt' } } as TextEditor),
'/foo/bar',
);
});
});
suite('toAbsolutePath', () => {
test('should generate a harmonized absolute path', () => {
let input = toAbsolutePath('/foo/bar', 'baz.js');
let reRemoveDrivePrefix = /^[A-Za-z]:/g; // remove the drive letter prefix for tests in CI (e.g. "D:")
assert.strictEqual(input.replace(reRemoveDrivePrefix, ''), path.normalize('/foo/bar/baz.js'));
input = toAbsolutePath('/foo/bar/', 'baz.js');
assert.strictEqual(input.replace(reRemoveDrivePrefix, ''), path.normalize('/foo/bar/baz.js'));
input = toAbsolutePath('/foo/bar/', '/baz.js');
assert.strictEqual(input.replace(reRemoveDrivePrefix, ''), path.normalize('/foo/bar/baz.js'));
input = toAbsolutePath('/foo/bar/', 'baz.js');
assert.strictEqual(input.replace(reRemoveDrivePrefix, ''), path.normalize('/foo/bar/baz.js'));
input = toAbsolutePath('/foo/bar/', '/a/baz.js');
assert.strictEqual(input.replace(reRemoveDrivePrefix, ''), path.normalize('/foo/bar/a/baz.js'));
input = toAbsolutePath('/foo/bar/', 'a/baz.js');
assert.strictEqual(input.replace(reRemoveDrivePrefix, ''), path.normalize('/foo/bar/a/baz.js'));
input = toAbsolutePath('/foo/bar/', 'a\\baz.js');
assert.strictEqual(input.replace(reRemoveDrivePrefix, ''), path.normalize('/foo/bar/a/baz.js'));
input = toAbsolutePath('/foo/bar/', '\\a\\baz.js');
assert.strictEqual(input.replace(reRemoveDrivePrefix, ''), path.normalize('/foo/bar/a/baz.js'));
input = toAbsolutePath('/foo/bar/', '\\a\\baz/');
assert.strictEqual(input.replace(reRemoveDrivePrefix, ''), path.normalize('/foo/bar/a/baz'));
input = toAbsolutePath('/foo/bar/', '\\b/a\\baz/');
assert.strictEqual(input.replace(reRemoveDrivePrefix, ''), path.normalize('/foo/bar/b/a/baz'));
});
});
suite('getFileContentForRange', () => {
const range = new Range(new Position(1, 1), new Position(2, 1));
test('should return the content from some line in a file', () => {
const filename = 'a.js';
fs.writeFileSync(filename, `foo${EOL}bar${EOL}baz${EOL}`);
const result = getFileContentForRange(filename, range);
assert.strictEqual(result, 'bar');
fs.unlinkSync(filename); // cleanup created file
});
test('should return an empty string when workspace folder cannot be determined', () => {
const result = getFileContentForRange('some-non-existing-file', range);
assert.strictEqual(result, '');
});
});
suite('getCsvFileHeader', () => {
test('should return the content from the first line in a file', () => {
const filename = 'a.js';
fs.writeFileSync(filename, `col1,col2,col3${EOL}val1,val2,val3`);
const result = getCsvFileHeader(filename);
assert.strictEqual(result, 'col1,col2,col3');
fs.unlinkSync(filename); // cleanup created file
});
test('should return an empty string when workspace folder cannot be determined', () => {
const result = getCsvFileHeader('some-non-existing-file');
assert.strictEqual(result, '');
});
});
suite('escapeDoubleQuotesForCsv', () => {
test('should escape a double quote sign as expected for CSV files (with another ")', () => {
assert.strictEqual(escapeDoubleQuotesForCsv('aa"bb'), 'aa""bb');
});
});
suite('escapeEndOfLineForCsv', () => {
test('should escape an end-of-line character as expected for CSV files (with a double anti-slash)', () => {
assert.strictEqual(escapeEndOfLineForCsv('aa\nbb'), 'aa\\nbb');
});
});
suite('unescapeEndOfLineFromCsv', () => {
test('should unescape an end-of-line marker as expected for CSV files (with a true eol)', () => {
assert.strictEqual(unescapeEndOfLineFromCsv('aa\\nbb'), 'aa\nbb');
});
});
suite('startLineNumberFromStringDefinition', () => {
test('should return the matching line before the colon', () => {
assert.strictEqual(startLineNumberFromStringDefinition('2:4'), 2);
assert.strictEqual(startLineNumberFromStringDefinition('103:18-12:4'), 103);
assert.strictEqual(startLineNumberFromStringDefinition(''), 0);
assert.strictEqual(startLineNumberFromStringDefinition(':3-12-4'), 0);
});
});
suite('startPositionNumberFromStringDefinition', () => {
test('should return the matching position after the colon', () => {
assert.strictEqual(startPositionNumberFromStringDefinition('2:4'), 4);
assert.strictEqual(startPositionNumberFromStringDefinition('103:18-12:4'), 18);
assert.strictEqual(startPositionNumberFromStringDefinition(''), 0);
assert.strictEqual(startPositionNumberFromStringDefinition(':3-12-4'), 3);
});
});
suite('endLineNumberFromStringDefinition', () => {
test('should return the matching line before the colon', () => {
assert.strictEqual(endLineNumberFromStringDefinition('103:18-12:4'), 12);
assert.strictEqual(endLineNumberFromStringDefinition('2:4'), 0);
assert.strictEqual(endLineNumberFromStringDefinition(''), 0);
assert.strictEqual(endLineNumberFromStringDefinition(':3-:4'), 0);
});
});
suite('endPositionNumberFromStringDefinition', () => {
test('should return the matching position after the colon', () => {
assert.strictEqual(endPositionNumberFromStringDefinition('103:18-12:4'), 4);
assert.strictEqual(endPositionNumberFromStringDefinition('2:4'), 0);
assert.strictEqual(endPositionNumberFromStringDefinition(''), 0);
assert.strictEqual(endPositionNumberFromStringDefinition(':3-:4'), 4);
});
});
suite('rangeFromStringDefinition', () => {
test('should return a range class based on the given string definition', () => {
const result = rangeFromStringDefinition('103:18-12:4');
assert.strictEqual(result instanceof Range, true);
assert.strictEqual(result.start.line, 11);
assert.strictEqual(result.start.character, 4);
assert.strictEqual(result.end.line, 102);
assert.strictEqual(result.end.character, 18);
});
test('should fallback to 0', () => {
let result = rangeFromStringDefinition('0');
assert.strictEqual(result instanceof Range, true);
assert.strictEqual(result.start.line, 0);
assert.strictEqual(result.start.character, 0);
assert.strictEqual(result.end.line, 0);
assert.strictEqual(result.end.character, 0);
result = rangeFromStringDefinition('0:0');
assert.strictEqual(result instanceof Range, true);
assert.strictEqual(result.start.line, 0);
assert.strictEqual(result.start.character, 0);
assert.strictEqual(result.end.line, 0);
assert.strictEqual(result.end.character, 0);
result = rangeFromStringDefinition('0:0-0:0');
assert.strictEqual(result instanceof Range, true);
assert.strictEqual(result.start.line, 0);
assert.strictEqual(result.start.character, 0);
assert.strictEqual(result.end.line, 0);
assert.strictEqual(result.end.character, 0);
});
});
suite('rangesFromStringDefinition', () => {
test('should return a range class based on the given string definition', () => {
const result = rangesFromStringDefinition('103:18-12:4|10:3-17:4|19:5-200:1');
assert.strictEqual(result.length, 3);
assert.strictEqual(result[0] instanceof Range, true);
assert.strictEqual(result[0].start.line, 11);
assert.strictEqual(result[0].start.character, 4);
assert.strictEqual(result[0].end.line, 102);
assert.strictEqual(result[0].end.character, 18);
assert.strictEqual(result[1] instanceof Range, true);
assert.strictEqual(result[1].start.line, 9);
assert.strictEqual(result[1].start.character, 3);
assert.strictEqual(result[1].end.line, 16);
assert.strictEqual(result[1].end.character, 4);
assert.strictEqual(result[2] instanceof Range, true);
assert.strictEqual(result[2].start.line, 18);
assert.strictEqual(result[2].start.character, 5);
assert.strictEqual(result[2].end.line, 199);
assert.strictEqual(result[2].end.character, 1);
});
});
suite('splitStringDefinition', () => {
test('should split a string definition by the "|" character', () => {
const result = splitStringDefinition('103:18-12:4|10:3-17:4|19:5-200:1');
assert.strictEqual(result.length, 3);
assert.deepStrictEqual(result, ['103:18-12:4', '10:3-17:4', '19:5-200:1']);
});
});
suite('sortLineSelections', () => {
test('should sort the line selection', () => {
assert.deepStrictEqual(['5:3-12:4', '8:2-10:5'].sort(sortLineSelections), ['5:3-12:4', '8:2-10:5']);
assert.deepStrictEqual(['5:3-12:4', '2:2-10:5'].sort(sortLineSelections), ['2:2-10:5', '5:3-12:4']);
});
});
suite('sortCsvEntryForLines', () => {
const dummyEntry = {
sha: 'string',
filename: 'string',
url: 'string',
title: 'string',
comment: 'string',
priority: 0,
category: 'string',
additional: 'string',
id: 'string',
private: 0,
};
const testData: CsvEntry[] = [
{
...dummyEntry,
lines: '5:3-8:2',
},
{
...dummyEntry,
lines: '4:2-6:7|9:0-12:8|6:3-12:8',
},
{
...dummyEntry,
lines: '8:6-9:3',
},
{
...dummyEntry,
lines: '10:5-10:12|7:2-11:3',
},
{
...dummyEntry,
lines: '3:2-14:6',
},
{
...dummyEntry,
lines: '4:5-15:0',
},
];
test('should sort the lines association correctly', () => {
const result = testData.sort(sortCsvEntryForLines);
assert.strictEqual(result[0].lines, '3:2-14:6');
assert.strictEqual(result[1].lines, '4:5-15:0');
assert.strictEqual(result[2].lines, '4:2-6:7|9:0-12:8|6:3-12:8');
assert.strictEqual(result[3].lines, '5:3-8:2');
assert.strictEqual(result[4].lines, '10:5-10:12|7:2-11:3');
assert.strictEqual(result[5].lines, '8:6-9:3');
});
});
suite('cleanCsvStorage', () => {
test('should return zero rows', () => {
assert.strictEqual(cleanCsvStorage([]).length, 0);
});
test('should return zero rows', () => {
assert.strictEqual(cleanCsvStorage(['', ' ']).length, 0);
});
test('should return non-empty rows', () => {
assert.strictEqual(cleanCsvStorage(['', ' ', 'row_1', 'row_2', '']).length, 2);
});
});
suite('createCommentFromObject', () => {
test('should return object with comment and id', () => {
const object = createCommentFromObject({ comment: 'some text' });
assert.strictEqual(object.comment, 'some text');
assert.notStrictEqual(object.id, '');
});
});
suite('formatAsCsvLine', () => {
test('should work even with an empty object', () => {
const object = createCommentFromObject({});
const line = CsvStructure.formatAsCsvLine(object);
assert.ok(line.length > 0);
});
});
suite('standardizeFilename', () => {
test('should return a refined filename', () => {
const workspaceRoot = '/path/to/my/workspace';
const filename = '/my/file';
const refined = standardizeFilename(workspaceRoot, workspaceRoot + filename);
assert.strictEqual(refined, filename);
});
});
suite('isValidComment', () => {
test('should detect empty object', () => {
assert.ok(!CsvStructure.isValidComment({} as CsvEntry));
});
test('should detect null comment', () => {
assert.ok(!CsvStructure.isValidComment(({ comment: null } as unknown) as CsvEntry));
});
test('should detect empty comment', () => {
assert.ok(!CsvStructure.isValidComment(({ comment: '' } as unknown) as CsvEntry));
});
test('should detect null filename', () => {
assert.ok(
!CsvStructure.isValidComment(({
comment: 'lorem ipsum',
filename: null,
} as unknown) as CsvEntry),
);
});
test('should detect empty filename', () => {
assert.ok(
!CsvStructure.isValidComment(({
comment: 'lorem ipsum',
filename: '',
} as unknown) as CsvEntry),
);
});
test('should detect empty filename', () => {
assert.ok(
!CsvStructure.isValidComment(({
comment: 'lorem ipsum',
filename: '/my/file.txt',
} as unknown) as CsvEntry),
);
});
test('should detect null id', () => {
assert.ok(
!CsvStructure.isValidComment(({
comment: 'lorem ipsum',
filename: '/my/file.txt',
id: null,
} as unknown) as CsvEntry),
);
});
test('should detect empty id', () => {
assert.ok(
!CsvStructure.isValidComment(({
comment: 'lorem ipsum',
filename: '/my/file.txt',
id: '',
} as unknown) as CsvEntry),
);
});
test('should detect invalid id', () => {
assert.ok(
!CsvStructure.isValidComment(({
comment: 'lorem ipsum',
filename: '/my/file.txt',
id: '123456',
} as unknown) as CsvEntry),
);
});
test('should detect null lines', () => {
assert.ok(
!CsvStructure.isValidComment(({
comment: 'lorem ipsum',
filename: '/my/file.txt',
id: '10c2d1ec-b98d-4b88-b7fc-ed141c66070c',
lines: null,
} as unknown) as CsvEntry),
);
});
test('should detect empty lines', () => {
assert.ok(
!CsvStructure.isValidComment(({
comment: 'lorem ipsum',
filename: '/my/file.txt',
id: '10c2d1ec-b98d-4b88-b7fc-ed141c66070c',
lines: '',
} as unknown) as CsvEntry),
);
});
test('should detect invalid lines', () => {
assert.ok(
!CsvStructure.isValidComment(({
comment: 'lorem ipsum',
filename: '/my/file.txt',
id: '10c2d1ec-b98d-4b88-b7fc-ed141c66070c',
lines: '0:0',
} as unknown) as CsvEntry),
);
});
test('should accept single selection', () => {
assert.ok(
CsvStructure.isValidComment(({
comment: 'lorem ipsum',
filename: '/my/file.txt',
id: '10c2d1ec-b98d-4b88-b7fc-ed141c66070c',
lines: '0:0-0:0',
} as unknown) as CsvEntry),
);
});
test('should accept multiple selection (1)', () => {
assert.ok(
CsvStructure.isValidComment(({
comment: 'lorem ipsum',
filename: '/my/file.txt',
id: '10c2d1ec-b98d-4b88-b7fc-ed141c66070c',
lines: '0:0-0:0|0:0-0:0',
} as unknown) as CsvEntry),
);
});
test('should accept multiple selection (2)', () => {
assert.ok(
CsvStructure.isValidComment(({
comment: 'lorem ipsum',
filename: '/my/file.txt',
id: '10c2d1ec-b98d-4b88-b7fc-ed141c66070c',
lines: '0:0-0:0|0:0-0:0|0:0-0:0',
} as unknown) as CsvEntry),
);
});
});
suite('isValidColorDefinition', () => {
test('should match color definition', () => {
assert.ok(isValidColorDefinition('#C8C832'));
assert.ok(isValidColorDefinition('#C8C83226'));
assert.ok(isValidColorDefinition('rgba(200, 200, 50, 0)'));
assert.ok(isValidColorDefinition('rgba(200, 200, 50, 1)'));
assert.ok(isValidColorDefinition('rgba(200, 200, 50, 0.15)'));
});
test('should not match color definition', () => {
assert.ok(!isValidColorDefinition(''));
assert.ok(!isValidColorDefinition('C8C832'));
assert.ok(!isValidColorDefinition('C8C83226'));
assert.ok(!isValidColorDefinition('#ABCDE'));
assert.ok(!isValidColorDefinition('#ABCDEF1'));
assert.ok(!isValidColorDefinition('rgba(200, 200, 50)'));
});
});
suite('getBackupFilename', () => {
test('should return the actual filename with a current timestamp', () => {
const date = new Date();
const year = date.getFullYear();
const month = (date.getMonth() + 1).toLocaleString('en', { minimumIntegerDigits: 2 });
assert.ok(getBackupFilename('test-csv').startsWith('test-csv-'));
assert.ok(getBackupFilename('test-csv').includes(`${year.toString()}-`));
assert.ok(getBackupFilename('test-csv').includes(`${month.toString()}-`));
assert.ok(getBackupFilename('test-csv').endsWith('Z.bak'));
});
});
suite('standardizeFilename', () => {
test('should remove the workspace-part from the filename', () => {
assert.strictEqual(standardizeFilename('/foo/bar', '/foo/bar/baz.txt'), '/baz.txt');
});
});
});