-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathconfig.coffee
1262 lines (1146 loc) · 40.8 KB
/
config.coffee
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
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
_ = require 'underscore-plus'
fs = require 'fs-plus'
{CompositeDisposable, Disposable, Emitter} = require 'event-kit'
CSON = require 'season'
path = require 'path'
async = require 'async'
pathWatcher = require 'pathwatcher'
{
getValueAtKeyPath, setValueAtKeyPath, deleteValueAtKeyPath,
pushKeyPath, splitKeyPath,
} = require 'key-path-helpers'
Color = require './color'
ScopedPropertyStore = require 'scoped-property-store'
ScopeDescriptor = require './scope-descriptor'
# Essential: Used to access all of Atom's configuration details.
#
# An instance of this class is always available as the `atom.config` global.
#
# ## Getting and setting config settings.
#
# ```coffee
# # Note that with no value set, ::get returns the setting's default value.
# atom.config.get('my-package.myKey') # -> 'defaultValue'
#
# atom.config.set('my-package.myKey', 'value')
# atom.config.get('my-package.myKey') # -> 'value'
# ```
#
# You may want to watch for changes. Use {::observe} to catch changes to the setting.
#
# ```coffee
# atom.config.set('my-package.myKey', 'value')
# atom.config.observe 'my-package.myKey', (newValue) ->
# # `observe` calls immediately and every time the value is changed
# console.log 'My configuration changed:', newValue
# ```
#
# If you want a notification only when the value changes, use {::onDidChange}.
#
# ```coffee
# atom.config.onDidChange 'my-package.myKey', ({newValue, oldValue}) ->
# console.log 'My configuration changed:', newValue, oldValue
# ```
#
# ### Value Coercion
#
# Config settings each have a type specified by way of a
# [schema](json-schema.org). For example we might an integer setting that only
# allows integers greater than `0`:
#
# ```coffee
# # When no value has been set, `::get` returns the setting's default value
# atom.config.get('my-package.anInt') # -> 12
#
# # The string will be coerced to the integer 123
# atom.config.set('my-package.anInt', '123')
# atom.config.get('my-package.anInt') # -> 123
#
# # The string will be coerced to an integer, but it must be greater than 0, so is set to 1
# atom.config.set('my-package.anInt', '-20')
# atom.config.get('my-package.anInt') # -> 1
# ```
#
# ## Defining settings for your package
#
# Define a schema under a `config` key in your package main.
#
# ```coffee
# module.exports =
# # Your config schema
# config:
# someInt:
# type: 'integer'
# default: 23
# minimum: 1
#
# activate: (state) -> # ...
# # ...
# ```
#
# See [package docs](http://flight-manual.atom.io/hacking-atom/sections/package-word-count/) for
# more info.
#
# ## Config Schemas
#
# We use [json schema](http://json-schema.org) which allows you to define your value's
# default, the type it should be, etc. A simple example:
#
# ```coffee
# # We want to provide an `enableThing`, and a `thingVolume`
# config:
# enableThing:
# type: 'boolean'
# default: false
# thingVolume:
# type: 'integer'
# default: 5
# minimum: 1
# maximum: 11
# ```
#
# The type keyword allows for type coercion and validation. If a `thingVolume` is
# set to a string `'10'`, it will be coerced into an integer.
#
# ```coffee
# atom.config.set('my-package.thingVolume', '10')
# atom.config.get('my-package.thingVolume') # -> 10
#
# # It respects the min / max
# atom.config.set('my-package.thingVolume', '400')
# atom.config.get('my-package.thingVolume') # -> 11
#
# # If it cannot be coerced, the value will not be set
# atom.config.set('my-package.thingVolume', 'cats')
# atom.config.get('my-package.thingVolume') # -> 11
# ```
#
# ### Supported Types
#
# The `type` keyword can be a string with any one of the following. You can also
# chain them by specifying multiple in an an array. For example
#
# ```coffee
# config:
# someSetting:
# type: ['boolean', 'integer']
# default: 5
#
# # Then
# atom.config.set('my-package.someSetting', 'true')
# atom.config.get('my-package.someSetting') # -> true
#
# atom.config.set('my-package.someSetting', '12')
# atom.config.get('my-package.someSetting') # -> 12
# ```
#
# #### string
#
# Values must be a string.
#
# ```coffee
# config:
# someSetting:
# type: 'string'
# default: 'hello'
# ```
#
# #### integer
#
# Values will be coerced into integer. Supports the (optional) `minimum` and
# `maximum` keys.
#
# ```coffee
# config:
# someSetting:
# type: 'integer'
# default: 5
# minimum: 1
# maximum: 11
# ```
#
# #### number
#
# Values will be coerced into a number, including real numbers. Supports the
# (optional) `minimum` and `maximum` keys.
#
# ```coffee
# config:
# someSetting:
# type: 'number'
# default: 5.3
# minimum: 1.5
# maximum: 11.5
# ```
#
# #### boolean
#
# Values will be coerced into a Boolean. `'true'` and `'false'` will be coerced into
# a boolean. Numbers, arrays, objects, and anything else will not be coerced.
#
# ```coffee
# config:
# someSetting:
# type: 'boolean'
# default: false
# ```
#
# #### array
#
# Value must be an Array. The types of the values can be specified by a
# subschema in the `items` key.
#
# ```coffee
# config:
# someSetting:
# type: 'array'
# default: [1, 2, 3]
# items:
# type: 'integer'
# minimum: 1.5
# maximum: 11.5
# ```
#
# #### color
#
# Values will be coerced into a {Color} with `red`, `green`, `blue`, and `alpha`
# properties that all have numeric values. `red`, `green`, `blue` will be in
# the range 0 to 255 and `value` will be in the range 0 to 1. Values can be any
# valid CSS color format such as `#abc`, `#abcdef`, `white`,
# `rgb(50, 100, 150)`, and `rgba(25, 75, 125, .75)`.
#
# ```coffee
# config:
# someSetting:
# type: 'color'
# default: 'white'
# ```
#
# #### object / Grouping other types
#
# A config setting with the type `object` allows grouping a set of config
# settings. The group will be visualy separated and has its own group headline.
# The sub options must be listed under a `properties` key.
#
# ```coffee
# config:
# someSetting:
# type: 'object'
# properties:
# myChildIntOption:
# type: 'integer'
# minimum: 1.5
# maximum: 11.5
# ```
#
# ### Other Supported Keys
#
# #### enum
#
# All types support an `enum` key, which lets you specify all the values the
# setting can take. `enum` may be an array of allowed values (of the specified
# type), or an array of objects with `value` and `description` properties, where
# the `value` is an allowed value, and the `description` is a descriptive string
# used in the settings view.
#
# In this example, the setting must be one of the 4 integers:
#
# ```coffee
# config:
# someSetting:
# type: 'integer'
# default: 4
# enum: [2, 4, 6, 8]
# ```
#
# In this example, the setting must be either 'foo' or 'bar', which are
# presented using the provided descriptions in the settings pane:
#
# ```coffee
# config:
# someSetting:
# type: 'string'
# default: 'foo'
# enum: [
# {value: 'foo', description: 'Foo mode. You want this.'}
# {value: 'bar', description: 'Bar mode. Nobody wants that!'}
# ]
# ```
#
# Usage:
#
# ```coffee
# atom.config.set('my-package.someSetting', '2')
# atom.config.get('my-package.someSetting') # -> 2
#
# # will not set values outside of the enum values
# atom.config.set('my-package.someSetting', '3')
# atom.config.get('my-package.someSetting') # -> 2
#
# # If it cannot be coerced, the value will not be set
# atom.config.set('my-package.someSetting', '4')
# atom.config.get('my-package.someSetting') # -> 4
# ```
#
# #### title and description
#
# The settings view will use the `title` and `description` keys to display your
# config setting in a readable way. By default the settings view humanizes your
# config key, so `someSetting` becomes `Some Setting`. In some cases, this is
# confusing for users, and a more descriptive title is useful.
#
# Descriptions will be displayed below the title in the settings view.
#
# For a group of config settings the humanized key or the title and the
# description are used for the group headline.
#
# ```coffee
# config:
# someSetting:
# title: 'Setting Magnitude'
# description: 'This will affect the blah and the other blah'
# type: 'integer'
# default: 4
# ```
#
# __Note__: You should strive to be so clear in your naming of the setting that
# you do not need to specify a title or description!
#
# Descriptions allow a subset of
# [Markdown formatting](https://help.github.com/articles/github-flavored-markdown/).
# Specifically, you may use the following in configuration setting descriptions:
#
# * **bold** - `**bold**`
# * *italics* - `*italics*`
# * [links](https://atom.io) - `[links](https://atom.io)`
# * `code spans` - `\`code spans\``
# * line breaks - `line breaks<br/>`
# * ~~strikethrough~~ - `~~strikethrough~~`
#
# #### order
#
# The settings view orders your settings alphabetically. You can override this
# ordering with the order key.
#
# ```coffee
# config:
# zSetting:
# type: 'integer'
# default: 4
# order: 1
# aSetting:
# type: 'integer'
# default: 4
# order: 2
# ```
#
# ## Best practices
#
# * Don't depend on (or write to) configuration keys outside of your keypath.
#
module.exports =
class Config
@schemaEnforcers = {}
@addSchemaEnforcer: (typeName, enforcerFunction) ->
@schemaEnforcers[typeName] ?= []
@schemaEnforcers[typeName].push(enforcerFunction)
@addSchemaEnforcers: (filters) ->
for typeName, functions of filters
for name, enforcerFunction of functions
@addSchemaEnforcer(typeName, enforcerFunction)
return
@executeSchemaEnforcers: (keyPath, value, schema) ->
error = null
types = schema.type
types = [types] unless Array.isArray(types)
for type in types
try
enforcerFunctions = @schemaEnforcers[type].concat(@schemaEnforcers['*'])
for enforcer in enforcerFunctions
# At some point in one's life, one must call upon an enforcer.
value = enforcer.call(this, keyPath, value, schema)
error = null
break
catch e
error = e
throw error if error?
value
# Created during initialization, available as `atom.config`
constructor: ({@configDirPath, @resourcePath, @notificationManager, @enablePersistence}={}) ->
if @enablePersistence?
@configFilePath = fs.resolve(@configDirPath, 'config', ['json', 'cson'])
@configFilePath ?= path.join(@configDirPath, 'config.cson')
@clear()
clear: ->
@emitter = new Emitter
@schema =
type: 'object'
properties: {}
@defaultSettings = {}
@settings = {}
@scopedSettingsStore = new ScopedPropertyStore
@configFileHasErrors = false
@transactDepth = 0
@savePending = false
@requestLoad = _.debounce(@loadUserConfig, 100)
@requestSave = =>
@savePending = true
debouncedSave.call(this)
save = =>
@savePending = false
@save()
debouncedSave = _.debounce(save, 100)
shouldNotAccessFileSystem: -> not @enablePersistence
###
Section: Config Subscription
###
# Essential: Add a listener for changes to a given key path. This is different
# than {::onDidChange} in that it will immediately call your callback with the
# current value of the config entry.
#
# ### Examples
#
# You might want to be notified when the themes change. We'll watch
# `core.themes` for changes
#
# ```coffee
# atom.config.observe 'core.themes', (value) ->
# # do stuff with value
# ```
#
# * `keyPath` {String} name of the key to observe
# * `options` (optional) {Object}
# * `scope` (optional) {ScopeDescriptor} describing a path from
# the root of the syntax tree to a token. Get one by calling
# {editor.getLastCursor().getScopeDescriptor()}. See {::get} for examples.
# See [the scopes docs](http://flight-manual.atom.io/behind-atom/sections/scoped-settings-scopes-and-scope-descriptors/)
# for more information.
# * `callback` {Function} to call when the value of the key changes.
# * `value` the new value of the key
#
# Returns a {Disposable} with the following keys on which you can call
# `.dispose()` to unsubscribe.
observe: ->
if arguments.length is 2
[keyPath, callback] = arguments
else if arguments.length is 3 and (_.isString(arguments[0]) and _.isObject(arguments[1]))
[keyPath, options, callback] = arguments
scopeDescriptor = options.scope
else
console.error 'An unsupported form of Config::observe is being used. See https://atom.io/docs/api/latest/Config for details'
return
if scopeDescriptor?
@observeScopedKeyPath(scopeDescriptor, keyPath, callback)
else
@observeKeyPath(keyPath, options ? {}, callback)
# Essential: Add a listener for changes to a given key path. If `keyPath` is
# not specified, your callback will be called on changes to any key.
#
# * `keyPath` (optional) {String} name of the key to observe. Must be
# specified if `scopeDescriptor` is specified.
# * `options` (optional) {Object}
# * `scope` (optional) {ScopeDescriptor} describing a path from
# the root of the syntax tree to a token. Get one by calling
# {editor.getLastCursor().getScopeDescriptor()}. See {::get} for examples.
# See [the scopes docs](http://flight-manual.atom.io/behind-atom/sections/scoped-settings-scopes-and-scope-descriptors/)
# for more information.
# * `callback` {Function} to call when the value of the key changes.
# * `event` {Object}
# * `newValue` the new value of the key
# * `oldValue` the prior value of the key.
#
# Returns a {Disposable} with the following keys on which you can call
# `.dispose()` to unsubscribe.
onDidChange: ->
if arguments.length is 1
[callback] = arguments
else if arguments.length is 2
[keyPath, callback] = arguments
else
[keyPath, options, callback] = arguments
scopeDescriptor = options.scope
if scopeDescriptor?
@onDidChangeScopedKeyPath(scopeDescriptor, keyPath, callback)
else
@onDidChangeKeyPath(keyPath, callback)
###
Section: Managing Settings
###
# Essential: Retrieves the setting for the given key.
#
# ### Examples
#
# You might want to know what themes are enabled, so check `core.themes`
#
# ```coffee
# atom.config.get('core.themes')
# ```
#
# With scope descriptors you can get settings within a specific editor
# scope. For example, you might want to know `editor.tabLength` for ruby
# files.
#
# ```coffee
# atom.config.get('editor.tabLength', scope: ['source.ruby']) # => 2
# ```
#
# This setting in ruby files might be different than the global tabLength setting
#
# ```coffee
# atom.config.get('editor.tabLength') # => 4
# atom.config.get('editor.tabLength', scope: ['source.ruby']) # => 2
# ```
#
# You can get the language scope descriptor via
# {TextEditor::getRootScopeDescriptor}. This will get the setting specifically
# for the editor's language.
#
# ```coffee
# atom.config.get('editor.tabLength', scope: @editor.getRootScopeDescriptor()) # => 2
# ```
#
# Additionally, you can get the setting at the specific cursor position.
#
# ```coffee
# scopeDescriptor = @editor.getLastCursor().getScopeDescriptor()
# atom.config.get('editor.tabLength', scope: scopeDescriptor) # => 2
# ```
#
# * `keyPath` The {String} name of the key to retrieve.
# * `options` (optional) {Object}
# * `sources` (optional) {Array} of {String} source names. If provided, only
# values that were associated with these sources during {::set} will be used.
# * `excludeSources` (optional) {Array} of {String} source names. If provided,
# values that were associated with these sources during {::set} will not
# be used.
# * `scope` (optional) {ScopeDescriptor} describing a path from
# the root of the syntax tree to a token. Get one by calling
# {editor.getLastCursor().getScopeDescriptor()}
# See [the scopes docs](http://flight-manual.atom.io/behind-atom/sections/scoped-settings-scopes-and-scope-descriptors/)
# for more information.
#
# Returns the value from Atom's default settings, the user's configuration
# file in the type specified by the configuration schema.
get: ->
if arguments.length > 1
if typeof arguments[0] is 'string' or not arguments[0]?
[keyPath, options] = arguments
{scope} = options
else
[keyPath] = arguments
if scope?
value = @getRawScopedValue(scope, keyPath, options)
value ? @getRawValue(keyPath, options)
else
@getRawValue(keyPath, options)
# Extended: Get all of the values for the given key-path, along with their
# associated scope selector.
#
# * `keyPath` The {String} name of the key to retrieve
# * `options` (optional) {Object} see the `options` argument to {::get}
#
# Returns an {Array} of {Object}s with the following keys:
# * `scopeDescriptor` The {ScopeDescriptor} with which the value is associated
# * `value` The value for the key-path
getAll: (keyPath, options) ->
{scope, sources} = options if options?
result = []
if scope?
scopeDescriptor = ScopeDescriptor.fromObject(scope)
result = result.concat @scopedSettingsStore.getAll(scopeDescriptor.getScopeChain(), keyPath, options)
if globalValue = @getRawValue(keyPath, options)
result.push(scopeSelector: '*', value: globalValue)
result
# Essential: Sets the value for a configuration setting.
#
# This value is stored in Atom's internal configuration file.
#
# ### Examples
#
# You might want to change the themes programmatically:
#
# ```coffee
# atom.config.set('core.themes', ['atom-light-ui', 'atom-light-syntax'])
# ```
#
# You can also set scoped settings. For example, you might want change the
# `editor.tabLength` only for ruby files.
#
# ```coffee
# atom.config.get('editor.tabLength') # => 4
# atom.config.get('editor.tabLength', scope: ['source.ruby']) # => 4
# atom.config.get('editor.tabLength', scope: ['source.js']) # => 4
#
# # Set ruby to 2
# atom.config.set('editor.tabLength', 2, scopeSelector: '.source.ruby') # => true
#
# # Notice it's only set to 2 in the case of ruby
# atom.config.get('editor.tabLength') # => 4
# atom.config.get('editor.tabLength', scope: ['source.ruby']) # => 2
# atom.config.get('editor.tabLength', scope: ['source.js']) # => 4
# ```
#
# * `keyPath` The {String} name of the key.
# * `value` The value of the setting. Passing `undefined` will revert the
# setting to the default value.
# * `options` (optional) {Object}
# * `scopeSelector` (optional) {String}. eg. '.source.ruby'
# See [the scopes docs](http://flight-manual.atom.io/behind-atom/sections/scoped-settings-scopes-and-scope-descriptors/)
# for more information.
# * `source` (optional) {String} The name of a file with which the setting
# is associated. Defaults to the user's config file.
#
# Returns a {Boolean}
# * `true` if the value was set.
# * `false` if the value was not able to be coerced to the type specified in the setting's schema.
set: ->
[keyPath, value, options] = arguments
scopeSelector = options?.scopeSelector
source = options?.source
shouldSave = options?.save ? true
if source and not scopeSelector
throw new Error("::set with a 'source' and no 'sourceSelector' is not yet implemented!")
source ?= @getUserConfigPath()
unless value is undefined
try
value = @makeValueConformToSchema(keyPath, value)
catch e
return false
if scopeSelector?
@setRawScopedValue(keyPath, value, source, scopeSelector)
else
@setRawValue(keyPath, value)
@requestSave() if source is @getUserConfigPath() and shouldSave and not @configFileHasErrors
true
# Essential: Restore the setting at `keyPath` to its default value.
#
# * `keyPath` The {String} name of the key.
# * `options` (optional) {Object}
# * `scopeSelector` (optional) {String}. See {::set}
# * `source` (optional) {String}. See {::set}
unset: (keyPath, options) ->
{scopeSelector, source} = options ? {}
source ?= @getUserConfigPath()
if scopeSelector?
if keyPath?
settings = @scopedSettingsStore.propertiesForSourceAndSelector(source, scopeSelector)
if getValueAtKeyPath(settings, keyPath)?
@scopedSettingsStore.removePropertiesForSourceAndSelector(source, scopeSelector)
setValueAtKeyPath(settings, keyPath, undefined)
settings = withoutEmptyObjects(settings)
@set(null, settings, {scopeSelector, source, priority: @priorityForSource(source)}) if settings?
@requestSave()
else
@scopedSettingsStore.removePropertiesForSourceAndSelector(source, scopeSelector)
@emitChangeEvent()
else
for scopeSelector of @scopedSettingsStore.propertiesForSource(source)
@unset(keyPath, {scopeSelector, source})
if keyPath? and source is @getUserConfigPath()
@set(keyPath, getValueAtKeyPath(@defaultSettings, keyPath))
# Extended: Get an {Array} of all of the `source` {String}s with which
# settings have been added via {::set}.
getSources: ->
_.uniq(_.pluck(@scopedSettingsStore.propertySets, 'source')).sort()
# Extended: Retrieve the schema for a specific key path. The schema will tell
# you what type the keyPath expects, and other metadata about the config
# option.
#
# * `keyPath` The {String} name of the key.
#
# Returns an {Object} eg. `{type: 'integer', default: 23, minimum: 1}`.
# Returns `null` when the keyPath has no schema specified, but is accessible
# from the root schema.
getSchema: (keyPath) ->
keys = splitKeyPath(keyPath)
schema = @schema
for key in keys
if schema.type is 'object'
childSchema = schema.properties?[key]
unless childSchema?
if isPlainObject(schema.additionalProperties)
childSchema = schema.additionalProperties
else if schema.additionalProperties is false
return null
else
return {type: 'any'}
else
return null
schema = childSchema
schema
# Extended: Get the {String} path to the config file being used.
getUserConfigPath: ->
@configFilePath
# Extended: Suppress calls to handler functions registered with {::onDidChange}
# and {::observe} for the duration of `callback`. After `callback` executes,
# handlers will be called once if the value for their key-path has changed.
#
# * `callback` {Function} to execute while suppressing calls to handlers.
transact: (callback) ->
@beginTransaction()
try
callback()
finally
@endTransaction()
###
Section: Internal methods used by core
###
# Private: Suppress calls to handler functions registered with {::onDidChange}
# and {::observe} for the duration of the {Promise} returned by `callback`.
# After the {Promise} is either resolved or rejected, handlers will be called
# once if the value for their key-path has changed.
#
# * `callback` {Function} that returns a {Promise}, which will be executed
# while suppressing calls to handlers.
#
# Returns a {Promise} that is either resolved or rejected according to the
# `{Promise}` returned by `callback`. If `callback` throws an error, a
# rejected {Promise} will be returned instead.
transactAsync: (callback) ->
@beginTransaction()
try
endTransaction = (fn) => (args...) =>
@endTransaction()
fn(args...)
result = callback()
new Promise (resolve, reject) ->
result.then(endTransaction(resolve)).catch(endTransaction(reject))
catch error
@endTransaction()
Promise.reject(error)
beginTransaction: ->
@transactDepth++
endTransaction: ->
@transactDepth--
@emitChangeEvent()
pushAtKeyPath: (keyPath, value) ->
arrayValue = @get(keyPath) ? []
result = arrayValue.push(value)
@set(keyPath, arrayValue)
result
unshiftAtKeyPath: (keyPath, value) ->
arrayValue = @get(keyPath) ? []
result = arrayValue.unshift(value)
@set(keyPath, arrayValue)
result
removeAtKeyPath: (keyPath, value) ->
arrayValue = @get(keyPath) ? []
result = _.remove(arrayValue, value)
@set(keyPath, arrayValue)
result
setSchema: (keyPath, schema) ->
unless isPlainObject(schema)
throw new Error("Error loading schema for #{keyPath}: schemas can only be objects!")
unless typeof schema.type?
throw new Error("Error loading schema for #{keyPath}: schema objects must have a type attribute")
rootSchema = @schema
if keyPath
for key in splitKeyPath(keyPath)
rootSchema.type = 'object'
rootSchema.properties ?= {}
properties = rootSchema.properties
properties[key] ?= {}
rootSchema = properties[key]
Object.assign rootSchema, schema
@transact =>
@setDefaults(keyPath, @extractDefaultsFromSchema(schema))
@setScopedDefaultsFromSchema(keyPath, schema)
@resetSettingsForSchemaChange()
load: ->
@initializeConfigDirectory()
@loadUserConfig()
@observeUserConfig()
###
Section: Private methods managing the user's config file
###
initializeConfigDirectory: (done) ->
return if fs.existsSync(@configDirPath) or @shouldNotAccessFileSystem()
fs.makeTreeSync(@configDirPath)
queue = async.queue ({sourcePath, destinationPath}, callback) ->
fs.copy(sourcePath, destinationPath, callback)
queue.drain = done
templateConfigDirPath = fs.resolve(@resourcePath, 'dot-atom')
onConfigDirFile = (sourcePath) =>
relativePath = sourcePath.substring(templateConfigDirPath.length + 1)
destinationPath = path.join(@configDirPath, relativePath)
queue.push({sourcePath, destinationPath})
fs.traverseTree(templateConfigDirPath, onConfigDirFile, (path) -> true)
loadUserConfig: ->
return if @shouldNotAccessFileSystem()
try
unless fs.existsSync(@configFilePath)
fs.makeTreeSync(path.dirname(@configFilePath))
CSON.writeFileSync(@configFilePath, {})
catch error
@configFileHasErrors = true
@notifyFailure("Failed to initialize `#{path.basename(@configFilePath)}`", error.stack)
return
try
unless @savePending
userConfig = CSON.readFileSync(@configFilePath)
@resetUserSettings(userConfig)
@configFileHasErrors = false
catch error
@configFileHasErrors = true
message = "Failed to load `#{path.basename(@configFilePath)}`"
detail = if error.location?
# stack is the output from CSON in this case
error.stack
else
# message will be EACCES permission denied, et al
error.message
@notifyFailure(message, detail)
observeUserConfig: ->
return if @shouldNotAccessFileSystem()
try
@watchSubscription ?= pathWatcher.watch @configFilePath, (eventType) =>
@requestLoad() if eventType is 'change' and @watchSubscription?
catch error
@notifyFailure """
Unable to watch path: `#{path.basename(@configFilePath)}`. Make sure you have permissions to
`#{@configFilePath}`. On linux there are currently problems with watch
sizes. See [this document][watches] for more info.
[watches]:https://github.com/atom/atom/blob/master/docs/build-instructions/linux.md#typeerror-unable-to-watch-path
"""
unobserveUserConfig: ->
@watchSubscription?.close()
@watchSubscription = null
notifyFailure: (errorMessage, detail) ->
@notificationManager?.addError(errorMessage, {detail, dismissable: true})
save: ->
return if @shouldNotAccessFileSystem()
allSettings = {'*': @settings}
allSettings = Object.assign allSettings, @scopedSettingsStore.propertiesForSource(@getUserConfigPath())
allSettings = sortObject(allSettings)
try
CSON.writeFileSync(@configFilePath, allSettings)
catch error
message = "Failed to save `#{path.basename(@configFilePath)}`"
detail = error.message
@notifyFailure(message, detail)
###
Section: Private methods managing global settings
###
resetUserSettings: (newSettings) ->
unless isPlainObject(newSettings)
@settings = {}
@emitChangeEvent()
return
if newSettings.global?
newSettings['*'] = newSettings.global
delete newSettings.global
if newSettings['*']?
scopedSettings = newSettings
newSettings = newSettings['*']
delete scopedSettings['*']
@resetUserScopedSettings(scopedSettings)
@transact =>
@settings = {}
@set(key, value, save: false) for key, value of newSettings
return
getRawValue: (keyPath, options) ->
unless options?.excludeSources?.indexOf(@getUserConfigPath()) >= 0
value = getValueAtKeyPath(@settings, keyPath)
unless options?.sources?.length > 0
defaultValue = getValueAtKeyPath(@defaultSettings, keyPath)
if value?
value = @deepClone(value)
@deepDefaults(value, defaultValue) if isPlainObject(value) and isPlainObject(defaultValue)
else
value = @deepClone(defaultValue)
value
setRawValue: (keyPath, value) ->
defaultValue = getValueAtKeyPath(@defaultSettings, keyPath)
if _.isEqual(defaultValue, value)
if keyPath?
deleteValueAtKeyPath(@settings, keyPath)
else
@settings = null
else
if keyPath?
setValueAtKeyPath(@settings, keyPath, value)
else
@settings = value
@emitChangeEvent()
observeKeyPath: (keyPath, options, callback) ->
callback(@get(keyPath))
@onDidChangeKeyPath keyPath, (event) -> callback(event.newValue)
onDidChangeKeyPath: (keyPath, callback) ->
oldValue = @get(keyPath)
@emitter.on 'did-change', =>
newValue = @get(keyPath)
unless _.isEqual(oldValue, newValue)
event = {oldValue, newValue}
oldValue = newValue
callback(event)
isSubKeyPath: (keyPath, subKeyPath) ->
return false unless keyPath? and subKeyPath?
pathSubTokens = splitKeyPath(subKeyPath)
pathTokens = splitKeyPath(keyPath).slice(0, pathSubTokens.length)
_.isEqual(pathTokens, pathSubTokens)
setRawDefault: (keyPath, value) ->
setValueAtKeyPath(@defaultSettings, keyPath, value)
@emitChangeEvent()
setDefaults: (keyPath, defaults) ->
if defaults? and isPlainObject(defaults)
keys = splitKeyPath(keyPath)
@transact =>
for key, childValue of defaults
continue unless defaults.hasOwnProperty(key)
@setDefaults(keys.concat([key]).join('.'), childValue)
else
try
defaults = @makeValueConformToSchema(keyPath, defaults)
@setRawDefault(keyPath, defaults)
catch e
console.warn("'#{keyPath}' could not set the default. Attempted default: #{JSON.stringify(defaults)}; Schema: #{JSON.stringify(@getSchema(keyPath))}")
return
deepClone: (object) ->
if object instanceof Color
object.clone()
else if _.isArray(object)
object.map (value) => @deepClone(value)
else if isPlainObject(object)
_.mapObject object, (key, value) => [key, @deepClone(value)]
else
object
deepDefaults: (target) ->
result = target
i = 0
while ++i < arguments.length
object = arguments[i]
if isPlainObject(result) and isPlainObject(object)
for key in Object.keys(object)
result[key] = @deepDefaults(result[key], object[key])
else
if not result?
result = @deepClone(object)
result
# `schema` will look something like this
#
# ```coffee
# type: 'string'