-
Notifications
You must be signed in to change notification settings - Fork 6
/
tabset.js
executable file
·507 lines (453 loc) · 12.9 KB
/
tabset.js
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
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
#!/usr/bin/env node
'use strict'
var process = require('process')
var fs = require('fs')
var linewrap = require('linewrap')
var minimist = require('minimist')
var path = require('path')
var tildify = require('tildify')
var stringHash = require('string-hash')
var colorpick = require('./colorpick')
var cssColors = require('./csscolors')
var util = require('./util')
var _ = require('underscore')
util.globalize(util)
var wrap = linewrap(70, { skipScheme: 'ansi-color' })
var argopt = { alias: { a: 'all', b: 'badge', c: 'color',
h: 'hash', t: 'title', p: 'pick',
del: 'delete', V: 'verbose' },
'boolean': ['pwd', 'verbose', 'debug']
}
var args = minimist(process.argv.slice(2), argopt)
const ARGS_DEBUG = args.debug
dprintln.display = args.debug
const cwd = process.cwd()
var defaultColorSpec = 'peru'
var colors = cssColors()
var allcolors = _.clone(colors) // remember even if deleted
var cssColorNames = _.keys(colors).sort()
updateColorMap('default', defaultColorSpec)
var configpath = path.join(process.env.HOME, '.tabset')
const defaultConfig = { colors: {
alisongreen: 'rgb(125,199,53)'
},
defaults: {
all: '.',
title: '.',
badge: '.',
color: '.'
}
}
var config = readJSON(configpath) || defaultConfig
interpretConfig(config)
process_args()
function process_args () {
args.pwd ? println('dir:', cwd) : null;
if (ARGS_DEBUG)
console.log('args:', args)
// help requested
if (args.help) {
println()
println('To set an iTerm2 tab\'s color, badge, or title:')
println()
println('tabset --all|-a <string>')
println(' --color|-c <named-color>')
println(' | <rgb()>')
println(' | <hex-color>')
println(' | random')
println(' | RANDOM')
println(' --pick|-p')
println(' --hash|-h <string>')
println(' --badge|-b <string>')
println(' --title|-t <string>')
println(' --pwd')
println(' --mode 0 | 1 | 2')
println(' --init')
println(' --add <name> <colorspec>')
println(' --add <name> --pick|-p')
println(' --del <name>')
println(' --list')
println(' --colors')
println(' --help')
println(' --verbose|-V')
println()
}
const nFreeArgs = _.size(args._)
// no real args given, so improvise
var noSpecificArgs = (_.size(args) === (argopt['boolean'].length + 1 + 1));
// always expect _ and booleans (e.g. pwd and verbose)
// they do not count at "specific" arguments
dprintln('noSpecificArgs:', jsonify(noSpecificArgs))
if (!nFreeArgs && noSpecificArgs) {
args.all = settingString(null, 'all')
if (!args.all) {
args.all = cwd
}
dprintln('set args.all to', args.all)
}
if (args.colors) {
var colorNames = _.keys(colors).sort()
println(wrap('named colors: ' + colorNames.join(', ')))
}
// combo set everthing
if (nFreeArgs === 1) {
args.all = settingString(args._[0], 'all')
} else if (nFreeArgs > 1) {
args.all = args._.join(' ')
}
if (ARGS_DEBUG) {
console.log('nFreeArgs:', nFreeArgs)
console.log('setting args.all to:' , args.all)
}
if (args.all) {
setBadge(args.all)
setTabTitle(args.all, definedOr(args.mode, 1))
var col = decodeColorSpec(args.all)
if (!col) {
var colorNames = _.keys(colors).sort()
var index = stringHash(args.all) % colorNames.length
var hashColor = colorNames[index]
col = colors[hashColor]
}
showChoice('picked color:', hashColor)
setTabColor(col, definedOr(args.mode, 1))
}
if (args.badge) {
var badge = settingString(args.badge, 'badge')
setBadge(badge)
}
if (args.title) {
var title = settingString(args.title, 'title')
setTabTitle(title, definedOr(args.mode, 1))
}
if (args.hash && !args.color) {
args.color = true
}
if (args.add) {
if (!_.isString(args.add)) {
errorExit('must give name to add')
}
if (args.pick) {
colorpick({ targetApp: 'iTerm2'},
function (res) {
addColor(args.add, rgbstr(res.rgb))
println('added:', args.add)
})
} else if (_.size(args._) === 1) {
addColor(args.add, args._[0])
println('added:', args.add)
} else {
errorExit('add what color?')
}
} else if (args.pick) {
colorpick({ targetApp: 'iTerm2'},
function (res) {
println('picked:', rgbstr(res.rgb))
setTabColor(res.rgb)
})
}
if (args.del) {
if (!_.isString(args.del)) {
errorExit('must give name to delete')
}
delColor(args.del)
println('deleted:', args.del)
}
if (args.list) {
listColors()
}
if (args.color) {
setTabColor(decodeColor(args.color))
}
if (args.init) {
initConfigFile()
}
}
/**
* Interpret a color/title/badge setting string,
* using a default value if need be.
*/
function settingString(s, category) {
var finalS = s
if ((s === true) || (!s)) {
finalS = config.defaults[category]
}
if (ARGS_DEBUG)
console.log('s:', s, 'finalS:', finalS, 'cwd:', cwd)
if ((finalS === '~') || (finalS == process.env['HOME'])) {
return tildify(cwd)
} else if ((finalS === '.') || (finalS === cwd)){
return path.basename(cwd)
}
if (ARGS_DEBUG)
console.log('backup return')
return finalS
}
/**
* Add a color to the local definitions
*/
function addColor (name, spec) {
config.colors[name] = spec
writeJSON(configpath, config)
}
/**
* Remove a color from use. If it's a base color, need
* to mark it `null` in config file. Otherwise, no reason
* to even keep it in the config file. Delete outright.
*/
function delColor (name) {
if (_.contains(cssColorNames, name)) {
config.colors[name] = null
} else if (_.has(config.colors, name)) {
delete config.colors[name]
} else {
errorExit('no such color', jsonify(name))
}
writeJSON(configpath, config)
}
/**
* List out the custom colors.
*/
function listColors () {
if (_.isEmpty(config.colors)) {
println('no custom colors to list')
} else {
println()
var namel = maxLength(config.colors)
var swatchl = 9
var nulled = []
println(padRight('Name', namel + 1),
padRight('Swatch', swatchl + 1),
'Definition')
_.each(config.colors, function (value, key) {
if (!value) {
nulled.push(key)
} else {
var rgb = decodeColorSpec(value)
var swatch = swatchString(rgb, swatchl)
println(padRight(key, namel + 1), swatch + ' ', value)
}
})
if (nulled.length) {
println()
var nullplus = nulled.map(n => {
var rgb = decodeColorSpec(n)
return n + (rgb ? swatchString(rgb, 2) : '')
})
println(wrap('Nulled: ' + nullplus.join(', ')))
}
println()
}
}
/**
* Return a swatch (ANSI-colored string).
* @param {Array of Integer} rgb - color as rgb values
* @param {Integer} length - how wide?
*/
function swatchString (rgb, length) {
return ansiseq2(`48;2;${rgb[0]};${rgb[1]};${rgb[2]}m`,
padRight('', length))
}
/**
* A low-level color spec decoder that handles only
* the simple cases: A named color, rgb() spec, or
* hex rgb spec.
*/
function decodeColorSpec (spec) {
spec = spec.toString(); // in case not string already
// exact match for existing named color?
if (colors) {
var color = allcolors[spec]
if (color) {
return color
}
}
// match rgb(r, g, b)
var rgbmatch = spec.match(/rgb\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*\)/i)
if (rgbmatch) {
return [ parseInt(rgbmatch[1]),
parseInt(rgbmatch[2]),
parseInt(rgbmatch[3]) ]
}
// match #fa21b4
var hexmatch = spec.match(/^#?([0-9a-f][0-9a-f])([0-9a-f][0-9a-f])([0-9a-f][0-9a-f])$/i)
if (hexmatch) {
return [ parseInt(hexmatch[1], 16),
parseInt(hexmatch[2], 16),
parseInt(hexmatch[3], 16) ]
}
// failed to decode
return null
}
/**
* A high-level color decoder that handles the complex,
* UI-entangled cases such as random colors, hashed colors,
* partial string search, and defaults. By delegation to
* decodeColorSpec(), also handles the simpler cases of
* exactly named colors and rgb() or hex CSS color definitions.
*/
function decodeColor (name) {
if (_.isArray(name)) { // predecoded!
return name
}
if (name === null) { // not in use
return name
}
var colorNames = _.keys(colors).sort()
if (!_.isString(name)) {
// --color invoked, but no color specified
// might be a hashed color request
if (args.hash) {
var index = stringHash(args.hash) % colorNames.length
var hashColor = colorNames[index]
showChoice('hashed color:', hashColor)
return colors[hashColor]
}
// nope, no hash; so pick something at random
name = 'random'
}
// random named color
if (name === 'random') {
var randColor = _.sample(colorNames)
showChoice('random color:', randColor)
return colors[randColor]
}
// RANDOM color - not just a random named color
if (name === 'RANDOM') {
var rcolor = [_.random(255), _.random(255), _.random(255) ]
showChoice('RANDOM color:', rgbstr(rcolor))
return rcolor
}
// try a low level spec
name = name.toLowerCase()
var defn = decodeColorSpec(name)
if (defn) {
return defn
}
// finally, a string containment search
if (colorNames) {
var possibles = colorNames.filter(s => {
return s.indexOf(name) >= 0
})
if (possibles.length === 1) {
showChoice('guessing:', possibles[0])
return colors[possibles[0]]
} else if (possibles.length > 1) {
println(wrap('possibly: ' + possibles.join(', ')))
var rcolor = _.sample(possibles)
showChoice('randomly picked:', rcolor)
return colors[rcolor]
}
}
// nothing worked, use default color
showChoice('using default:', defaultColorSpec)
println('because no color', jsonify(name), 'known')
println('use --colors option to list color names')
return colors['default']
}
/**
* Show a given color choice. Print the current working
* directory if global args says so.
*/
function showChoice (label, value) {
if (args.vervise && label && value) {
println(label, value)
}
}
/**
* Format a three-element rgb araay into a CSS-style
* rgb specification.
*/
function rgbstr (rgbarray) {
return [ 'rgb(', rgbarray.join(','), ')'].join('')
}
/**
* Set the tab or window color of the topmost iTerm2 tab/window.
*
* @param {Array of int} color RGB colors to set.
*/
function setTabColor (color) {
var cmd = ansiseq('6;1;bg;red;brightness;', color[0]) +
ansiseq('6;1;bg;green;brightness;', color[1]) +
ansiseq('6;1;bg;blue;brightness;', color[2])
print(cmd)
}
/**
* Set the title of the topmost iTerm2 tab.
*
* @param {string} title
* @param {int} mode 0 => tab title and window title,
* 1 => tab title, 2 => window title
*/
function setTabTitle (title, mode) {
var cmd = ansiseq(mode, ';', title)
print(cmd)
}
/**
* Set the badge of the topmost iTerm2 tab.
*
* @param {string} msg
*/
function setBadge (msg) {
msg += '\u00a0' // give some right spacing
var msg64 = Buffer.from(msg.toString()).toString('base64')
var cmd = ansiseq('1337;SetBadgeFormat=', msg64)
print(cmd)
}
/**
* Many of iTterm2's command sequences begin with an ESC ] and end with a
* BEL (Ctrl-G). This function returns its arguments wrapped
* in those start/stop codes.
*/
function ansiseq () {
var parts = _.flatten(['\u001b]', _.toArray(arguments), '\u0007'])
return parts.join('')
}
/**
* Other iTterm2 command sequences are slightly differently structured.
* This function returns its arguments wrapped
* in those start/stop codes.
*/
function ansiseq2 () {
var parts = _.flatten(['\u001b[', _.toArray(arguments), '\u001b[0m'])
return parts.join('')
}
function interpretConfig (config) {
_.each(config.colors, function (spec, key) {
if (key === 'default') {
defaultColorSpec = spec // might be name or value
}
updateColorMap(key, spec)
})
}
/**
* Write a suitable default configuration file
*/
function initConfigFile () {
if (fs.existsSync(configpath)) {
errorExit('config file already exists')
}
var sample = {
colors: {
alisongreen: 'rgb(125,199,53)',
js: 'orchid',
html: 'gold',
server: 'alisongreen',
papayawhip: null
}
}
writeJSON(configpath, sample)
}
/**
* Update the existing color map, either by
* adding decoded color specs or deleting entries.
*/
function updateColorMap (key, value) {
if (value === null) {
delete colors[key]
} else {
var rgb = decodeColorSpec(value)
colors[key] = rgb
allcolors[key] = rgb
}
}