Class: Doing::Configuration

Inherits:
Object show all
Defined in:
lib/doing/configuration.rb

Overview

Configuration object

Constant Summary collapse

MissingConfigFile =
Class.new(RuntimeError)
DEFAULTS =
{
  'autotag' => {
    'whitelist' => [],
    'synonyms' => {}
  },
  'editors' => {
    'default' => ENV['DOING_EDITOR'] || ENV['GIT_EDITOR'] || ENV['EDITOR'],
    'doing_file' => nil,
    'config' => nil,
    'pager' => nil
  },
  'plugins' => {
    'plugin_path' => File.join(Util.user_home, '.config', 'doing', 'plugins'),
    'command_path' => File.join(Util.user_home, '.config', 'doing', 'commands')
  },
  'disabled_commands' => [],
  'doing_file' => '~/.local/share/doing/what_was_i_doing.md',
  'doing_file_sort' => 'desc',
  'backup_dir' => '~/.local/share/doing/doing_backup',
  'history_size' => 15,
  'current_section' => 'Currently',
  'paginate' => false,
  'never_time' => [],
  'never_finish' => [],
  'date_tags' => ['done', 'defer(?:red)?', 'waiting'],

  'timer_format' => 'text',
  'interval_format' => 'text',

  'order' => 'asc',

  'shortdate_format' => {
    'today' => '%_I:%M%P',
    'this_week' => '%a %_I:%M%P',
    'this_month' => '%m/%d %_I:%M%P',
    'older' => '%m/%d/%y %_I:%M%P'
  },

  'templates' => {
    'default' => {
      'date_format' => '%Y-%m-%d %H:%M',
      'template' => '%reset%cyan%shortdate %boldwhite%80║ title %boldmagenta[%boldwhite%-10section%boldmagenta]%reset %yellow%interval%boldred%duration%white%80_14┃ note',
      'wrap_width' => 0,
      'order' => 'asc'
    },
    'today' => {
      'date_format' => '%_I:%M%P',
      'template' => '%date: %title %interval%duration%note',
      'wrap_width' => 0,
      'order' => 'asc'
    },
    'last' => {
      'date_format' => '%-I:%M%P on %a',
      'template' => '%title (at %date) %interval%duration%odnote',
      'wrap_width' => 88
    },
    'recent' => {
      'date_format' => '%_I:%M%P',
      'template' => '%reset%cyan%shortdate %boldwhite%80║ title %boldmagenta[%boldwhite%-10section%boldmagenta]%reset  %yellow%interval%boldred%duration%white%80_14┃ note',
      'wrap_width' => 88,
      'count' => 10,
      'order' => 'asc'
    }
  },

  'export_templates' => {},

  'views' => {
    'done' => {
      'date_format' => '%_I:%M%P',
      'template' => '%date | %title (%section)% 18: note',
      'wrap_width' => 0,
      'section' => 'All',
      'count' => 0,
      'order' => 'desc',
      'tags' => 'done complete cancelled',
      'tags_bool' => 'OR'
    },
    'color' => {
      'date_format' => '%F %_I:%M%P',
      'template' => '%boldblack%date %boldgreen| %boldwhite%title%default%note',
      'wrap_width' => 0,
      'section' => 'Currently',
      'count' => 10,
      'order' => 'asc'
    }
  },
  'marker_tag' => 'flagged',
  'marker_color' => 'red',
  'default_tags' => [],
  'tag_sort' => 'name',
  'search' => {
    'matching' => 'pattern', # fuzzy, pattern, exact
    'distance' => 3,
    'case' => 'smart', # sensitive, ignore, smart
    'highlight' => false
  },
  'include_notes' => true,
  'interaction' => {
    'confirm_longer_than' => '5h'
  }
}

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(file = nil, options: {}) ⇒ Configuration

Returns a new instance of Configuration.



121
122
123
124
125
# File 'lib/doing/configuration.rb', line 121

def initialize(file = nil, options: {})
  @config_file = file.nil? ? default_config_file : File.expand_path(file)

  @settings = configure(options)
end

Instance Attribute Details

#config_fileObject



127
128
129
# File 'lib/doing/configuration.rb', line 127

def config_file
  @config_file ||= default_config_file
end

#force_answerObject



12
13
14
# File 'lib/doing/configuration.rb', line 12

def force_answer
  @force_answer ||= false
end

#ignore_local=(value) ⇒ Object (writeonly)

Sets the attribute ignore_local

Parameters:

  • value

    the value to set the attribute ignore_local to.



10
11
12
# File 'lib/doing/configuration.rb', line 10

def ignore_local=(value)
  @ignore_local = value
end

#settingsObject (readonly)

Returns the value of attribute settings.



8
9
10
# File 'lib/doing/configuration.rb', line 8

def settings
  @settings
end

Instance Method Details

#additional_configsObject



160
161
162
# File 'lib/doing/configuration.rb', line 160

def additional_configs
  @additional_configs ||= find_local_config
end

#choose_config(create: false, local: false) ⇒ String

Present a menu if there are multiple configs found

Returns:



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
# File 'lib/doing/configuration.rb', line 169

def choose_config(create: false, local: false)
  if local && create
    res = File.expand_path('.doingrc')
    FileUtils.touch(res)
    return res
  end

  return @config_file if @force_answer

  if @additional_configs&.count&.positive? || create
    choices = [@config_file].concat(@additional_configs)
    choices.push('Create a new .doingrc in the current directory') if create && !File.exist?('.doingrc')
    res = Doing::Prompt.choose_from(choices.uniq.sort.reverse,
                                    sorted: false,
                                    prompt: 'Local configs found, select which to update > ')

    raise UserCancelled, 'Cancelled' unless res

    if res =~ /^Create a new/
      res = File.expand_path('.doingrc')
      FileUtils.touch(res)
    end

    res.strip || @config_file
  else
    @config_file
  end
end

#config_dirObject



131
132
133
# File 'lib/doing/configuration.rb', line 131

def config_dir
  @config_dir ||= File.join(Util.user_home, '.config', 'doing')
end

#configure(opt = {}) ⇒ Object

Read user configuration and merge with defaults

Parameters:

  • opt (Hash) (defaults to: {})

    Additional Options



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
# File 'lib/doing/configuration.rb', line 338

def configure(opt = {})
  update_deprecated_config if config_file == default_config_file

  @ignore_local = opt[:ignore_local] if opt[:ignore_local]

  config = read_config.clone

  plugin_config = Util.deep_merge_hashes(DEFAULTS['plugins'], config['plugins'] || {})

  load_plugins(plugin_config['plugin_path'])

  Plugins.plugins.each do |_type, plugins|
    plugins.each do |title, plugin|
      plugin_config[title] = plugin[:config] if plugin[:config].good?
      config['export_templates'][title] ||= nil if plugin[:templates] && !plugin[:templates].empty?
    end
  end

  config = Util.deep_merge_hashes({
                                    'plugins' => plugin_config
                                  }, config)

  config = find_deprecations(config)

  if !File.exist?(config_file) || opt[:rewrite]
    Util.write_to_file(config_file, YAML.dump(config), backup: true)
    Doing.logger.warn('Config:', "Config file written to #{config_file}")
  end

  Hooks.trigger :post_config, self

  config = local_config.deep_merge(config, { extend_existing_arrays: true, sort_merged_arrays: true }) unless @ignore_local
  # config = Util.deep_merge_hashes(config, local_config) unless @ignore_local

  Hooks.trigger :post_local_config, self

  config
end

#default_config_fileObject



146
147
148
149
150
151
152
153
154
155
156
157
158
# File 'lib/doing/configuration.rb', line 146

def default_config_file
  if File.exist?(config_dir) && !File.directory?(config_dir)
    raise DoingRuntimeError, "#{config_dir} exists but is not a directory"

  end

  unless File.exist?(config_dir)
    FileUtils.mkdir_p(config_dir)
    Doing.logger.log_now(:warn, "Config directory created at #{config_dir}")
  end

  File.join(config_dir, 'config.yml')
end

#exact_match?Boolean

Check if configuration enforces exact string matching

Returns:

  • (Boolean)

    exact matching enabled



140
141
142
143
144
# File 'lib/doing/configuration.rb', line 140

def exact_match?
  search_settings = @settings['search']
  matching = search_settings.fetch('matching', 'pattern').normalize_matching
  matching == :exact
end

#fetch(*path, default) ⇒ Object



198
199
200
# File 'lib/doing/configuration.rb', line 198

def fetch(*path, default)
  @settings.dig(*path) || default
end

#from(user_config) ⇒ Hash

It takes the input, fills in the defaults where values do not exist.

Parameters:

  • user_config

    a Hash or Configuration of overrides.

Returns:

  • (Hash)

    a Configuration filled with defaults.



296
297
298
299
# File 'lib/doing/configuration.rb', line 296

def from(user_config)
  # Util.deep_merge_hashes(DEFAULTS, Configuration[user_config].stringify_keys)
  Configuration[user_config].stringify_keys.deep_merge(DEFAULTS, { extend_existing_arrays: true, sort_merged_arrays: true })
end

#resolve_key_path(keypath, create: false, distance: 2, exact: false) ⇒ Array

Resolve a fuzzy-matched key path

Parameters:

  • keypath (String)

    A dot-separated key path, e.g. "plugins.plugin_path". Will also work with "plug.path" (fuzzy matched, first match wins)

Returns:

  • (Array)

    ordered array of resolved keys



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
# File 'lib/doing/configuration.rb', line 212

def resolve_key_path(keypath, create: false, distance: 2, exact: false)
  cfg = @settings
  real_path = []
  unless keypath =~ /^[.*]?$/
    paths = keypath.split(/[:.]/)
    element_count = paths.count
    while paths.length.positive? && !cfg.nil?
      path = paths.shift
      new_cfg = nil

      if cfg.is_a?(Hash)
        matches = if exact
                    cfg.select { |key, _| key == path }
                  else
                    cfg.select { |key, _| key =~ path.to_rx(distance: distance) }
                  end
        if matches.count.positive?
          shortest = matches.keys.group_by(&:length).min.last[0]
          real_path << shortest
          new_cfg = matches[shortest]
        end
      else
        new_cfg = cfg
      end

      if new_cfg.nil?
        return real_path if real_path[-1] == path && real_path.count == element_count

        if distance < 5 && !create
          return resolve_key_path(keypath, create: false, distance: distance + 1)
        else
          return nil unless create
        end

        resolved = real_path.count.positive? ? "Resolved #{real_path.join('.')}, but " : ''
        Doing.logger.log_now(:warn, "#{resolved}#{path} is unknown")
        new_path = [*real_path, path, *paths].compact.join('.')
        Doing.logger.log_now(:warn, "Continuing will create the path #{new_path}")
        res = Prompt.yn('Key path not found, create it?', default_response: true)
        raise InvalidArgument, 'Invalid key path' unless res

        real_path.push(path).concat(paths).compact!
        Doing.logger.debug('Config:', "translated key path #{keypath} to #{real_path.join('.')}") unless keypath == real_path.join('.')
        return real_path
      end
      cfg = new_cfg
    end
  end
  Doing.logger.debug('Config:', "translated key path #{keypath} to #{real_path.join('.')}") unless keypath == real_path.join('.')
  real_path
end

#save_view(view, title) ⇒ Object

Save a set of options to the views configuration

Parameters:

  • view (Hash)

    view options

  • title (String)

    view title



383
384
385
386
387
388
389
390
391
392
393
394
395
396
# File 'lib/doing/configuration.rb', line 383

def save_view(view, title)
  title.downcase!
  default_template = Doing.setting('templates.default')
  user_config = Util.safe_load_file(config_file)
  user_config['views'] = {} unless user_config.key?('views')

  view.delete_if { |k, v| v == default_template[k] }

  user_config['views'][title] = view
  Util.write_to_file(config_file, YAML.dump(user_config), backup: true)
  Doing.logger.warn('Config:', %(View "#{title}" saved to #{config_file}))
  Doing.logger.info('Config:', %(to use, run `doing view #{title}`))
  Hooks.trigger :post_config, self
end

#update_deprecated_configObject

Method for transitioning from ~/.doingrc to ~/.config/doing/config.yml



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
# File 'lib/doing/configuration.rb', line 304

def update_deprecated_config
  # return # Until further notice
  return if File.exist?(default_config_file)

  old_file = File.join(Util.user_home, '.doingrc')
  return unless File.exist?(old_file)

  Doing.logger.log_now(:warn, 'Deprecated:', "main config file location has changed to #{config_file}")
  res = Prompt.yn("Move #{old_file} to new location, preserving settings?", default_response: true)

  return unless res

  if File.exist?(default_config_file)
    res = Prompt.yn("#{default_config_file} already exists, overwrite it?", default_response: false)

    unless res
      @config_file = old_file
      return
    end
  end

  FileUtils.mv old_file, default_config_file, force: true
  Doing.logger.log_now(:warn, 'Config:', "Config file moved to #{default_config_file}")
  Doing.logger.log_now(:warn, 'Config:', %(If ~/.doingrc exists in the future,
                       it will be considered a local config and its values will override the
                       default configuration.))
  Process.exit 0
end

#value_for_key(keypath = '') ⇒ Hash

Get the value for a fuzzy-matched key path

Parameters:

  • keypath (String) (defaults to: '')

    A dot-separated key path, e.g. "plugins.plugin_path". Will also work with "plug.path" (fuzzy matched, first match wins)

Returns:

  • (Hash)

    Config value



274
275
276
277
278
279
280
281
282
283
284
285
# File 'lib/doing/configuration.rb', line 274

def value_for_key(keypath = '')
  cfg = @settings
  real_path = ['config']
  unless keypath =~ /^[.*]?$/
    real_path = resolve_key_path(keypath, create: false)
    return nil unless real_path&.count&.positive?

    cfg = cfg.dig(*real_path)
  end

  cfg.nil? ? nil : { real_path[-1] => cfg }
end