|
| 1 | +/*----------------------------------------------------------------------------------------------- |
| 2 | + * Copyright (c) Red Hat, Inc. All rights reserved. |
| 3 | + * Licensed under the MIT License. See LICENSE file in the project root for license information. |
| 4 | + *-----------------------------------------------------------------------------------------------*/ |
| 5 | + |
| 6 | +import { KubernetesObject } from '@kubernetes/client-node'; |
| 7 | +import { load as loadYaml } from 'js-yaml'; |
| 8 | +import * as vscode from 'vscode'; |
| 9 | + |
| 10 | +const YAML_SELECTOR: vscode.DocumentSelector = { |
| 11 | + language: 'yaml', |
| 12 | + scheme: 'file' |
| 13 | +}; |
| 14 | + |
| 15 | +const RANGE: vscode.Range = new vscode.Range(new vscode.Position(0, 0), new vscode.Position(0, 1)); |
| 16 | + |
| 17 | +export function registerYamlHandlers(): vscode.Disposable[] { |
| 18 | + const disposables: vscode.Disposable[] = []; |
| 19 | + disposables.push( |
| 20 | + vscode.languages.registerCodeLensProvider(YAML_SELECTOR, new YamlCodeLensProvider())); |
| 21 | + return disposables; |
| 22 | +} |
| 23 | + |
| 24 | +class YamlCodeLensProvider implements vscode.CodeLensProvider { |
| 25 | + provideCodeLenses(document: vscode.TextDocument, _token: vscode.CancellationToken): vscode.ProviderResult<vscode.CodeLens[]> { |
| 26 | + |
| 27 | + try { |
| 28 | + |
| 29 | + const objectTexts: string[] = document.getText().split(/(?:^---\r?\n)|(?:\n---\r?\n)/).filter(text => text && text.length > 0); |
| 30 | + |
| 31 | + for (const objectText of objectTexts) { |
| 32 | + const yaml = loadYaml(objectText) as KubernetesObject; |
| 33 | + |
| 34 | + // heuristic to check if it's a k8s yaml |
| 35 | + if (!yaml.apiVersion || !yaml.kind || !yaml.metadata) { |
| 36 | + return []; |
| 37 | + } |
| 38 | + } |
| 39 | + |
| 40 | + } catch (e) { |
| 41 | + return []; |
| 42 | + } |
| 43 | + |
| 44 | + return [ |
| 45 | + { |
| 46 | + isResolved: true, |
| 47 | + range: RANGE, |
| 48 | + command: { |
| 49 | + command: 'openshift.create', |
| 50 | + title: 'Apply YAML to cluster', |
| 51 | + tooltip: 'Performs `kubectl apply -f` on this file' |
| 52 | + } |
| 53 | + }, |
| 54 | + { |
| 55 | + isResolved: true, |
| 56 | + range: RANGE, |
| 57 | + command: { |
| 58 | + command: 'openshift.delete', |
| 59 | + title: 'Delete YAML from cluster', |
| 60 | + tooltip: 'Performs `kubectl delete -f` on this file' |
| 61 | + } |
| 62 | + } |
| 63 | + ]; |
| 64 | + } |
| 65 | +} |
0 commit comments