forked from heroku/cli
/
plugins.go
457 lines (420 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
package main
import (
"encoding/json"
"errors"
"fmt"
"os"
"os/exec"
"os/signal"
"path/filepath"
"sort"
"strconv"
"strings"
"syscall"
"github.com/heroku/heroku-cli/Godeps/_workspace/src/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())
setup, err := gode.IsSetup()
PrintError(err)
if !setup {
setupNode()
}
}
func setupNode() {
Err("heroku-cli: Adding dependencies...")
PrintError(gode.Setup())
Errln(" done")
}
func updateNode() {
gode.SetRootPath(AppDir())
needsUpdate, err := gode.NeedsUpdate()
PrintError(err)
if needsUpdate {
setupNode()
}
}
// LoadPlugins loads the topics and commands from the JavaScript plugins into the CLI
func (cli *Cli) LoadPlugins(plugins map[string]*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, true)
if plugin == nil || len(plugin.Commands) == 0 {
Err("\nThis does not appear to be a Heroku plugin, uninstalling... ")
ExitIfError(gode.RemovePackage(name))
}
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 := pluginPath(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 " + cyan("npm install") + "?")
if err := os.Remove(newPath); err != nil {
panic(err)
}
return
}
if name != plugin.Name {
path = newPath
newPath = pluginPath(plugin.Name)
os.Remove(newPath)
os.RemoveAll(newPath)
os.Rename(path, newPath)
}
Println("Symlinked", plugin.Name)
AddPluginsToCache(plugin)
},
}
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)
RemovePluginFromCache(name)
Errln("done")
},
}
var pluginsListCmd = &Command{
Topic: "plugins",
Hidden: true,
Description: "Lists installed plugins",
Help: `
Example:
$ heroku plugins`,
Run: func(ctx *Context) {
SetupBuiltinPlugins()
var plugins []string
for _, plugin := range GetPlugins() {
if plugin != nil && len(plugin.Commands) > 0 {
symlinked := ""
if isPluginSymlinked(plugin.Name) {
symlinked = " (symlinked)"
}
plugins = append(plugins, fmt.Sprintf("%s %s %s", plugin.Name, plugin.Version, symlinked))
}
}
sort.Strings(plugins)
for _, plugin := range plugins {
Println(plugin)
}
},
}
func runFn(plugin *Plugin, topic, command string) func(ctx *Context) {
return func(ctx *Context) {
lockfile := updateLockPath + "." + plugin.Name
if exists, _ := fileExists(lockfile); exists {
golock.Lock(lockfile)
golock.Unlock(lockfile)
}
ctx.Dev = isPluginSymlinked(plugin.Name)
ctxJSON, err := json.Marshal(ctx)
if err != nil {
panic(err)
}
title, _ := json.Marshal(processTitle(ctx))
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);`, plugin.Name, plugin.Version, topic, command, string(title), ctxJSON, strconv.Quote(ErrLogPath))
// swallow sigint since the plugin will handle it
swallowSignal(os.Interrupt)
cmd := gode.RunScript(script)
cmd.Stdin = os.Stdin
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
if ctx.Flags["debugger"] == true {
cmd = gode.DebugScript(script)
}
if err := cmd.Run(); err != nil {
os.Exit(getExitCode(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 nil:
return 0
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 + `');
if (!plugin.commands) plugin = {}; // not a real plugin
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(name + ": " + 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)
for _, command := range plugin.Commands {
command.Plugin = plugin.Name
command.Help = strings.TrimSpace(command.Help)
}
return &plugin
}
// GetPlugins goes through all the node plugins and returns them in Go stucts
func GetPlugins() map[string]*Plugin {
plugins := FetchPluginCache()
for name, plugin := range plugins {
if plugin == nil || !pluginExists(name) {
delete(plugins, name)
} else {
for _, command := range plugin.Commands {
command.Run = runFn(plugin, command.Topic, command.Command)
}
}
}
return plugins
}
// PluginNames lists all the plugin names
func PluginNames() []string {
plugins := FetchPluginCache()
names := make([]string, 0, len(plugins))
for _, plugin := range plugins {
if plugin != nil {
names = append(names, plugin.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 isPluginSymlinked(plugin string) bool {
path := filepath.Join(AppDir(), "node_modules", plugin)
fi, err := os.Lstat(path)
if err != nil {
return false
}
return fi.Mode()&os.ModeSymlink != 0
}
// SetupBuiltinPlugins ensures all the builtinPlugins are installed
func SetupBuiltinPlugins() {
pluginNames := difference(BuiltinPlugins, PluginNames())
if len(pluginNames) == 0 {
return
}
Err("heroku-cli: Installing core plugins...")
err := installPlugins(pluginNames...)
if err != nil {
Errln()
PrintError(err)
return
}
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(names ...string) error {
for _, name := range names {
lockfile := updateLockPath + "." + name
LogIfError(golock.Lock(lockfile))
}
err := gode.InstallPackage(names...)
if err != nil {
return err
}
plugins := make([]*Plugin, 0, len(names))
for _, name := range names {
plugins = append(plugins, getPlugin(name, true))
}
AddPluginsToCache(plugins...)
for _, name := range names {
lockfile := updateLockPath + "." + name
LogIfError(golock.Unlock(lockfile))
}
return nil
}
func pluginExists(plugin string) bool {
exists, _ := fileExists(pluginPath(plugin))
return exists
}
func pluginPath(plugin string) string {
return filepath.Join(AppDir(), "node_modules", plugin)
}