UNPKG

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