UNPKG

3.11 kBJavaScriptView Raw
1"use strict";
2Object.defineProperty(exports, "__esModule", { value: true });
3exports.ensureHostAndKeyPath = exports.findHostSection = exports.getConfigPath = exports.isHostDirective = exports.isDirective = exports.loadFromPath = exports.SSHConfig = void 0;
4const utils_fs_1 = require("@ionic/utils-fs");
5const os = require("os");
6const path = require("path");
7const SSHConfig = require("ssh-config");
8exports.SSHConfig = SSHConfig;
9async function loadFromPath(p) {
10 const s = await utils_fs_1.fileToString(p);
11 return SSHConfig.parse(s);
12}
13exports.loadFromPath = loadFromPath;
14function isDirective(entry) {
15 return entry && entry.type === SSHConfig.DIRECTIVE;
16}
17exports.isDirective = isDirective;
18function isHostDirective(entry) {
19 return isDirective(entry) && entry.param === 'Host';
20}
21exports.isHostDirective = isHostDirective;
22function getConfigPath() {
23 return path.resolve(os.homedir(), '.ssh', 'config');
24}
25exports.getConfigPath = getConfigPath;
26function findHostSection(conf, host) {
27 return conf.find({ Host: host });
28}
29exports.findHostSection = findHostSection;
30function ensureHostAndKeyPath(conf, conn, keyPath) {
31 const section = ensureHostSection(conf, conn.host);
32 const index = conf.indexOf(section);
33 ensureSectionLine(section, 'IdentityFile', keyPath);
34 if (typeof conn.port === 'number' && conn.port !== 22) {
35 ensureSectionLine(section, 'Port', String(conn.port));
36 }
37 // massage the section for proper whitespace
38 if (index === 0) {
39 section.before = '';
40 }
41 else {
42 const previousSection = conf[index - 1];
43 if (isHostDirective(previousSection)) {
44 const previousSectionLastEntry = previousSection.config[previousSection.config.length - 1];
45 if (previousSectionLastEntry) {
46 previousSectionLastEntry.after = '\n';
47 }
48 }
49 else {
50 previousSection.after = '\n';
51 }
52 section.before = '\n';
53 }
54 section.after = '\n';
55 if (!section.config) {
56 section.config = [];
57 }
58 for (const entry of section.config) {
59 entry.before = ' ';
60 entry.after = '\n';
61 }
62 if (index !== conf.length - 1) {
63 const lastEntry = section.config[section.config.length - 1];
64 lastEntry.after = '\n\n';
65 }
66}
67exports.ensureHostAndKeyPath = ensureHostAndKeyPath;
68function ensureHostSection(conf, host) {
69 let section = findHostSection(conf, host);
70 if (!section) {
71 conf.push(SSHConfig.parse(`\nHost ${host}\n`)[0]);
72 section = findHostSection(conf, host);
73 }
74 if (!section) {
75 throw new Error(`Could not find/insert section for host: ${host}`);
76 }
77 return section;
78}
79function ensureSectionLine(section, key, value) {
80 const found = section.config.some(line => {
81 if (isDirective(line)) {
82 if (line.param === key) {
83 line.value = value;
84 return true;
85 }
86 }
87 return false;
88 });
89 if (!found) {
90 section.config = section.config.concat(SSHConfig.parse(`${key} ${value}\n`));
91 }
92}