1
0

cjdnsshell 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. #!/usr/bin/env node
  2. /* -*- Mode:Js */
  3. /* vim: set expandtab ts=4 sw=4: */
  4. /*
  5. * You may redistribute this program and/or modify it under the terms of
  6. * the GNU General Public License as published by the Free Software Foundation,
  7. * either version 3 of the License, or (at your option) any later version.
  8. *
  9. * This program is distributed in the hope that it will be useful,
  10. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  12. * GNU General Public License for more details.
  13. *
  14. * You should have received a copy of the GNU General Public License
  15. * along with this program. If not, see <https://www.gnu.org/licenses/>.
  16. */
  17. const cjdns = require('./lib/cjdnsadmin/cjdnsadmin');
  18. const util = require('util');
  19. const vm = require('vm');
  20. const readline = require('readline');
  21. /**
  22. * Promisify all functions in an object
  23. * @param {Object} obj Object to promisify
  24. */
  25. function promisifyAll(obj) {
  26. for (let k in obj) {
  27. if (typeof obj[k] === 'function') {
  28. obj[k] = util.promisify(obj[k]);
  29. }
  30. }
  31. }
  32. /**
  33. * Connect to cjdns
  34. * @return {Promise} A promise resolving to the session object
  35. */
  36. function connect() {
  37. return new Promise((resolve, reject) => {
  38. cjdns.connectWithAdminInfo(c => resolve(c));
  39. });
  40. }
  41. /**
  42. * Start the shell
  43. */
  44. async function runShell() {
  45. let session = await connect();
  46. console.log([
  47. `Connected`,
  48. `Run "functions()" for a list of functions`
  49. ].join('\n'));
  50. promisifyAll(session);
  51. let ctx = vm.createContext(session);
  52. let rl = readline.createInterface({
  53. input: process.stdin,
  54. output: process.stdout,
  55. prompt: 'cjdns> ',
  56. removeHistoryDuplicates: true
  57. });
  58. rl.on('line', async line => {
  59. let result;
  60. try {
  61. result = vm.runInContext(line, ctx);
  62. if (typeof result === 'undefined') return rl.prompt();
  63. if (result.then) result = await result;
  64. } catch (err) {
  65. result = err;
  66. }
  67. console.dir(result, {colors: true});
  68. rl.prompt();
  69. });
  70. rl.on('close', () => process.exit(0));
  71. rl.prompt();
  72. }
  73. runShell();