-
Notifications
You must be signed in to change notification settings - Fork 215
/
plugins.go
460 lines (423 loc) · 10.8 KB
/
plugins.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
package main
import (
"encoding/json"
"errors"
"fmt"
"io/ioutil"
"os"
"os/exec"
"os/signal"
"path/filepath"
"runtime"
"sort"
"strconv"
"strings"
"syscall"
"github.com/dickeyxxx/golock"
"github.com/heroku/heroku-cli/gode"
)
// Plugin represents a javascript plugin
type Plugin struct {
Name string `json:"name"`
Version string `json:"version"`
Topics TopicSet `json:"topics"`
Topic *Topic `json:"topic"`
Commands CommandSet `json:"commands"`
}
// SetupNode sets up node and npm in ~/.heroku
func SetupNode() {
gode.SetRootPath(AppDir())
if !gode.IsSetup() {
Errf("Setting up node-v%s...", gode.Version)
ExitIfError(gode.Setup())
Errln(" done")
}
}
func updateNode() {
gode.SetRootPath(AppDir())
if gode.NeedsUpdate() {
Errf("Setting up node-v%s...", gode.Version)
PrintError(gode.Setup())
Errln(" done")
}
}
// LoadPlugins loads the topics and commands from the JavaScript plugins into the CLI
func (cli *Cli) LoadPlugins(plugins []Plugin) {
for _, plugin := range plugins {
for _, topic := range plugin.Topics {
cli.AddTopic(topic)
}
if plugin.Topic != nil {
cli.AddTopic(plugin.Topic)
}
for _, command := range plugin.Commands {
if !cli.AddCommand(command) {
Errf("WARNING: command %s has already been defined\n", command)
}
}
}
sort.Sort(cli.Topics)
sort.Sort(cli.Commands)
}
var pluginsTopic = &Topic{
Name: "plugins",
Description: "manage plugins",
}
var pluginsInstallCmd = &Command{
Topic: "plugins",
Command: "install",
Hidden: true,
Args: []Arg{{Name: "name"}},
Description: "Installs a plugin into the CLI",
Help: `Install a Heroku plugin
Example:
$ heroku plugins:install dickeyxxx/heroku-production-status`,
Run: func(ctx *Context) {
name := ctx.Args.(map[string]string)["name"]
if len(name) == 0 {
Errln("Must specify a plugin name")
return
}
Errf("Installing plugin %s... ", name)
err := installPlugins(name)
ExitIfError(err)
plugin := getPlugin(name, false)
if plugin == nil || len(plugin.Commands) == 0 {
Err("\nThis does not appear to be a Heroku plugin, uninstalling... ")
ExitIfError(gode.RemovePackage(name))
}
ClearPluginCache()
WritePluginCache(GetPlugins())
Errln("done")
},
}
var pluginsLinkCmd = &Command{
Topic: "plugins",
Command: "link",
Description: "Links a local plugin into CLI",
Args: []Arg{{Name: "path", Optional: true}},
Help: `Links a local plugin into CLI.
This is useful when developing plugins locally.
It simply symlinks the specified path into ~/.heroku/node_modules
Example:
$ heroku plugins:link .`,
Run: func(ctx *Context) {
path := ctx.Args.(map[string]string)["path"]
if path == "" {
path = "."
}
path, err := filepath.Abs(path)
if err != nil {
panic(err)
}
if _, err := os.Stat(path); err != nil {
panic(err)
}
name := filepath.Base(path)
newPath := filepath.Join(ctx.HerokuDir, "node_modules", name)
os.Remove(newPath)
os.RemoveAll(newPath)
err = os.Symlink(path, newPath)
if err != nil {
panic(err)
}
plugin := getPlugin(name, false)
if plugin == nil || len(plugin.Commands) == 0 {
Errln(name + " does not appear to be a Heroku plugin.\nDid you run `npm install`?")
if err := os.Remove(newPath); err != nil {
panic(err)
}
return
}
if name != plugin.Name {
path = newPath
newPath = filepath.Join(ctx.HerokuDir, "node_modules", plugin.Name)
os.Remove(newPath)
os.RemoveAll(newPath)
os.Rename(path, newPath)
}
Println("symlinked", plugin.Name)
Err("Updating plugin cache... ")
ClearPluginCache()
WritePluginCache(GetPlugins())
Errln("done")
},
}
var pluginsUninstallCmd = &Command{
Topic: "plugins",
Command: "uninstall",
Hidden: true,
Args: []Arg{{Name: "name"}},
Description: "Uninstalls a plugin from the CLI",
Help: `Uninstalls a Heroku plugin
Example:
$ heroku plugins:uninstall heroku-production-status`,
Run: func(ctx *Context) {
name := ctx.Args.(map[string]string)["name"]
Errf("Uninstalling plugin %s... ", name)
err := gode.RemovePackage(name)
ExitIfError(err)
Errln("done")
},
}
var pluginsListCmd = &Command{
Topic: "plugins",
Hidden: true,
Description: "Lists the installed plugins",
Help: `Lists installed plugins
Example:
$ heroku plugins`,
Run: func(ctx *Context) {
packages, err := gode.Packages()
if err != nil {
panic(err)
}
for _, pkg := range packages {
Println(pkg.Name, pkg.Version)
}
},
}
func runFn(plugin *Plugin, module, topic, command string) func(ctx *Context) {
return func(ctx *Context) {
lockfile := updateLockPath + "." + module
if exists, _ := fileExists(lockfile); exists {
golock.Lock(lockfile)
golock.Unlock(lockfile)
}
ctx.Dev = isPluginSymlinked(module)
ctxJSON, err := json.Marshal(ctx)
if err != nil {
panic(err)
}
script := fmt.Sprintf(`
'use strict';
var moduleName = '%s';
var moduleVersion = '%s';
var topic = '%s';
var command = '%s';
process.title = '%s';
var ctx = %s;
ctx.version = ctx.version + ' ' + moduleName + '/' + moduleVersion + ' node-' + process.version;
var logPath = %s;
process.chdir(ctx.cwd);
function repair (name) {
console.error('Attempting to repair ' + name + '...');
require('child_process')
.spawnSync('heroku', ['plugins:install', name],
{stdio: [0,1,2]});
console.error('Repair complete. Try running your command again.');
}
if (!ctx.dev) {
process.on('uncaughtException', function (err) {
console.error(' ! Error in ' + moduleName + ':')
if (err.message) {
console.error(' ! ' + err.message);
if (err.message.indexOf('Cannot find module') != -1) {
repair(moduleName);
process.exit(1);
}
} else {
console.error(' ! ' + err);
}
if (err.stack) {
var fs = require('fs');
var log = function (line) {
var d = new Date().toISOString()
.replace(/T/, ' ')
.replace(/-/g, '/')
.replace(/\..+/, '');
fs.appendFileSync(logPath, d + ' ' + line + '\n');
}
log('Error during ' + topic + ':' + command);
log(err.stack);
console.error(' ! See ' + logPath + ' for more info.');
}
process.exit(1);
});
}
if (command === '') { command = null }
var module = require(moduleName);
var cmd = module.commands.filter(function (c) {
return c.topic === topic && c.command == command;
})[0];
cmd.run(ctx);`, module, plugin.Version, topic, command, processTitle(ctx), ctxJSON, strconv.Quote(ErrLogPath))
// swallow sigint since the plugin will handle it
swallowSignal(os.Interrupt)
cmd := gode.RunScript(script)
if ctx.Flags["debugger"] == true {
cmd = gode.DebugScript(script)
}
os.Chdir(cmd.Dir)
execBin(cmd.Path, cmd.Args)
}
}
func execBin(bin string, args []string) {
if runtime.GOOS == "windows" {
cmd := exec.Command(bin, args[1:]...)
cmd.Stdin = os.Stdin
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
if err := cmd.Run(); err != nil {
os.Exit(getExitCode(err))
}
} else {
if err := syscall.Exec(bin, args, os.Environ()); err != nil {
panic(err)
}
}
}
func swallowSignal(s os.Signal) {
c := make(chan os.Signal, 1)
signal.Notify(c, s)
go func() {
<-c
}()
}
func getExitCode(err error) int {
switch e := err.(type) {
case *exec.ExitError:
status, ok := e.Sys().(syscall.WaitStatus)
if !ok {
panic(err)
}
return status.ExitStatus()
default:
panic(err)
}
}
func getPlugin(name string, attemptReinstall bool) *Plugin {
script := `
var plugin = require('` + name + `');
var pjson = require('` + name + `/package.json');
plugin.name = pjson.name;
plugin.version = pjson.version;
console.log(JSON.stringify(plugin))`
cmd := gode.RunScript(script)
output, err := cmd.CombinedOutput()
if err != nil {
if attemptReinstall && strings.Contains(string(output), "Error: Cannot find module") {
Errf("Error reading plugin %s. Reinstalling... ", name)
if err := installPlugins(name); err != nil {
panic(errors.New(string(output)))
}
Errln("done")
return getPlugin(name, false)
}
Errf("Error reading plugin: %s. See %s for more information.\n", name, ErrLogPath)
Logln(err, "\n", string(output))
return nil
}
var plugin Plugin
json.Unmarshal([]byte(output), &plugin)
return &plugin
}
// GetPlugins goes through all the node plugins and returns them in Go stucts
func GetPlugins() []Plugin {
cache := FetchPluginCache()
names := PluginNames()
plugins := make([]Plugin, 0, len(names))
for _, name := range names {
plugin := cache[name]
if plugin == nil {
plugin = getPlugin(name, true)
}
if plugin != nil {
for _, command := range plugin.Commands {
command.Plugin = name
command.Run = runFn(plugin, name, command.Topic, command.Command)
command.Help = strings.TrimSpace(command.Help)
}
plugins = append(plugins, *plugin)
}
}
return plugins
}
// PluginNames just lists the files in ~/.heroku/node_modules
func PluginNames() []string {
files, _ := ioutil.ReadDir(filepath.Join(AppDir(), "node_modules"))
names := make([]string, 0, len(files))
for _, f := range files {
if !ignorePlugin(f.Name()) {
names = append(names, f.Name())
}
}
return names
}
// PluginNamesNotSymlinked returns all the plugins that are not symlinked
func PluginNamesNotSymlinked() []string {
a := PluginNames()
b := make([]string, 0, len(a))
for _, plugin := range a {
if !isPluginSymlinked(plugin) {
b = append(b, plugin)
}
}
return b
}
func ignorePlugin(plugin string) bool {
ignored := []string{".bin", ".DS_Store", "node-inspector"}
for _, p := range ignored {
if plugin == p {
return true
}
}
return false
}
func isPluginSymlinked(plugin string) bool {
path := filepath.Join(AppDir(), "node_modules", plugin)
fi, err := os.Lstat(path)
if err != nil {
panic(err)
}
return fi.Mode()&os.ModeSymlink != 0
}
// SetupBuiltinPlugins ensures all the builtinPlugins are installed
func SetupBuiltinPlugins() {
plugins := difference(BuiltinPlugins, PluginNames())
if len(plugins) == 0 {
return
}
noun := "plugins"
if len(plugins) == 1 {
noun = "plugin"
}
Errf("Installing core %s %s...", noun, strings.Join(plugins, ", "))
err := installPlugins(plugins...)
if err != nil {
Errln()
PrintError(err)
return
}
ClearPluginCache()
WritePluginCache(GetPlugins())
Errln(" done")
}
func difference(a, b []string) []string {
res := make([]string, 0, len(a))
for _, aa := range a {
if !contains(b, aa) {
res = append(res, aa)
}
}
return res
}
func contains(arr []string, s string) bool {
for _, a := range arr {
if a == s {
return true
}
}
return false
}
func installPlugins(plugins ...string) error {
for _, plugin := range plugins {
lockfile := updateLockPath + "." + plugin
LogIfError(golock.Lock(lockfile))
}
err := gode.InstallPackage(plugins...)
for _, plugin := range plugins {
lockfile := updateLockPath + "." + plugin
LogIfError(golock.Unlock(lockfile))
}
return err
}