Class: Doing::WWID

Inherits:
Object show all
Includes:
Color
Defined in:
lib/doing/wwid/wwid.rb,
lib/doing/wwid/tags.rb,
lib/doing/wwid/guess.rb,
lib/doing/wwid/editor.rb,
lib/doing/wwid/filter.rb,
lib/doing/wwid/modify.rb,
lib/doing/wwid/timers.rb,
lib/doing/wwid/display.rb,
lib/doing/wwid/wwidutil.rb,
lib/doing/wwid/filetools.rb,
lib/doing/wwid/interactive.rb

Overview

Main "What Was I Doing" methods

Constant Summary

Constants included from Color

Color::ATTRIBUTES, Color::ATTRIBUTE_NAMES, Color::COLORED_REGEXP, Color::ESCAPE_REGEX

Instance Attribute Summary collapse

Instance Method Summary collapse

Methods included from Color

#attributes, coloring?, #rgb, #support?, template, #uncolor

Constructor Details

#initializeWWID

Initializes the object.



55
56
57
58
59
60
# File 'lib/doing/wwid/wwid.rb', line 55

def initialize
  @timers = {}
  @recorded_items = []
  @content = Items.new
  Doing.auto_tag = true
end

Instance Attribute Details

#additional_configsObject (readonly)

Local configuration files detected at initialization



27
28
29
# File 'lib/doing/wwid/wwid.rb', line 27

def additional_configs
  @additional_configs
end

#configObject

For backwards compatibility where @wwid.config was accessed instead of Doing.config.settings



42
43
44
# File 'lib/doing/wwid/wwid.rb', line 42

def config
  @config
end

#config_fileObject

The location of the main config file



45
46
47
# File 'lib/doing/wwid/wwid.rb', line 45

def config_file
  @config_file
end

#contentObject (readonly)

The Items object into which all entries are read



36
37
38
# File 'lib/doing/wwid/wwid.rb', line 36

def content
  @content
end

#current_sectionObject (readonly)

The Currently section defined in configuration



30
31
32
# File 'lib/doing/wwid/wwid.rb', line 30

def current_section
  @current_section
end

#default_optionObject

[Boolean] the default option to provide in Y/N dialogs



48
49
50
# File 'lib/doing/wwid/wwid.rb', line 48

def default_option
  @default_option
end

#doing_fileObject (readonly)

The location of the Doing file defined in configuration



33
34
35
# File 'lib/doing/wwid/wwid.rb', line 33

def doing_file
  @doing_file
end

#initial_contentObject (readonly)

A frozen copy of the content object before any modification



39
40
41
# File 'lib/doing/wwid/wwid.rb', line 39

def initial_content
  @initial_content
end

Instance Method Details

#act_on(items, opt) ⇒ Object

Perform actions on a set of entries. If no valid action is included in the opt hash and the terminal is a TTY, a menu will be presented

Parameters:

  • items (Array)

    Array of Items to affect

  • opt (Hash)

    Options and actions to perform

Options Hash (opt):

  • :editor (Boolean)
  • :delete (Boolean)
  • :tag (String)
  • :flag (Boolean)
  • :finish (Boolean)
  • :cancel (Boolean)
  • :archive (Boolean)
  • :output (String)
  • :save_to (String)
  • :again (Boolean)
  • :resume (Boolean)


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
# File 'lib/doing/wwid/interactive.rb', line 65

def act_on(items, opt)
  opt ||= {}
  actions = %i[editor delete tag flag finish cancel archive output save_to again resume]
  has_action = false
  single = items.count == 1

  actions.each do |a|
    if opt[a]
      has_action = true
      break
    end
  end

  unless has_action
    actions = [
      'add tag',
      'remove tag',
      'autotag',
      'cancel',
      'delete',
      'finish',
      'flag',
      'archive',
      'move',
      'edit',
      'output formatted'
    ]

    actions.concat(['resume/repeat', 'begin/reset']) if items.count == 1

    choice = Prompt.choose_from(actions.map(&:titlecase),
                                prompt: 'What do you want to do with the selected items? > ',
                                multiple: true,
                                sorted: false,
                                fzf_args: ["--height=#{actions.count + 3}", '--tac', '--no-sort', '--info=hidden'])
    return unless choice

    to_do = choice.strip.split(/\n/).map(&:downcase)

    to_do.each do |action|
      action = 'resume' if action =~ /^resume/i
      action = 'reset' if action =~ /^begin/i

      case action
      when /(resume|reset|autotag|archive|delete|finish|cancel|flag)/
        opt[action.to_sym] = true
      when /edit/
        opt[:editor] = true
      when /(add|remove) tag/
        type = action =~ /^add/ ? 'add' : 'remove'
        raise InvalidArgument, "'add tag' and 'remove tag' can not be used together" if opt[:tag]

        tags = type == 'add' ? all_tags(@content) : all_tags(items)

        add_msg = type == 'add' ? ', include values with tag(value)' : ''
        puts "#{yellow}Separate multiple tags with spaces, hit tab to complete known tags#{add_msg}"
        puts "#{boldgreen}Available tags: #{boldwhite}#{tags.sort.map(&:add_at).join(', ')}" if type == 'remove'
        tag = Prompt.read_line(prompt: "Tags to #{type}", completions: tags)

        # print "#{yellow("Tag to #{type}: ")}#{reset}"
        # tag = $stdin.gets
        next if tag =~ /^ *$/

        opt[:tag] = tag.strip.sub(/^@/, '')
        opt[:remove] = true if type == 'remove'
      when /output formatted/
        plugins = Plugins.available_plugins(type: :export).sort
        output_format = Prompt.choose_from(plugins,
                                           prompt: 'Which output format? > ',
                                           fzf_args: [
                                             "--height=#{plugins.count + 3}",
                                             '--tac',
                                             '--no-sort',
                                             '--info=hidden'
                                           ])
        next if output_format =~ /^ *$/

        raise UserCancelled unless output_format

        opt[:output] = output_format.strip
        res = opt[:force] ? false : Prompt.yn('Save to file?', default_response: 'n')
        if res
          # print "#{yellow('File path/name: ')}#{reset}"
          # filename = $stdin.gets.strip
          filename = Prompt.read_line(prompt: 'File path/name')
          next if filename.empty?

          opt[:save_to] = filename
        end
      when /move/
        section = choose_section.strip
        opt[:move] = section.strip unless section =~ /^ *$/
      end
    end
  end

  if opt[:resume] || opt[:reset]
    raise InvalidArgument, 'resume and restart can only be used on a single entry' if items.count > 1

    item = items[0]
    if opt[:resume] && !opt[:reset]
      repeat_item(item, { editor: opt[:editor] }) # hooked
    elsif opt[:reset]
      res = Prompt.enter_text('Start date (blank for current time)', default_response: '')
      date = if res =~ /^ *$/
               Time.now
             else
               res.chronify(guess: :begin)
             end

      res = if item.tags?('done', :and) && !opt[:resume]
              opt[:force] ? true : Prompt.yn('Remove @done tag?', default_response: 'y')
            else
              opt[:resume]
            end
      old_item = item.clone
      new_entry = reset_item(item, date: date, resume: res)
      @content.update_item(item, new_entry)
      Hooks.trigger :post_entry_updated, self, new_entry, old_item
    end
    write(@doing_file)

    return
  end

  if opt[:delete]
    delete_items(items, force: opt[:force]) # hooked
    write(@doing_file)

    return
  end

  if opt[:flag]
    tag = Doing.setting('marker_tag', 'flagged')
    items.map! do |i|
      old_item = i.clone
      i.tag(tag, date: false, remove: opt[:remove], single: single)
      Hooks.trigger :post_entry_updated, self, i, old_item
    end
  end

  if opt[:finish] || opt[:cancel]
    tag = 'done'
    items.map! do |i|
      next unless i.should_finish?

      old_item = i.clone
      should_date = !opt[:cancel] && i.should_time?
      i.tag(tag, date: should_date, remove: opt[:remove], single: single)
      Hooks.trigger :post_entry_updated, self, i, old_item
    end
  end

  if opt[:autotag]
    items.map! do |i|
      new_title = autotag(i.title)
      if new_title == i.title
        logger.count(:skipped, level: :debug, message: '%count unchaged %items')
        # logger.debug('Autotag:', 'No changes')
      else
        logger.count(:added_tags)
        logger.write(items.count == 1 ? :info : :debug, 'Tagged:', new_title)
        old_item = i.clone
        i.title = new_title
        Hooks.trigger :post_entry_updated, self, i, old_item
      end
    end
  end

  if opt[:tag]
    tag = opt[:tag]
    items.map! do |i|
      old_item = i.clone
      i.tag(tag, date: false, remove: opt[:remove], single: single)
      i.expand_date_tags(Doing.setting('date_tags'))
      Hooks.trigger :post_entry_updated, self, i, old_item
    end
  end

  if opt[:archive] || opt[:move]
    section = opt[:archive] ? 'Archive' : guess_section(opt[:move])
    items.map! do |i|
      old_item = i.clone
      i.move_to(section, label: true)
      Hooks.trigger :post_entry_updated, self, i, old_item
    end
  end

  write(@doing_file)

  if opt[:editor]
    sleep 2 # This seems to be necessary between running fzf
            # and forking the editor, otherwise vim gets all
            # screwy and I can't figure out why
    edit_items(items) # hooked

    write(@doing_file)
  end

  return unless opt[:output]

  items.each { |i| i.title = "#{i.title} @section(#{i.section})" }

  export_items = Items.new
  export_items.concat(items)
  export_items.add_section(Section.new('Export'), log: false)
  options = { section: 'All' }

  if opt[:output] =~ /doing/
    options[:output] = 'template'
    options[:template] = '- %date | %title%note'
  else
    options[:output] = opt[:output]
    options[:template] = opt[:template] || nil
  end

  output = list_section(options, items: export_items) # hooked

  if opt[:save_to]
    file = File.expand_path(opt[:save_to])
    if File.exist?(file)
      # Create a backup copy for the undo command
      FileUtils.cp(file, "#{file}~")
    end

    File.open(file, 'w+') do |f|
      f.puts output
    end

    logger.warn('File written:', file)
  else
    Doing::Pager.page output
  end
end

#add_item(title, section = nil, opt) ⇒ Object

Adds an entry

Parameters:

  • title (String)

    The entry title

  • section (String) (defaults to: nil)

    The section to add to

  • opt (Hash)

    Additional Options

Options Hash (opt):

  • :date (Date)

    item start date

  • :note (Note)

    item note (will be converted if value is String)

  • :back (Date)

    backdate

  • :timed (Boolean)

    new item is timed entry, marks previous entry as @done

  • :done (Date)

    If set, adds a @done tag to new entry



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
# File 'lib/doing/wwid/modify.rb', line 18

def add_item(title, section = nil, opt)
  opt ||= {}
  section ||= Doing.setting('current_section')
  @content.add_section(section, log: false)
  opt[:back] ||= opt[:date] ? opt[:date] : Time.now
  opt[:date] ||= Time.now
  note = Note.new
  opt[:timed] ||= false

  note.add(opt[:note]) if opt[:note]

  title = [title.strip.cap_first]
  title = title.join(' ')

  if Doing.auto_tag
    title = autotag(title)
    title.add_tags!(Doing.setting('default_tags')) if Doing.setting('default_tags').good?
  end

  title.compress!
  entry = Item.new(opt[:back], title.strip, section)

  if opt[:done] && entry.should_finish?
    if entry.should_time?
      finish = opt[:done].is_a?(String) ? opt[:done].chronify(guess: :end, context: :today) : opt[:done]
      entry.tag('done', value: finish)
    else
      entry.tag('done')
    end
  end

  entry.note = note

  if opt[:timed]
    last_item = last_entry({ section: section })
    if last_item.tags?(['done'], :not)
      finish_date = verify_duration(last_item.date, opt[:back], title: last_item.title)
      last_item.tag('done', value: finish_date.strftime('%F %R'))
    end
  end

  Hooks.trigger :pre_entry_add, self, entry

  @content.push(entry)
  # logger.count(:added, level: :debug)
  logger.info('New entry:', %(added "#{entry.date.relative_date}: #{entry.title}" to #{section}))

  Hooks.trigger :post_entry_added, self, entry
  entry
end

#add_with_editor(**options) ⇒ Object

Raises:

  • (MissingEditor)


103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
# File 'lib/doing/wwid/editor.rb', line 103

def add_with_editor(**options)
  raise MissingEditor, 'No EDITOR variable defined in environment' if Util.default_editor.nil?

  input = options[:date].strftime('%F %R | ')
  input += options[:title]
  input += "\n#{options[:note]}" if options[:note]
  input = fork_editor(input).strip

  d, title, note = format_input(input)
  raise EmptyInput, 'No content' if title.empty?

  if options[:ask]
    ask_note = Doing::Prompt.read_lines(prompt: 'Add a note')
    note.add(ask_note) unless ask_note.empty?
  end

  date = d.nil? ? options[:date] : d
  finish = options[:finish_last] || false
  add_item(title.cap_first, options[:section], { note: note, back: date, timed: finish })
  write(@doing_file)
end

#all_tags(items, opt: {}, counts: false) ⇒ Hash, Array

List all tags that exist on given items

Parameters:

  • items (Array)

    array of Item

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

    additional options

  • counts (Boolean) (defaults to: false)

    Include tag counts in results

Returns:

  • (Hash)

    if counts is true, returns a hash with { tag: count }.

  • (Array)

    If counts is false, returns a simple array of tags.



18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
# File 'lib/doing/wwid/tags.rb', line 18

def all_tags(items, opt: {}, counts: false)
  if counts
    all_tags = {}
    items.each do |item|
      item.tags.each do |tag|
        if all_tags.key?(tag.downcase)
          all_tags[tag.downcase] += 1
        else
          all_tags[tag.downcase] = 1
        end
      end
    end

    all_tags.sort_by { |_, count| count }
  else
    all_tags = []
    items.each { |item| all_tags.concat(item.tags.map(&:downcase)).uniq! }
    all_tags.sort
  end
end

#archive(section = Doing.setting('current_section'), options) ⇒ Object

Move entries from a section to Archive or other specified section

Parameters:

  • section (String) (defaults to: Doing.setting('current_section'))

    The source section

  • options (Hash)

    Options



417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
# File 'lib/doing/wwid/modify.rb', line 417

def archive(section = Doing.setting('current_section'), options)
  options ||= {}
  count       = options[:keep] || 0
  destination = options[:destination] || 'Archive'
  tags        = options[:tags] || []
  bool        = options[:bool] || :and

  section = choose_section if section.nil? || section =~ /choose/i
  archive_all = section =~ /^all$/i # && !(tags.nil? || tags.empty?)
  section = guess_section(section) unless archive_all

  @content.add_section(destination, log: true)
  # add_section(Section.new('Archive')) if destination =~ /^archive$/i && [email protected]?('Archive')

  destination = guess_section(destination)

  if @content.section?(destination) && (@content.section?(section) || archive_all)
    do_archive(section, destination, { count: count, tags: tags, bool: bool, search: options[:search], label: options[:label], before: options[:before], after: options[:after], from: options[:from] })
    write(doing_file)
  else
    raise InvalidArgument, 'Either source or destination does not exist'
  end
end

#autotag(string) ⇒ Object

Uses 'autotag' configuration to turn keywords into tags for time tracking. Does not repeat tags in a title, and only converts the first instance of an untagged keyword

Parameters:

  • string (String)

    The text to tag



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
# File 'lib/doing/wwid/modify.rb', line 448

def autotag(string)
  return unless string
  return string unless Doing.auto_tag

  original = string.dup
  text = string.dup

  current_tags = text.scan(/@\w+/).map { |t| t.sub(/^@/, '') }
  tagged = {
    whitelisted: [],
    synonyms: [],
    transformed: [],
    replaced: []
  }

  Doing.setting('autotag.whitelist').each do |tag|
    next if text =~ /@#{tag}\b/i

    text.sub!(/(?<= |\A)(#{tag.strip})(?= |\Z)/i) do |m|
      m.downcase! unless tag =~ /[A-Z]/
      tagged[:whitelisted].push(m)
      "@#{m}"
    end
  end

  Doing.setting('autotag.synonyms').each do |tag, v|
    v.each do |word|
      word = word.wildcard_to_rx
      next unless text =~ /\b#{word}\b/i

      unless current_tags.include?(tag) || tagged[:whitelisted].include?(tag)
        tagged[:synonyms].push(tag)
        tagged[:synonyms] = tagged[:synonyms].uniq
      end
    end
  end

  if Doing.setting('autotag.transform')
    Doing.setting('autotag.transform').each do |tag|
      next unless tag =~ /\S+:\S+/

      if tag =~ /::/
        rx, r = tag.split(/::/)
      else
        rx, r = tag.split(/:/)
      end

      flag_rx = %r{/([r]+)$}
      if r =~ flag_rx
        flags = r.match(flag_rx)[1].split(//)
        r.sub!(flag_rx, '')
      end
      r.gsub!(/\$/, '\\')
      rx.sub!(/^@?/, '@')
      regex = Regexp.new("(?<= |\\A)#{rx}(?= |\\Z)")

      text.sub!(regex) do
        m = Regexp.last_match
        new_tag = r

        m.to_a.slice(1, m.length - 1).each_with_index do |v, idx|
          next if v.nil?

          new_tag.gsub!("\\#{idx + 1}", v)
        end
        # Replace original tag if /r
        if flags&.include?('r')
          tagged[:replaced].concat(new_tag.split(/ /).map { |t| t.sub(/^@/, '') })
          new_tag.split(/ /).map { |t| t.sub(/^@?/, '@') }.join(' ')
        else
          tagged[:transformed].concat(new_tag.split(/ /).map { |t| t.sub(/^@/, '') })
          tagged[:transformed] = tagged[:transformed].uniq
          m[0]
        end
      end
    end
  end

  logger.debug('Autotag:', "whitelisted tags: #{tagged[:whitelisted].log_tags}") unless tagged[:whitelisted].empty?
  logger.debug('Autotag:', "synonyms: #{tagged[:synonyms].log_tags}") unless tagged[:synonyms].empty?
  logger.debug('Autotag:', "transforms: #{tagged[:transformed].log_tags}") unless tagged[:transformed].empty?
  logger.debug('Autotag:', "transform replaced: #{tagged[:replaced].log_tags}") unless tagged[:replaced].empty?

  tail_tags = tagged[:synonyms].concat(tagged[:transformed])
  tail_tags.sort!
  tail_tags.uniq!

  text.add_tags!(tail_tags) unless tail_tags.empty?

  if text == original
    logger.debug('Autotag:', "no change to \"#{text.strip}\"")
  else
    new_tags = tagged[:whitelisted].concat(tail_tags).concat(tagged[:replaced])
    logger.debug('Autotag:', "added #{new_tags.log_tags} to \"#{text.strip}\"")
    logger.count(:autotag, level: :info, count: 1, message: 'autotag updated %count %items')
  end

  text.dedup_tags
end

#changesHash

Return a hash of changes between initial file read and current Items object

Returns:

  • (Hash)

    Hash containing added and removed keys with arrays of Item



97
98
99
# File 'lib/doing/wwid/wwidutil.rb', line 97

def changes
  @content.diff(@initial_content)
end

#choose_section(include_all: false) ⇒ String

Generate a menu of sections and allow user selection

Returns:

  • (String)

    The selected section name



305
306
307
308
309
310
# File 'lib/doing/wwid/interactive.rb', line 305

def choose_section(include_all: false)
  options = @content.section_titles.sort
  options.unshift('All') if include_all
  choice = Prompt.choose_from(options, prompt: 'Choose a section > ', fzf_args: ['--height=60%'])
  choice ? choice.strip : choice
end

#choose_section_tagString

Generate a menu of sections and tags and allow user selection

Returns:

  • (String)

    The selected section or tag name



334
335
336
337
338
339
# File 'lib/doing/wwid/interactive.rb', line 334

def 
  options = @content.section_titles.sort
  options.concat(@content.all_tags.sort.map { |t| "@#{t}" })
  choice = Prompt.choose_from(options, prompt: 'Choose a section or tag > ', fzf_args: ['--height=60%'])
  choice ? choice.strip : choice
end

#choose_tag(section = 'All', items: nil, include_all: false) ⇒ String

Generate a menu of tags and allow user selection

Returns:

  • (String)

    The selected tag name



317
318
319
320
321
322
323
324
325
326
327
# File 'lib/doing/wwid/interactive.rb', line 317

def choose_tag(section = 'All', items: nil, include_all: false)
  items ||= @content.in_section(section)
  tags = all_tags(items, counts: true).map { |t, c| "@#{t} (#{c})" }
  tags.unshift('No tag filter') if include_all
  choice = Prompt.choose_from(tags,
                              sorted: false,
                              multiple: true,
                              prompt: 'Choose tag(s) > ',
                              fzf_args: ['--height=60%'])
  choice ? choice.split(/\n/).map { |t| t.strip.sub(/ \(.*?\)$/, '') }.join(' ') : choice
end

#choose_viewString

Generate a menu of views and allow user selection

Returns:

  • (String)

    The selected view name



346
347
348
349
# File 'lib/doing/wwid/interactive.rb', line 346

def choose_view
  choice = Prompt.choose_from(views.sort, prompt: 'Choose a view > ', fzf_args: ['--height=60%'])
  choice ? choice.strip : choice
end

#configure(filename = nil) ⇒ Object

Load configuration files and updated the @settings attribute with a Doing::Configuration object

Parameters:

  • filename (String) (defaults to: nil)

    (optional) path to alternative config file



56
57
58
59
60
61
62
63
64
65
66
67
68
# File 'lib/doing/wwid/wwidutil.rb', line 56

def configure(filename = nil)
  logger.benchmark(:configure, :start)

  if filename
    Doing.config_with(filename, { ignore_local: true })
  elsif ENV['DOING_CONFIG']
    Doing.config_with(ENV['DOING_CONFIG'], { ignore_local: true })
  end

  logger.benchmark(:configure, :finish)

  Doing.set('backup_dir', ENV['DOING_BACKUP_DIR']) if ENV['DOING_BACKUP_DIR']
end

#create(filename = nil) ⇒ Object

Create a new doing file



75
76
77
78
79
80
81
82
83
84
# File 'lib/doing/wwid/filetools.rb', line 75

def create(filename = nil)
  filename = @doing_file if filename.nil?
  return if File.exist?(filename) && File.stat(filename).size.positive?

  FileUtils.mkdir_p(File.dirname(filename)) unless File.directory?(File.dirname(filename))

  File.open(filename, 'w+') do |f|
    f.puts "#{Doing.setting('current_section')}:"
  end
end

#dedup(items, no_overlap: false) ⇒ Object

Remove items from an array that already exist in :content based on start and end times

Parameters:

  • items (Array)

    The items to deduplicate

  • no_overlap (Boolean) (defaults to: false)

    Remove items with overlapping time spans



14
15
16
17
18
19
20
21
22
23
24
25
# File 'lib/doing/wwid/wwidutil.rb', line 14

def dedup(items, no_overlap: false)
  items.delete_if do |item|
    duped = false
    @content.each do |comp|
      duped = no_overlap ? item.overlapping_time?(comp) : item.same_time?(comp)
      break if duped
    end
    logger.count(:skipped, level: :debug, message: '%count overlapping %items') if duped
    # logger.log_now(:debug, 'Skipped:', "overlapping entry: #{item.title}") if duped
    duped
  end
end

#delete_items(items, force: false) ⇒ Object

Delete a set of items from the main index

Parameters:

  • items (Array)

    The items to delete

  • force (Boolean) (defaults to: false)

    Force deletion without confirmation



399
400
401
402
403
404
405
406
407
408
# File 'lib/doing/wwid/modify.rb', line 399

def delete_items(items, force: false)
  items.slice(0, 5).each { |i| puts i.to_pretty } unless force
  puts softpurple("+ #{items.size - 5} additional #{'item'.to_p(items.size - 5)}") if items.size > 5 && !force

  res = force ? true : Prompt.yn("Delete #{items.size} #{'item'.to_p(items.size)}?", default_response: 'y')
  return unless res

  items.each { |i| Hooks.trigger :post_entry_removed, self, @content.delete_item(i, single: items.count == 1) }
  # write(@doing_file)
end

#edit_items(items) ⇒ Object



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
# File 'lib/doing/wwid/editor.rb', line 125

def edit_items(items)
  items.sort_by! { |i| i.date }
  editable_items = []

  items.each do |i|
    editable = "#{i.date.strftime('%F %R')} | #{i.title}"
    old_note = i.note ? i.note.strip_lines.join("\n") : nil
    editable += "\n#{old_note}" unless old_note.nil?
    editable_items << editable
  end
  divider = "-----------"
  notice =<<~EONOTICE

  # - You may delete entries, but leave all divider lines (---) in place.
  # - Start and @done dates replaced with a time string (yesterday 3pm) will
  #   be parsed automatically. Do not delete the pipe (|) between start date
  #   and entry title.
  EONOTICE
  input =  "#{editable_items.map(&:strip).join("\n#{divider}\n")}\n"

  new_items = fork_editor(input, message: notice).split(/^#{divider}/).map(&:strip)

  new_items.each_with_index do |new_item, i|
    input_lines = new_item.split(/[\n\r]+/).delete_if(&:ignore?)
    first_line = input_lines[0]&.strip

    if first_line.nil? || first_line =~ /^#{divider.strip}$/ || first_line.strip.empty?
      deleted = @content.delete_item(items[i], single: new_items.count == 1)
      Hooks.trigger :post_entry_removed, self, deleted
      Doing.logger.info('Deleted:', deleted.title)
    else
      date, title, note = format_input(new_item)

      note.map!(&:strip)
      note.delete_if(&:ignore?)
      item = items[i]
      old_item = item.clone
      item.date = date || items[i].date
      item.title = title
      item.note = note
      if (item.equal?(old_item))
        Doing.logger.count(:skipped, level: :debug)
      else
        Doing.logger.count(:updated)
        Hooks.trigger :post_entry_updated, self, item, old_item
      end
    end
  end
end

#edit_last(section: 'All', options: {}) ⇒ Object

Edit the last entry

Parameters:

  • section (String) (defaults to: 'All')

    The section, default "All"

Raises:

  • (UserCancelled)


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
# File 'lib/doing/wwid/editor.rb', line 180

def edit_last(section: 'All', options: {})
  options[:section] = guess_section(section)

  item = last_entry(options)

  if item.nil?
    logger.debug('Skipped:', 'No entries found')
    return
  end

  old_item = item.clone
  content = ["#{item.date.strftime('%F %R')} | #{item.title.dup}"]
  content << item.note.strip_lines.join("\n") unless item.note.empty?
  new_item = fork_editor(content.join("\n"))
  raise UserCancelled, 'No change' if new_item.strip == content.join("\n").strip

  date, title, note = format_input(new_item)
  date ||= item.date

  if title.nil? || title.empty?
    logger.debug('Skipped:', 'No content provided')
  elsif title == item.title && note.equal?(item.note) && date.equal?(item.date)
    logger.debug('Skipped:', 'No change in content')
  else
    item.date = date unless date.nil?
    item.title = title
    item.note.add(note, replace: true)
    logger.info('Edited:', item.title)
    Hooks.trigger :post_entry_updated, self, item, old_item

    write(@doing_file)
  end
end

#filter_items(items = Items.new, opt: {}) ⇒ Object

Filter items based on search criteria

Parameters:

  • items (Array) (defaults to: Items.new)

    The items to filter (if empty, filters all items)

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

    The filter parameters

Options Hash (opt:):

  • :section (String) — default: 'all'
  • :unfinished (Boolean) — default: false
  • :tag (Array or String) — default: []

    Array or comma-separated string

  • :tag_bool (Symbol) — default: :and

    :and, :or, :not

  • :search (String) — default: ''

    string, optional regex with /string/

  • :date_filter (Array) — default: nil

    [[Time]start, [Time]end]

  • :only_timed (Boolean) — default: false
  • :before (String) — default: nil

    Date/Time string, unparsed

  • :after (String) — default: nil

    Date/Time string, unparsed

  • :today (Boolean) — default: false

    limit to entries from today

  • :yesterday (Boolean) — default: false

    limit to entries from yesterday

  • :count (Number) — default: 0

    max entries to return

  • :age (String) — default: new

    'old' or 'new'

  • :val (Array) — default: nil

    Array of tag value queries



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
# File 'lib/doing/wwid/filter.rb', line 61

def filter_items(items = Items.new, opt: {})
  logger.benchmark(:filter_items, :start)
  time_rx = /^(\d{1,2}+(:\d{1,2}+)?( *(am|pm))?|midnight|noon)$/i

  if items.nil? || items.empty?
    section = opt[:section] ? guess_section(opt[:section]) : 'All'
    items = section =~ /^all$/i ? @content.clone : @content.in_section(section)
  end

  unless opt[:time_filter]
    opt[:time_filter] = [nil, nil]
    if opt[:from] && !opt[:date_filter]
      if opt[:from][0].is_a?(String) && opt[:from][0] =~ time_rx
        opt[:time_filter] = opt[:from]
      elsif opt[:from][0].is_a?(Time)
        opt[:date_filter] = opt[:from]
      end
    end
  end

  if opt[:before].is_a?(String) && opt[:before] =~ time_rx
    opt[:time_filter][1] = opt[:before]
    opt[:before] = nil
  end

  if opt[:after].is_a?(String) && opt[:after] =~ time_rx
    opt[:time_filter][0] = opt[:after]
    opt[:after] = nil
  end

  items.sort_by! { |item| [item.date, item.title.downcase] }.reverse

  filtered_items = items.select { |item| item.keep_item?(opt) }

  count = opt[:count].to_i&.positive? ? opt[:count].to_i : filtered_items.count

  output = Items.new

  if opt[:age] && opt[:age].normalize_age == :oldest
    output.concat(filtered_items.slice(0, count).reverse)
  else
    output.concat(filtered_items.reverse.slice(0, count))
  end

  logger.benchmark(:filter_items, :finish)

  output
end

#fork_editor(input = '', message: :default) ⇒ Object

Create a process for an editor and wait for the file handle to return

Parameters:

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

    Text input for editor

Raises:

  • (MissingEditor)


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
# File 'lib/doing/wwid/editor.rb', line 10

def fork_editor(input = '', message: :default)
  # raise NonInteractive, 'Non-interactive terminal' unless $stdout.isatty || ENV['DOING_EDITOR_TEST']

  raise MissingEditor, 'No EDITOR variable defined in environment' if Util.default_editor.nil?

  tmpfile = Tempfile.new(['doing_temp', '.doing'])

  File.open(tmpfile.path, 'w+') do |f|
    f.puts input
    unless message.nil?
      f.puts message == :default ? '# First line is the entry title, lines after are added as a note' : message
    end
  end

  pid = Process.fork { system("#{Util.editor_with_args} #{tmpfile.path}") }

  trap('INT') do
    begin
      Process.kill(9, pid)
    rescue StandardError
      Errno::ESRCH
    end
    tmpfile.unlink
    tmpfile.close!
    exit 0
  end

  Process.wait(pid)

  begin
    if $?.exitstatus == 0
      input = IO.read(tmpfile.path)
    else
      exit_now! 'Cancelled'
    end
  ensure
    tmpfile.close
    tmpfile.unlink
  end

  input.split(/\n/).delete_if(&:ignore?).join("\n")
end

#format_input(input) ⇒ Array

Takes a multi-line string and formats it as an entry

Parameters:

  • input (String)

    The string to parse

Returns:

  • (Array)

    [[String]title, [Note]note]

Raises:

  • (EmptyInput)


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
# File 'lib/doing/wwid/editor.rb', line 60

def format_input(input)
  raise EmptyInput, 'No content in entry' if input.nil? || input.strip.empty?

  input_lines = input.split(/[\n\r]+/).delete_if(&:ignore?)
  title = input_lines[0]&.strip
  raise EmptyInput, 'No content in first line' if title.nil? || title.strip.empty?

  date = nil
  iso_rx = /\d{4}-\d\d-\d\d \d\d:\d\d/
  date_rx = /^(?:\s*- )?(?<date>.*?) \| (?=\S)/

  raise EmptyInput, 'No content' if title.sub(/^.*?\| */, '').strip.empty?

  title.expand_date_tags(Doing.setting('date_tags'))

  if title =~ date_rx
    m = title.match(date_rx)
    d = m['date']
    date = if d =~ iso_rx
             Time.parse(d)
           else
             d.chronify(guess: :begin)
           end
    title.sub!(date_rx, '').strip!
  end

  note = Note.new
  note.add(input_lines[1..-1]) if input_lines.length > 1
  # If title line ends in a parenthetical, use that as the note
  if note.empty? && title =~ /\s+\(.*?\)$/
    title.sub!(/\s+\((?<note>.*?)\)$/) do
      m = Regexp.last_match
      note.add(m['note'])
      ''
    end
  end

  note.strip_lines!
  note.compress

  [date, title, note]
end

#fuzzy_filter_args(query, case_type) ⇒ Object



27
28
29
30
31
32
33
34
35
36
37
38
# File 'lib/doing/wwid/filter.rb', line 27

def fuzzy_filter_args(query, case_type)
  fzf_args = ['--multi', %(--filter="#{query.sub(/^'?/, "'")}"), '--no-sort', '-d "\|"', '--nth=1']
  fzf_args << case case_type.normalize_case
              when :smart
                query =~ /[A-Z]/ ? '+i' : '-i'
              when :sensitive
                '+i'
              when :ignore
                '-i'
              end
  fzf_args
end

#fuzzy_filter_items(items, query, case_type: :smart) ⇒ Items

Use fzf to filter an Items object with a search query. Faster than #filter_items when all you need is a text search of the title and note

Parameters:

  • items (Items)

    an Items object

  • query (String)

    The search query

  • case_type (Symbol) (defaults to: :smart)

    The case type (:smart, :sensitive, :ignore)

Returns:

  • (Items)

    Filtered Items array



15
16
17
18
19
20
21
22
23
24
25
# File 'lib/doing/wwid/filter.rb', line 15

def fuzzy_filter_items(items, query, case_type: :smart)
  scannable = items.map.with_index { |item, idx| "#{item.title} #{item.note.join(' ')}".gsub(/[|*?!]/, '') + "|#{idx}" }.join("\n")

  res = `echo #{Shellwords.escape(scannable)}|#{Prompt.fzf} #{fuzzy_filter_args(query, case_type).join(' ')}`
  selected = Items.new
  res.split(/\n/).each do |item|
    idx = item.match(/\|(\d+)$/)[1].to_i
    selected.push(items[idx])
  end
  selected
end

#get_diff(filename = nil) ⇒ Object

Get difference between current content and last backup

Parameters:

  • filename (String) (defaults to: nil)

    The file path

Raises:

  • (DoingRuntimeError)


75
76
77
78
79
80
81
82
83
84
85
86
87
88
# File 'lib/doing/wwid/wwidutil.rb', line 75

def get_diff(filename = nil)
  configure if Doing.settings.nil?

  filename ||= Doing.setting('doing_file')
  init_doing_file(filename)
  current_content = @content.clone
  backup_file = Util::Backup.last_backup(filename, count: 1)
  raise DoingRuntimeError, 'No undo history to diff' if backup_file.nil?

  backup = WWID.new
  backup.config = Doing.settings
  backup.init_doing_file(backup_file)
  current_content.diff(backup.content)
end

#get_interval(item, formatted: true, record: true) ⇒ Object

Gets the interval between entry's start date and @done date

Parameters:

  • item (Item)

    The entry

  • formatted (Boolean) (defaults to: true)

    Return human readable time (default seconds)

  • record (Boolean) (defaults to: true)

    Add the interval to the total for each tag

Returns:

  • Interval in seconds, or [d, h, m] array if formatted is true. False if no end date or interval is 0



154
155
156
157
158
159
160
161
162
163
164
# File 'lib/doing/wwid/timers.rb', line 154

def get_interval(item, formatted: true, record: true)
  if item.interval
    seconds = item.interval
    record_tag_times(item, seconds) if record
    return seconds.positive? ? seconds : false unless formatted

    return seconds.positive? ? seconds.time_string(format: :clock) : false
  end

  false
end

#get_view(title, fallback: nil) ⇒ Object

Gets a view from configuration

Parameters:

  • title (String)

    The title of the view to retrieve



103
104
105
# File 'lib/doing/wwid/wwid.rb', line 103

def get_view(title, fallback: nil)
  Doing.setting(['views', title], fallback)
end

#guess_section(frag, guessed: false, suggest: false) ⇒ Object

Attempt to match a string with an existing section

Parameters:

  • frag (String)

    The user-provided string

  • guessed (Boolean) (defaults to: false)

    already guessed and failed



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
# File 'lib/doing/wwid/guess.rb', line 11

def guess_section(frag, guessed: false, suggest: false)
  return 'All' if frag =~ /^all$/i

  frag ||= Doing.setting('current_section')

  return frag.cap_first if @content.section?(frag)

  found = @content.guess_section(frag, distance: 2)

  section = found ? found.title : nil

  return section if suggest

  unless section || guessed
    alt = guess_view(frag, guessed: true, suggest: true)
    if alt
      prompt = Color.template("{bw}Did you mean `{xy}doing {by}view {xy}#{alt}`{bw}?{x}")
      meant_view = Prompt.yn(prompt, default_response: 'n')

      msg = format('%<y>srun with `%<w>sdoing view %<alt>s%<y>s`', w: boldwhite, y: yellow, alt: alt)
      raise Errors::WrongCommand.new(msg, topic: 'Try again:') if meant_view

    end

    res = Prompt.yn("#{boldwhite}Section #{frag.yellow}#{boldwhite} not found, create it", default_response: 'n')

    if res
      @content.add_section(frag.cap_first, log: true)
      write(@doing_file)
      return frag.cap_first
    end

    raise Errors::InvalidSection.new("unknown section #{frag.bold.white}", topic: 'Missing:')
  end
  section ? section.cap_first : guessed
end

#guess_view(frag, guessed: false, suggest: false) ⇒ Object

Attempt to match a string with an existing view

Parameters:

  • frag (String)

    The user-provided string

  • guessed (Boolean) (defaults to: false)

    already guessed



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
# File 'lib/doing/wwid/guess.rb', line 54

def guess_view(frag, guessed: false, suggest: false)
  views.each { |view| return view if frag.downcase == view.downcase }
  view = nil
  re = frag.to_rx(distance: 2, case_type: :ignore)
  views.each do |v|
    next unless v =~ /#{re}/i

    logger.debug('Match:', %(Assuming "#{v}" from "#{frag}"))
    view = v
    break
  end
  unless view || guessed
    alt = guess_section(frag, guessed: true, suggest: true)

    raise Errors::InvalidView.new(%(unknown view #{frag.bold.white}), topic: 'Missing:') unless alt

    prompt = Color.template("{bw}Did you mean `{xy}doing {by}show {xy}#{alt}`{bw}?{x}")
    meant_view = Prompt.yn(prompt, default_response: 'n')

    if meant_view
      msg = format('%<y>srun with `%<w>sdoing show %<alt>s%<y>s`', w: boldwhite, y: yellow, alt: alt)
      raise Errors::WrongCommand.new(msg, topic: 'Try again:')

    end

    raise Errors::InvalidView.new(%(unknown view #{alt.bold.white}), topic: 'Missing:')

  end
  view
end

#import(paths, opt) ⇒ Object

Imports external entries

Parameters:

  • paths (String)

    Path to JSON report file

  • opt (Hash)

    Additional Options



33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
# File 'lib/doing/wwid/wwidutil.rb', line 33

def import(paths, opt)
  opt ||= {}
  Plugins.plugins[:import].each do |_, options|
    next unless opt[:type] =~ /^(#{options[:trigger].normalize_trigger})$/i

    if paths.count.positive?
      paths.each do |path|
        options[:class].import(self, path, options: opt)
      end
    else
      options[:class].import(self, nil, options: opt)
    end
    break
  end
end

#init_doing_file(path = nil) ⇒ Object

Initializes the doing file.

Parameters:

  • path (String) (defaults to: nil)

    Override path to a doing file, optional



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
# File 'lib/doing/wwid/filetools.rb', line 10

def init_doing_file(path = nil)
  @doing_file =  File.expand_path(Doing.setting('doing_file'))

  if path.nil?
    create(@doing_file) unless File.exist?(@doing_file)
    input = IO.read(@doing_file)
    input = input.force_encoding('utf-8') if input.respond_to? :force_encoding
    logger.debug('Read:', "read file #{@doing_file}")
  elsif File.exist?(File.expand_path(path)) && File.file?(File.expand_path(path)) && File.stat(File.expand_path(path)).size.positive?
    @doing_file = File.expand_path(path)
    input = IO.read(File.expand_path(path))
    input = input.force_encoding('utf-8') if input.respond_to? :force_encoding
    logger.debug('Read:', "read file #{File.expand_path(path)}")
  elsif path.length < 256
    @doing_file = File.expand_path(path)
    create(path)
    input = IO.read(File.expand_path(path))
    input = input.force_encoding('utf-8') if input.respond_to? :force_encoding
    logger.debug('Read:', "read file #{File.expand_path(path)}")
  end

  @other_content_top = []
  @other_content_bottom = []

  section = nil
  lines = input.split(/[\n\r]/)

  lines.each do |line|
    next if line =~ /^\s*$/

    if line =~ /^(\S[\S ]+):\s*(@[\w\-_.]+\s*)*$/
      section = Regexp.last_match(1)
      @content.add_section(Section.new(section, original: line), log: false)
    elsif line =~ /^\s*- (\d{4}-\d\d-\d\d \d\d:\d\d) \| (.*?)(?: +<([a-z0-9]{32})>)? *$/
      if section.nil?
        section = 'Uncategorized'
        @content.add_section(Section.new(section, original: 'Uncategorized:'), log: false)
      end

      date = Regexp.last_match(1).strip
      title = Regexp.last_match(2).strip
      id = Regexp.last_match(3) || nil
      item = Item.new(date, title, section, [], id)
      @content.push(item)
    elsif @content.count.zero?
      # if content[section].items.length - 1 == current
      @other_content_top.push(line)
    elsif line =~ /^\S/
      @other_content_bottom.push(line)
    else
      prev_item = @content.last
      prev_item.note = Note.new unless prev_item.note

      prev_item.note.add(line)
      # end
    end
  end

  Hooks.trigger :post_read, self
  @initial_content = @content.clone
end

#interactive(opt) ⇒ Object

Display an interactive menu of entries

Options hash is shared with #filter_items and #act_on

Parameters:

  • opt (Hash)

    Additional options

Raises:

  • (NoResults)


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
# File 'lib/doing/wwid/interactive.rb', line 12

def interactive(opt)
  opt ||= {}
  opt[:section] = opt[:section] ? guess_section(opt[:section]) : 'All'

  search = nil

  if opt[:search]
    search = opt[:search]
    search.sub!(/^'?/, "'") if opt[:exact]
    opt[:search] = search
  end

  # opt[:query] = opt[:search] if opt[:search] && !opt[:query]
  opt[:query] = "!#{opt[:query]}" if opt[:query] && opt[:not]
  opt[:multiple] = true
  opt[:show_if_single] = true
  filter_options = %i[after before case date_filter from fuzzy not search section val].each_with_object({}) {
    |k, hsh| hsh[k] = opt[k]
  }
  items = filter_items(Items.new, opt: filter_options)

  menu_options = %i[search query exact multiple show_if_single menu sort case].each_with_object({}) {
    |k, hsh| hsh[k] = opt[k]
  }

  selection = Prompt.choose_from_items(items, include_section: opt[:section] =~ /^all$/i, **menu_options)

  raise NoResults, 'no items selected' if selection.nil? || selection.empty?

  act_on(selection, opt)
end

#last(times: true, section: nil, options: {}) ⇒ Object

Show the last entry

Parameters:

  • times (Bool) (defaults to: true)

    Show times

  • section (String) (defaults to: nil)

    Section to pull from, default Currently



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
# File 'lib/doing/wwid/display.rb', line 249

def last(times: true, section: nil, options: {})
  section = section.nil? || section =~ /all/i ? 'All' : guess_section(section)
  cfg = Doing.setting(['templates', options[:config_template]]).deep_merge(Doing.setting('templates.default'), { extend_existing_arrays: true, sort_merged_arrays: true }).deep_merge({
    'wrap_width' => Doing.setting('wrap_width', 0),
    'date_format' => Doing.setting('default_date_format'),
    'order' => Doing.setting('order', :asc),
    'tags_color' => Doing.setting('tags_color'),
    'duration' => Doing.setting('duration'),
    'interval_format' => Doing.setting('interval_format')
  }, { extend_existing_arrays: true, sort_merged_arrays: true })
  options[:duration] ||= cfg['duration'] || false
  options[:interval_format] ||= cfg['interval_format'] || 'text'

  opts = {
    case: options[:case],
    config_template: options[:config_template] || 'last',
    count: 1,
    delete: options[:delete],
    duration: options[:duration],
    format: cfg['date_format'],
    interval_format: options[:interval_format],
    not: options[:negate],
    output: options[:output],
    section: section,
    template: options[:template] || cfg['template'],
    times: times,
    val: options[:val],
    wrap_width: cfg['wrap_width']
  }

  if options[:tag]
    opts[:tag_filter] = {
      'tags' => options[:tag],
      'bool' => options[:tag_bool]
    }
  end

  opts[:search] = options[:search] if options[:search]

  list_section(opts)
end

#last_entry(opt) ⇒ Object

Get the last entry

Parameters:

  • opt (Hash)

    Additional Options



315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
# File 'lib/doing/wwid/display.rb', line 315

def last_entry(opt)
  opt ||= {}
  opt[:tag_bool] ||= :and
  opt[:section] ||= Doing.setting('current_section')

  items = filter_items(Items.new, opt: opt)

  logger.debug('Filtered:', "Parameters matched #{items.count} entries")

  if opt[:interactive]
    last_entry = Prompt.choose_from_items(items, include_section: opt[:section] =~ /^all$/i,
      menu: true,
      header: '',
      prompt: 'Select an entry > ',
      multiple: false,
      sort: false,
      show_if_single: true
     )
  else
    last_entry = items.max_by { |item| item.date }
  end

  last_entry
end

#last_note(section = 'All') ⇒ Object

Return the content of the last note for a given section

Parameters:

  • section (String) (defaults to: 'All')

    The section to retrieve from, default All

Raises:

  • (NoEntryError)


297
298
299
300
301
302
303
304
305
306
307
308
# File 'lib/doing/wwid/display.rb', line 297

def last_note(section = 'All')
  section = guess_section(section)

  last_item = last_entry({ section: section })

  raise NoEntryError, 'No entry found' unless last_item

  logger.log_now(:info, 'Edit note:', last_item.title)

  note = last_item.note&.to_s || ''
  "#{last_item.title}\n# EDIT BELOW THIS LINE ------------\n#{note}"
end

#list_date(dates, section, times = nil, output = nil, opt) ⇒ Object

Display entries within a date range

Parameters:

  • dates (Array)

    [start, end]

  • section (String)

    The section

  • times (Bool) (defaults to: nil)

    Show times

  • output (String) (defaults to: nil)

    Output format

  • opt (Hash)

    Additional Options



105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
# File 'lib/doing/wwid/display.rb', line 105

def list_date(dates, section, times = nil, output = nil, opt)
  opt ||= {}
  opt[:totals] ||= false
  opt[:sort_tags] ||= false
  section = guess_section(section)
  # :date_filter expects an array with start and end date
  dates = dates.split_date_range if dates.instance_of?(String)

  opt[:section] = section
  opt[:count] = 0
  opt[:order] = :asc
  opt[:date_filter] = dates
  opt[:times] = times
  opt[:output] = output

  time_rx = /^(\d{1,2}+(:\d{1,2}+)?( *(am|pm))?|midnight|noon)$/
  if opt[:from] && opt[:from][0].is_a?(String) && opt[:from][0] =~ time_rx
    opt[:time_filter] = opt[:from]
  end

  list_section(opt)
end

#list_section(opt, items: Items.new) ⇒ Object

Display contents of a section based on options

Parameters:

  • opt (Hash)

    Additional Options



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
# File 'lib/doing/wwid/display.rb', line 10

def list_section(opt, items: Items.new)
  logger.benchmark(:list_section, :start)
  opt[:config_template] ||= 'default'

  tpl_cfg = Doing.setting(['templates', opt[:config_template]])

  cfg = if opt[:view_template]
          Doing.setting(['views', opt[:view_template]]).deep_merge(tpl_cfg, { extend_existing_arrays: true, sort_merged_arrays: true })
        else
          tpl_cfg
        end

  cfg.deep_merge({
                   'wrap_width' => Doing.setting('wrap_width') || 0,
                   'date_format' => Doing.setting('default_date_format'),
                   'order' => Doing.setting('order') || :asc,
                   'tags_color' => Doing.setting('tags_color'),
                   'duration' => Doing.setting('duration'),
                   'interval_format' => Doing.setting('interval_format')
                 }, { extend_existing_arrays: true, sort_merged_arrays: true })

  opt[:duration] ||= cfg['duration'] || false
  opt[:interval_format] ||= cfg['interval_format'] || 'text'
  opt[:count] ||= 0
  opt[:age] ||= :newest
  opt[:age] = opt[:age].normalize_age
  opt[:format] ||= cfg['date_format']
  opt[:order] ||= cfg['order'] || :asc
  opt[:tag_order] ||= :asc
  opt[:tags_color] = cfg['tags_color'] || false if opt[:tags_color].nil?
  opt[:template] ||= cfg['template']
  opt[:sort_tags] ||= opt[:tag_sort]

  # opt[:highlight] ||= true
  title = ''
  is_single = true
  if opt[:section].nil?
    opt[:section] = choose_section
    title = opt[:section]
  elsif opt[:section].instance_of?(String)
    title = if opt[:section] =~ /^all$/i
              if opt[:page_title]
                opt[:page_title]
              elsif opt[:tag_filter] && opt[:tag_filter]['bool'].normalize_bool != :not
                opt[:tag_filter]['tags'].map { |tag| "@#{tag}" }.join(' + ')
              else
                'doing'
              end
            else
              guess_section(opt[:section])
            end
  end

  items = filter_items(items, opt: opt)

  items.reverse! unless opt[:order].normalize_order == :desc

  if opt[:delete]
    delete_items(items, force: opt[:force])

    write(@doing_file)
    return
  elsif opt[:editor]
    edit_items(items)

    write(@doing_file)
    return
  elsif opt[:interactive]
    opt[:menu] = !opt[:force]
    opt[:query] = '' # opt[:search]
    opt[:multiple] = true
    selected = Prompt.choose_from_items(items.reverse, include_section: opt[:section] =~ /^all$/i, **opt)

    raise NoResults, 'no items selected' if selected.nil? || selected.empty?

    act_on(selected, opt)
    return
  end

  opt[:output] ||= 'template'
  opt[:wrap_width] ||= Doing.setting('templates.default.wrap_width', 0)

  logger.benchmark(:list_section, :finish)
  output(items, title, is_single, opt)
end

#loggerObject

Logger

Responds to :debug, :info, :warn, and :error

Each method takes a topic, and a message or block

Example: debug('Hooks', 'Hook 1 triggered')



76
77
78
# File 'lib/doing/wwid/wwid.rb', line 76

def logger
  @logger ||= Doing.logger
end

#recent(count = 10, section = nil, opt) ⇒ Object

Show recent entries

Parameters:

  • count (Integer) (defaults to: 10)

    The number to show

  • section (String) (defaults to: nil)

    The section to show from, default Currently

  • opt (Hash)

    Additional Options



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
# File 'lib/doing/wwid/display.rb', line 213

def recent(count = 10, section = nil, opt)
  opt ||= {}
  opt[:times] ||= false
  opt[:totals] ||= false
  opt[:sort_tags] ||= false

  cfg = Doing.setting('templates.recent').deep_merge(Doing.setting('templates.default'), { extend_existing_arrays: true, sort_merged_arrays: true }).deep_merge({
    'wrap_width' => Doing.setting('wrap_width') || 0,
    'date_format' => Doing.setting('default_date_format'),
    'order' => Doing.setting('order') || :asc,
    'tags_color' => Doing.setting('tags_color'),
    'duration' => Doing.setting('duration'),
    'interval_format' => Doing.setting('interval_format')
  }, { extend_existing_arrays: true, sort_merged_arrays: true })
  opt[:duration] ||= cfg['duration'] || false
  opt[:interval_format] ||= cfg['interval_format'] || 'text'

  section ||= Doing.setting('current_section')
  section = guess_section(section)

  opt[:section] = section
  opt[:wrap_width] = cfg['wrap_width']
  opt[:count] = count
  opt[:format] = cfg['date_format']
  opt[:template] = opt[:template] || cfg['template']
  opt[:order] = :asc

  list_section(opt)
end

#rename_view_keys(view) ⇒ Object



107
108
109
110
111
112
113
114
115
116
117
# File 'lib/doing/wwid/wwid.rb', line 107

def rename_view_keys(view)
  options = view.symbolize_keys
  # options.rename_key(:tags, :tag, keep: true)
  options.rename_key(:output_format, :output)
  options.rename_key(:tags_bool, :bool)
  options.rename_key(:tag_sort, :sort_tags)
  options.rename_key(:negate, :not)
  options.rename_key(:order, :sort)

  options
end

#repeat_item(item, opt) ⇒ Object

Duplicate an item and add it as a new item

Parameters:

  • item (Item)

    the item to duplicate

  • opt (Hash)

    additional options

Options Hash (opt):

  • :editor (Boolean)

    open new item in editor

  • :date (String)

    set start date

  • :in (String)

    add new item to section :in

  • :note (Note)

    add note to new item

Returns:

  • nothing



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
# File 'lib/doing/wwid/modify.rb', line 100

def repeat_item(item, opt)
  opt ||= {}
  old_item = item.clone
  if item.unfinished? && item.should_finish?
    if item.should_time?
      finish_date = verify_duration(item.date, Time.now, title: item.title)
      item.title.tag!('done', value: finish_date.strftime('%F %R'))
    else
      item.title.tag!('done')
    end
    Hooks.trigger :post_entry_updated, self, item, old_item
  end

  # Remove @done tag
  title = item.title.sub(/\s*@done(\(.*?\))?/, '').chomp
  section = opt[:in].nil? ? item.section : guess_section(opt[:in])
  Doing.auto_tag = false

  note = opt[:note] || Note.new

  if opt[:editor]
    start = opt[:date] ? opt[:date] : Time.now
    to_edit = "#{start.strftime('%F %R')} | #{title}"
    to_edit += "\n#{note.strip_lines.join("\n")}" unless note.empty?
    new_item = fork_editor(to_edit)
    date, title, note = format_input(new_item)

    opt[:date] = date unless date.nil?

    if title.nil? || title.empty?
      logger.warn('Skipped:', 'No content provided')
      return
    end
  end

  # @content.update_item(original, item)
  add_item(title, section, { note: note, back: opt[:date], timed: false })
end

#repeat_last(opt) ⇒ Object

Restart the last entry

Parameters:

  • opt (Hash)

    Additional Options



144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
# File 'lib/doing/wwid/modify.rb', line 144

def repeat_last(opt)
  opt ||= {}
  opt[:section] ||= 'all'
  opt[:section] = guess_section(opt[:section])
  opt[:note] ||= []
  opt[:tag] ||= []
  opt[:tag_bool] ||= :and

  last = last_entry(opt)
  if last.nil?
    logger.warn('Skipped:', 'No previous entry found')
    return
  end

  repeat_item(last, opt)
  write(@doing_file)
end

#reset_item(item, date: nil, finish_date: nil, resume: false) ⇒ Object

Reset start date to current time, optionally remove done tag (resume)

Parameters:

  • item (Item)

    the item to reset/resume

  • resume (Boolean) (defaults to: false)

    removing @done tag if true



75
76
77
78
79
80
81
82
83
84
85
86
# File 'lib/doing/wwid/modify.rb', line 75

def reset_item(item, date: nil, finish_date: nil, resume: false)
  date ||= Time.now
  item.date = date
  if finish_date
    item.tag('done', remove: true)
    item.tag('done', value: finish_date.strftime('%F %R'))
  else
    item.tag('done', remove: true) if resume
  end
  logger.info('Reset:', %(Reset #{resume ? 'and resumed ' : ''} "#{item.title}" in #{item.section}))
  item
end

#rotate(opt) ⇒ Object

Rename doing file with date and start fresh one



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
# File 'lib/doing/wwid/filetools.rb', line 105

def rotate(opt)
  opt ||= {}
  keep = opt[:keep] || 0
  tags = []
  tags.concat(opt[:tag].split(/ *, */).map { |t| t.sub(/^@/, '').strip }) if opt[:tag]
  bool  = opt[:bool] || :and
  sect = opt[:section] !~ /^all$/i ? guess_section(opt[:section]) : 'all'

  section = guess_section(sect)

  section_items = @content.in_section(section)
  max = section_items.count - keep.to_i

  counter = 0
  new_content = Items.new

  section_items.each do |item|
    break if counter >= max
    if opt[:before]
      time_string = opt[:before]
      cutoff = time_string.chronify(guess: :begin)
    end

    unless ((!tags.empty? && !item.tags?(tags, bool)) || (opt[:search] && !item.search(opt[:search].to_s)) || (opt[:before] && item.date >= cutoff))
      new_item = @content.delete(item)
      Hooks.trigger :post_entry_removed, self, item.clone
      raise DoingRuntimeError, "Error deleting item: #{item}" if new_item.nil?

      new_content.add_section(new_item.section, log: false)
      new_content.push(new_item)
      counter += 1
    end
  end

  if counter.positive?
    logger.count(:rotated,
                 level: :info,
                 count: counter,
                 message: "Rotated %count %items")
  else
    logger.info('Skipped:', 'No items were rotated')
  end

  write(@doing_file)

  file = @doing_file.sub(/(\.\w+)$/, "_#{Time.now.strftime('%Y-%m-%d')}\\1")
  if File.exist?(file)
    init_doing_file(file)
    @content.concat(new_content).uniq!
    logger.warn('File update:', "added entries to existing file: #{file}")
  else
    @content = new_content
    logger.warn('File update:', "created new file: #{file}")
  end

  write(file, backup: false)
end

#sectionsArray

List sections

Returns:

  • (Array)

    section titles



85
86
87
# File 'lib/doing/wwid/wwid.rb', line 85

def sections
  @content.section_titles
end

#stop_start(target_tag, opt) ⇒ Object

Accepts one tag and the raw text of a new item if the passed tag is on any item, it's replaced with @done. if new_item is not nil, it's tagged with the passed tag and inserted. This is for use where only one instance of a given tag should exist (@meanwhile)

Parameters:

  • target_tag (String)

    Tag to replace

  • opt (Hash)

    Additional Options

Options Hash (opt):

  • :section (String)

    target section

  • :archive (Boolean)

    archive old item

  • :back (Date)

    backdate new item

  • :new_item (String)

    content to use for new item

  • :note (Array)

    note content for new item



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
# File 'lib/doing/wwid/modify.rb', line 341

def stop_start(target_tag, opt)
  opt ||= {}
  tag = target_tag.dup
  opt[:section] ||= Doing.setting('current_section')
  opt[:archive] ||= false
  opt[:back] ||= Time.now
  opt[:new_item] ||= false
  opt[:note] ||= false

  opt[:section] = guess_section(opt[:section])

  tag.sub!(/^@/, '')

  found_items = 0

  @content.each_with_index do |item, i|
    old_item = i.clone
    next unless item.section == opt[:section] || opt[:section] =~ /all/i

    next unless item.title =~ /@#{tag}/

    item.title.add_tags!([tag, 'done'], remove: true)
    item.tag('done', value: opt[:back].strftime('%F %R'))

    found_items += 1

    if opt[:archive] && opt[:section] != 'Archive'
      item.title = item.title.sub(/(?:@from\(.*?\))?(.*)$/, "\\1 @from(#{item.section})")
      item.move_to('Archive', label: false, log: false)
      logger.count(:completed_archived)
      logger.info('Completed/archived:', item.title)
    else
      logger.count(:completed)
      logger.info('Completed:', item.title)
    end
    Hooks.trigger :post_entry_updated, self, item, old_item
  end


  logger.debug('Skipped:', "No active @#{tag} tasks found.") if found_items.zero?

  if opt[:new_item]
    date, title, note = format_input(opt[:new_item])
    opt[:back] = date unless date.nil?
    note.add(opt[:note]) if opt[:note]
    title.tag!(tag)
    add_item(title.cap_first, opt[:section], { note: note, back: opt[:back] })
  end

  write(@doing_file)
end

#tag_groups(items, opt: {}) ⇒ Object



39
40
41
42
43
44
45
46
47
48
49
# File 'lib/doing/wwid/tags.rb', line 39

def tag_groups(items, opt: {})
  all_items = filter_items(items, opt: opt)
  tags = all_tags(all_items, opt: {})
  groups = {}
  tags.each do |tag|
    groups[tag] ||= []
    groups[tag] = filter_items(all_items, opt: { tag: tag, tag_bool: :or })
  end

  groups
end

#tag_last(opt) ⇒ Object

Tag the last entry or X entries

Parameters:

  • opt (Hash)

    Additional Options (see

    filter_items for filtering

    options)

Raises:

  • (NoResults)

See Also:



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
# File 'lib/doing/wwid/modify.rb', line 171

def tag_last(opt) # hooked
  opt ||= {}
  opt[:count] ||= 1
  opt[:archive] ||= false
  opt[:tags] ||= ['done']
  opt[:sequential] ||= false
  opt[:date] ||= false
  opt[:remove] ||= false
  opt[:update] ||= false
  opt[:autotag] ||= false
  opt[:back] ||= false
  opt[:unfinished] ||= false
  opt[:section] = opt[:section] ? guess_section(opt[:section]) : 'All'

  items = filter_items(Items.new, opt: opt)

  if opt[:interactive]
    items = Prompt.choose_from_items(items, include_section: opt[:section] =~ /^all$/i, menu: true,
                                header: '',
                                prompt: 'Select entries to tag > ',
                                multiple: true,
                                sort: true,
                                show_if_single: true)

    raise NoResults, 'no items selected' if items.empty?

  end

  raise NoResults, 'no items matched your search' if items.empty?

  if opt[:tags].empty? && !opt[:autotag]
    completions = opt[:remove] ? all_tags(items) : all_tags(@content)
    if opt[:remove]
      puts "#{yellow}Available tags: #{boldwhite}#{completions.map(&:add_at).join(', ')}"
    else
      puts "#{yellow}Use tab to complete known tags"
    end
    opt[:tags] = Doing::Prompt.read_line(prompt: "Enter tag(s) to #{opt[:remove] ? 'remove' : 'add'}",
                                         completions: completions,
                                         default_response: '').to_tags
    raise UserCancelled, 'No tags provided' if opt[:tags].empty?
  end

  items.each do |item|
    old_item = item.clone
    added = []
    removed = []

    item.date = opt[:start_date] if opt[:start_date]

    if opt[:autotag]
      new_title = autotag(item.title) if Doing.auto_tag
      if new_title == item.title
        logger.count(:skipped, level: :debug, message: '%count unchaged %items')
        # logger.debug('Autotag:', 'No changes')
      else
        logger.count(:added_tags)
        logger.write(items.count == 1 ? :info : :debug, 'Tagged:', new_title)
        item.title = new_title
      end
    else
      if opt[:done_date]
        done_date = opt[:done_date]
      elsif opt[:sequential]
        next_entry = next_item(item)

        done_date = if next_entry.nil?
                      Time.now
                    else
                      next_entry.date - 60
                    end
      else
        done_date = item.calculate_end_date(opt)
      end

      opt[:tags].each do |tag|
        if tag == 'done' && !item.should_finish?

          Doing.logger.debug('Skipped:', "Item in never_finish: #{item.title}")
          logger.count(:skipped, level: :debug)
          next
        end

        tag = tag.strip

        if tag =~ /^(\S+)\((.*?)\)$/
          m = Regexp.last_match
          tag = m[1]
          opt[:value] ||= m[2]
        end

        if tag =~ /^done$/ && opt[:date] && item.should_time?
          max_elapsed = Doing.setting('interaction.confirm_longer_than', 0)
          max_elapsed = max_elapsed.chronify_qty if max_elapsed.is_a?(String)
          elapsed = done_date - item.date

          if max_elapsed.positive? && (elapsed > max_elapsed) && !opt[:took]
            puts boldwhite(item.title)
            human = elapsed.time_string(format: :natural)
            res = Prompt.yn(yellow("Did this actually take #{human}"), default_response: true)
            unless res
              new_elapsed = Prompt.enter_text('How long did it take?').chronify_qty
              raise InvalidTimeExpression, 'Unrecognized time span entry' unless new_elapsed > 0

              opt[:took] = new_elapsed
              done_date = item.calculate_end_date(opt) if opt[:took]
            end
          end
        end

        if opt[:remove] || opt[:rename] || opt[:value]
          rename_to = nil

          if opt[:value]
            rename_to = tag
          elsif opt[:rename]
            rename_to = tag
            tag = opt[:rename]
          end
          old_title = item.title.dup
          force = opt[:value].nil? ? false : true
          item.title.tag!(tag, remove: opt[:remove], rename_to: rename_to, regex: opt[:regex], value: opt[:value], force: force)
          if old_title != item.title
            removed << tag
            added << rename_to if rename_to
          else
            logger.count(:skipped, level: :debug)
          end
        else
          old_title = item.title.dup
          should_date = opt[:date] && item.should_time?
          item.title.tag!('done', remove: true) if tag =~ /done/ && (!should_date || opt[:update])
          item.title.tag!(tag, value: should_date ? done_date.strftime('%F %R') : nil)
          added << tag if old_title != item.title
        end
      end
    end

    logger.log_change(tags_added: added, tags_removed: removed, item: item, single: items.count == 1)

    item.note.add(opt[:note]) if opt[:note]

    if opt[:archive] && opt[:section] != 'Archive' && (opt[:count]).positive?
      item.move_to('Archive', label: true)
    elsif opt[:archive] && opt[:count].zero?
      logger.warn('Skipped:', 'Archiving is skipped when operating on all entries')
    end

    item.expand_date_tags(Doing.setting('date_tags'))
    Hooks.trigger :post_entry_updated, self, item, old_item
  end

  write(@doing_file)
end

#tag_times(format: :text, sort_by: :time, sort_order: :asc) ⇒ Object

Get total elapsed time for all tags in selection

Parameters:

  • format (String) (defaults to: :text)

    return format (html, json, or text)

  • sort_by (Symbol) (defaults to: :time)

    Sort by :name or :time

  • sort_order (Symbol) (defaults to: :asc)

    The sort order (:asc or :desc)



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
# File 'lib/doing/wwid/timers.rb', line 14

def tag_times(format: :text, sort_by: :time, sort_order: :asc)
  return '' if @timers.empty?

  @timers.delete('meanwhile')

  max = @timers.keys.sort_by(&:length).reverse[0].length + 1

  total = @timers.delete('All')

  tags_data = @timers.delete_if { |_k, v| v.zero? }
  sorted_tags_data = if sort_by.normalize_tag_sort == :name
                       tags_data.sort_by { |k, _v| k }
                     else
                       tags_data.sort_by { |_k, v| v }
                     end

  sorted_tags_data.reverse! if sort_order.normalize_order == :asc
  case format
  when :html

    output = <<EOHEAD
      <table>
      <caption id="tagtotals">Tag Totals</caption>
      <colgroup>
      <col style="text-align:left;"/>
      <col style="text-align:left;"/>
      </colgroup>
      <thead>
      <tr>
        <th style="text-align:left;">project</th>
        <th style="text-align:left;">time</th>
      </tr>
      </thead>
      <tbody>
EOHEAD
    sorted_tags_data.reverse.each do |k, v|
      if v.positive?
        output += "<tr><td style='text-align:left;'>#{k}</td><td style='text-align:left;'>#{v.time_string(format: :clock)}</td></tr>\n"
      end
    end
    tail = <<EOTAIL
    <tr>
      <td style="text-align:left;" colspan="2"></td>
    </tr>
    </tbody>
    <tfoot>
    <tr>
      <td style="text-align:left;"><strong>Total</strong></td>
      <td style="text-align:left;">#{total.time_string(format: :clock)}</td>
    </tr>
    </tfoot>
    </table>
EOTAIL
    output + tail
  when :markdown
    pad = sorted_tags_data.map { |k, _| k }.group_by(&:size).max.last[0].length
    pad = 7 if pad < 7
    output = <<~EOHEADER
  | #{' ' * (pad - 7)}project | time     |
  | #{'-' * (pad - 1)}: | :------- |
    EOHEADER
    sorted_tags_data.reverse.each do |k, v|
      if v.positive?
        output += "| #{' ' * (pad - k.length)}#{k} | #{v.time_string(format: :clock)} |\n"
      end
    end
    tail = '[Tag Totals]'
    output + tail
  when :json
    output = []
    sorted_tags_data.reverse.each do |k, v|
      output << {
        'tag' => k,
        'seconds' => v,
        'formatted' => v.time_string(format: :clock)
      }
    end
    output
  when :human
    output = []
    sorted_tags_data.reverse.each do |k, v|
      spacer = ''
      (max - k.length).times do
        spacer += ' '
      end
      output.push("#{spacer}#{k}:#{v.time_string(format: :hm)}")
    end

    header = '┏━━ Tag Totals '
    (max - 2).times { header += '' }
    header += ''
    footer = ''
    (max + 12).times { footer += '' }
    footer += ''
    divider = ''
    (max + 12).times { divider += '' }
    divider += ''
    output = output.empty? ? '' : "\n#{header}\n#{output.join("\n")}"
    output += "\n#{divider}"
    spacer = ''
    (max - 6).times do
      spacer += ' '
    end
    total_time = total.time_string(format: :hm)
    total = "#{spacer}total: "
    total += total_time
    total += ''
    output += "\n#{total}"
    output += "\n#{footer}"
    output
  else
    output = []
    sorted_tags_data.reverse.each do |k, v|
      spacer = ''
      (max - k.length).times do
        spacer += ' '
      end
      output.push("#{k}:#{spacer}#{v.time_string(format: :clock)}")
    end

    output = output.empty? ? '' : "\n--- Tag Totals ---\n#{output.join("\n")}"
    output += "\n\nTotal tracked: #{total.time_string(format: :clock)}\n"
    output
  end
end

#today(times = true, output = nil, opt) ⇒ Object

Show all entries from the current day

Parameters:

  • times (Boolean) (defaults to: true)

    show times

  • output (String) (defaults to: nil)

    output format

  • opt (Hash)

    Options



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
# File 'lib/doing/wwid/display.rb', line 135

def today(times = true, output = nil, opt)
  opt ||= {}
  opt[:totals] ||= false
  opt[:sort_tags] ||= false

  cfg = Doing.setting('templates').deep_merge(Doing.setting('templates.default'), { extend_existing_arrays: true, sort_merged_arrays: true }).deep_merge({
    'wrap_width' => Doing.setting('wrap_width') || 0,
    'date_format' => Doing.setting('default_date_format'),
    'order' => Doing.setting('order') || :asc,
    'tags_color' => Doing.setting('tags_color'),
    'duration' => Doing.setting('duration'),
    'interval_format' => Doing.setting('interval_format')
  }, { extend_existing_arrays: true, sort_merged_arrays: true })

  template = opt[:template] || cfg['template']

  opt[:duration] ||= cfg['duration'] || false
  opt[:interval_format] ||= cfg['interval_format'] || 'text'

  options = {
    after: opt[:after],
    before: opt[:before],
    count: 0,
    duration: opt[:duration],
    from: opt[:from],
    format: cfg['date_format'],
    interval_format: opt[:interval_format],
    only_timed: opt[:only_timed],
    order: cfg['order'] || :asc,
    output: output,
    section: opt[:section],
    sort_tags: opt[:sort_tags],
    template: template,
    times: times,
    today: true,
    totals: opt[:totals],
    wrap_width: cfg['wrap_width'],
    tags_color: cfg['tags_color'],
    config_template: opt[:config_template]
  }
  list_section(options)
end

#verify_duration(date, finish_date, title: nil) ⇒ Object

Interactively verify an item modification if elapsed time is greater than configured threshold

Parameters:

  • date (String)

    Item date

  • finish_date (String)

    The finish date

  • title (String) (defaults to: nil)

    The Item title



358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
# File 'lib/doing/wwid/interactive.rb', line 358

def verify_duration(date, finish_date, title: nil)
  max_elapsed = Doing.setting('interaction.confirm_longer_than', 0)
  max_elapsed = max_elapsed.chronify_qty if max_elapsed.is_a?(String)
  date = date.chronify(guess: :end, context: :today) if date.is_a?(String)
  finish_date = finish_date.chronify(guess: :end, context: :today) if finish_date.is_a?(String)

  elapsed = finish_date - date

  if max_elapsed.positive? && (elapsed > max_elapsed)
    puts boldwhite(title) if title
    human = elapsed.time_string(format: :natural)
    res = Prompt.yn(yellow("Did this entry actually take #{human}"), default_response: true)
    unless res
      new_elapsed = Prompt.enter_text('How long did it take?').chronify_qty
      raise InvalidTimeExpression, 'Unrecognized time span entry' unless new_elapsed.positive?

      finish_date = date + new_elapsed if new_elapsed
    end
  end

  finish_date
end

#view_to_options(title) ⇒ Object



119
120
121
122
123
124
125
# File 'lib/doing/wwid/wwid.rb', line 119

def view_to_options(title)
  view = rename_view_keys(get_view(guess_view(title)))
  view.deep_merge(rename_view_keys(get_view(guess_view(view[:parent]), fallback: {}))) if view.key?(:parent)
  view.deep_merge(rename_view_keys(get_view(view[:config_template], fallback: {}))) if view.key?(:config_template)
  view.deep_merge(Doing.setting('templates.default').symbolize_keys)
  view
end

#viewsArray

List available views

Returns:



94
95
96
# File 'lib/doing/wwid/wwid.rb', line 94

def views
  Doing.setting('views') ? Doing.setting('views').keys : []
end

#write(file = nil, backup: true) ⇒ Object

Write content to file or STDOUT

Parameters:

  • file (String) (defaults to: nil)

    The filepath to write to



91
92
93
94
95
96
97
98
99
100
# File 'lib/doing/wwid/filetools.rb', line 91

def write(file = nil, backup: true)
  Hooks.trigger :pre_write, self, file
  output = combined_content
  if file.nil?
    $stdout.puts output
  else
    Util.write_to_file(file, output, backup: backup)
    run_after if Doing.setting('run_after')
  end
end

#yesterday(section, times = nil, output = nil, opt) ⇒ Object

Show entries from the previous day

Parameters:

  • section (String)

    The section

  • times (Bool) (defaults to: nil)

    Show times

  • output (String) (defaults to: nil)

    Output format

  • opt (Hash)

    Additional Options



186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
# File 'lib/doing/wwid/display.rb', line 186

def yesterday(section, times = nil, output = nil, opt)
  opt ||= {}
  opt[:totals] ||= false
  opt[:sort_tags] ||= false
  opt[:config_template] ||= 'today'
  opt[:yesterday] = true

  section = guess_section(section)
  y = (Time.now - (60 * 60 * 24)).strftime('%Y-%m-%d')
  opt[:after] = "#{y} #{opt[:after]}" if opt[:after]
  opt[:before] = "#{y} #{opt[:before]}" if opt[:before]

  opt[:output] = output
  opt[:section] = section
  opt[:times] = times
  opt[:count] = 0

  list_section(opt)
end