Class: WWID

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

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initializeWWID

Returns a new instance of WWID.



50
51
52
53
54
55
56
57
# File 'lib/doing/wwid.rb', line 50

def initialize
  @content = {}
  @doingrc_needs_update = false
  @default_config_file = '.doingrc'
  @interval_cache = {}
  @results = []
  @auto_tag = true
end

Instance Attribute Details

#auto_tagObject

Returns the value of attribute auto_tag.



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

def auto_tag
  @auto_tag
end

#configObject

Returns the value of attribute config.



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

def config
  @config
end

#config_fileObject

Returns the value of attribute config_file.



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

def config_file
  @config_file
end

#contentObject

Returns the value of attribute content.



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

def content
  @content
end

#current_sectionObject

Returns the value of attribute current_section.



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

def current_section
  @current_section
end

#default_config_fileObject

Returns the value of attribute default_config_file.



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

def default_config_file
  @default_config_file
end

#doing_fileObject

Returns the value of attribute doing_file.



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

def doing_file
  @doing_file
end

#resultsObject

Returns the value of attribute results.



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

def results
  @results
end

#sectionsArray

Returns section titles.

Returns:

  • (Array)

    section titles



441
442
443
# File 'lib/doing/wwid.rb', line 441

def sections
  @sections
end

#user_homeObject

Returns the value of attribute user_home.



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

def user_home
  @user_home
end

Instance Method Details

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

Parameters:

  • title (String)

    The entry title

  • section (String) (defaults to: nil)

    The section to add to

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

    Additional Options :note, :back, :timed



577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
# File 'lib/doing/wwid.rb', line 577

def add_item(title,section=nil,opt={})
  section ||= @current_section
  add_section(section) unless @content.has_key?(section)
  opt[:date] ||= Time.now
  opt[:note] ||= []
  opt[:back] ||= Time.now
  opt[:timed] ||= false

  opt[:note] = [opt[:note]] if opt[:note].class == String

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

  if @auto_tag
    title = autotag(title)
    unless @config['default_tags'].empty?
      title += @config['default_tags'].map{|t|
        unless t.nil?
          dt = t.sub(/^ *@/,'').chomp
          if title =~ /@#{dt}/
            ""
          else
            ' @' + dt
          end
        end
      }.delete_if {|t| t == "" }.join(" ")
    end
  end
  title.gsub!(/ +/,' ')
  entry = {'title' => title.strip, 'date' => opt[:back]}
  unless opt[:note].join('').strip == ''
    entry['note'] = opt[:note].map {|n| n.chomp}
  end
  items = @content[section]['items']
  if opt[:timed]
    items.reverse!
    items.each_with_index {|i,x|
      if i['title'] =~ / @done/
        next
      else
        items[x]['title'] = "#{i['title']} @done(#{opt[:back].strftime('%F %R')})"
        break
      end
    }
    items.reverse!
  end
  items.push(entry)
  @content[section]['items'] = items
  @results.push(%Q{Added "#{entry['title']}" to #{section}})
end

#add_section(title) ⇒ Object

Parameters:

  • title (String)

    The new section title



450
451
452
453
# File 'lib/doing/wwid.rb', line 450

def add_section(title)
  @content[title.cap_first] = {'original' => "#{title}:", 'items' => []}
  @results.push(%Q{Added section "#{title.cap_first}"})
end

#archive(section = "Currently", count = 5, destination = nil, tags = nil, bool = nil, export = nil) ⇒ Object

Parameters:

  • section (String) (defaults to: "Currently")

    The source section

  • count (Integer) (defaults to: 5)

    The count

  • destination (String) (defaults to: nil)

    The destination section

  • tags (Array) (defaults to: nil)

    Tags to archive

  • bool (String) (defaults to: nil)

    Tag boolean combinator



1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
# File 'lib/doing/wwid.rb', line 1373

def archive(section="Currently",count=5,destination=nil,tags=nil,bool=nil,export=nil)

  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

  if destination =~ /archive/i && !sections.include?("Archive")
    add_section("Archive")
  end

  destination = guess_section(destination)

  if sections.include?(destination) && (sections.include?(section) || archive_all)
    if archive_all
      to_archive = sections.dup
      to_archive.delete(destination)
      to_archive.each {|source,v|
        do_archive(source, destination, { :count => count, :tags => tags, :bool => bool, :label => true })
      }
    else
      do_archive(section, destination, { :count => count, :tags => tags, :bool => bool, :label => true })
    end

    write(doing_file)
  else
    raise "Either source or destination does not exist"
  end
end

#autotag(text) ⇒ Object

Does not repeat tags in a title, and only converts the first instance of an untagged keyword

Parameters:

  • text (String)

    The text to tag



1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
# File 'lib/doing/wwid.rb', line 1689

def autotag(text)
  return unless text
  return text unless @auto_tag
  current_tags = text.scan(/@\w+/)
  whitelisted = []
  @config['autotag']['whitelist'].each {|tag|
    text.sub!(/(?<!@)(#{tag.strip})\b/i) do |m|
      m.downcase! if tag =~ /[a-z]/
      whitelisted.push("@#{m}")
      "@#{m}"
    end unless text =~ /@#{tag}\b/i
  }
  tail_tags = []
  @config['autotag']['synonyms'].each {|tag, v|
    v.each {|word|
      if text =~ /\b#{word}\b/i
        unless current_tags.include?("@#{tag}") || whitelisted.include?("@#{tag}")
          tail_tags.push(tag)
        end
      end
    }
  }
  if @config['autotag'].key? 'transform'
    @config['autotag']['transform'].each {|tag|
      if tag =~ /\S+:\S+/
        rx, r = tag.split(/:/)
        r.gsub!(/\$/,'\\')
        rx.sub!(/^@/,'')
        regex = Regexp.new('@' + rx + '\b')

        matches = text.scan(regex)
        matches.each {|m|
          new_tag = r
          if m.kind_of?(Array)
            index = 1
            m.each {|v|
              new_tag = new_tag.gsub('\\' + index.to_s, v)
              index = index + 1
            }
          end
          tail_tags.push(new_tag)
        } if matches
      end
    }
  end
  if whitelisted.length > 0
    @results.push("Whitelisted tags: #{whitelisted.join(', ')}")
  end
  if tail_tags.length > 0
    tags = tail_tags.uniq.map {|t| '@'+t }.join(' ')
    @results.push("Synonym tags: #{tags}")
    text + ' ' + tags
  else
    text
  end
end

#choose_sectionString

Returns The selected section name.

Returns:

  • (String)

    The selected section name



936
937
938
939
940
941
942
943
944
# File 'lib/doing/wwid.rb', line 936

def choose_section
  sections.each_with_index {|section, i|
    puts "% 3d: %s" % [i+1, section]
  }
  print "#{colors['green']}> #{colors['default']}"
  num = STDIN.gets
  return false if num =~ /^[a-z ]*$/i
  return sections[num.to_i - 1]
end

#choose_viewString

Returns The selected view name.

Returns:

  • (String)

    The selected view name



960
961
962
963
964
965
966
967
968
# File 'lib/doing/wwid.rb', line 960

def choose_view
  views.each_with_index {|view, i|
    puts "% 3d: %s" % [i+1, view]
  }
  print "> "
  num = STDIN.gets
  return false if num =~ /^[a-z ]*$/i
  return views[num.to_i - 1]
end

#chronify(input) ⇒ DateTime

Returns result.

Parameters:

  • input (String)

    String to chronify

Returns:

  • (DateTime)

    result



384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
# File 'lib/doing/wwid.rb', line 384

def chronify(input)
  now = Time.now
  raise "Invalid time expression #{input.inspect}" if input.to_s.strip == ""
  secs_ago = if input.match /^(\d+)$/
    # plain number, assume minutes
    $1.to_i * 60
  elsif (m = input.match /^((?<day>\d+)d)?((?<hour>\d+)h)?((?<min>\d+)m)?$/i)
    # day/hour/minute format e.g. 1d2h30m
    [[m['day'], 24*3600],
     [m['hour'], 3600],
     [m['min'], 60]].map {|qty, secs| qty ? (qty.to_i * secs) : 0 }.reduce(0, :+)
  end

  if secs_ago
    now - secs_ago
  else
    Chronic.parse(input, {:context => :past, :ambiguous_time_range => 8})
  end
end

#chronify_qty(qty) ⇒ Integer

Returns seconds.

Parameters:

  • qty (String)

    HH:MM or XX[[XXhm]] (1d2h30m, 45m, 1.5d, 1h20m, etc.)

Returns:

  • (Integer)

    seconds



413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
# File 'lib/doing/wwid.rb', line 413

def chronify_qty(qty)
  minutes = 0
  if qty.strip =~ /^(\d+):(\d\d)$/
    minutes += $1.to_i * 60
    minutes += $2.to_i
  elsif qty.strip =~ /^(\d+(?:\.\d+)?)([hmd])?$/
    amt = $1
    type = $2.nil? ? "m" : $2

    minutes = case type.downcase
    when 'm'
      amt.to_i
    when 'h'
      (amt.to_f * 60).round
    when 'd'
      (amt.to_f * 60 * 24).round
    else
      minutes
    end
  end
  minutes * 60
end

#colorsString

Returns ANSI escape sequence.

Returns:

  • (String)

    ANSI escape sequence



1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
# File 'lib/doing/wwid.rb', line 1477

def colors
  color = {}
  color['black'] = "\033[0;0;30m"
  color['red'] = "\033[0;0;31m"
  color['green'] = "\033[0;0;32m"
  color['yellow'] = "\033[0;0;33m"
  color['blue'] = "\033[0;0;34m"
  color['magenta'] = "\033[0;0;35m"
  color['cyan'] = "\033[0;0;36m"
  color['white'] = "\033[0;0;37m"
  color['bgblack'] = "\033[40m"
  color['bgred'] = "\033[41m"
  color['bggreen'] = "\033[42m"
  color['bgyellow'] = "\033[43m"
  color['bgblue'] = "\033[44m"
  color['bgmagenta'] = "\033[45m"
  color['bgcyan'] = "\033[46m"
  color['bgwhite'] = "\033[47m"
  color['boldblack'] = "\033[1;30m"
  color['boldred'] = "\033[1;31m"
  color['boldgreen'] = "\033[0;1;32m"
  color['boldyellow'] = "\033[0;1;33m"
  color['boldblue'] = "\033[0;1;34m"
  color['boldmagenta'] = "\033[0;1;35m"
  color['boldcyan'] = "\033[0;1;36m"
  color['boldwhite'] = "\033[0;1;37m"
  color['boldbgblack'] = "\033[1;40m"
  color['boldbgred'] = "\033[1;41m"
  color['boldbggreen'] = "\033[1;42m"
  color['boldbgyellow'] = "\033[1;43m"
  color['boldbgblue'] = "\033[1;44m"
  color['boldbgmagenta'] = "\033[1;45m"
  color['boldbgcyan'] = "\033[1;46m"
  color['boldbgwhite'] = "\033[1;47m"
  color['softpurple'] = "\033[0;35;40m"
  color['hotpants'] = "\033[7;34;40m"
  color['knightrider'] = "\033[7;30;40m"
  color['flamingo'] = "\033[7;31;47m"
  color['yeller'] = "\033[1;37;43m"
  color['whiteboard'] = "\033[1;30;47m"
  color['default'] = "\033[0;39m"
  color
end

#configure(opt = {}) ⇒ Object

Parameters:

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

    Additional Options



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

def configure(opt={})
  @timers = {}
  opt[:ignore_local] ||= false

  unless @config_file
    @config_file = File.join(@user_home, @default_config_file)
  end

  read_config({:ignore_local => opt[:ignore_local]})

  user_config = @config.dup

  @config = {} if @config.nil?

  @config['autotag'] ||= {}
  @config['autotag']['whitelist'] ||= []
  @config['autotag']['synonyms'] ||= {}
  @config['doing_file'] ||= "~/what_was_i_doing.md"
  @config['current_section'] ||= 'Currently'
  @config['editor_app'] ||= nil

  @config['html_template'] ||= {}
  @config['html_template']['haml'] ||= nil
  @config['html_template']['css'] ||= nil

  @config['templates'] ||= {}
  @config['templates']['default'] ||= {
    'date_format' => '%Y-%m-%d %H:%M',
    'template' => '%date | %title%note',
    'wrap_width' => 0
  }
  @config['templates']['today'] ||= {
    'date_format' => '%_I:%M%P',
    'template' => '%date: %title %interval%note',
    'wrap_width' => 0
  }
  @config['templates']['last'] ||= {
    'date_format' => '%-I:%M%P on %a',
    'template' => '%title (at %date)%odnote',
    'wrap_width' => 88
  }
  @config['templates']['recent'] ||= {
    'date_format' => '%_I:%M%P',
    'template' => '%shortdate: %title (%section)',
    'wrap_width' => 88
  }
  @config['views'] ||= {
    'done' => {
      'date_format' => '%_I:%M%P',
      'template' => '%date | %title%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"
    }
  }
  @config['marker_tag'] ||= 'flagged'
  @config['marker_color'] ||= 'red'
  @config['default_tags'] ||= []
  @config['tag_sort'] ||= 'time'

  @current_section = config['current_section']
  @default_template = config['templates']['default']['template']
  @default_date_format = config['templates']['default']['date_format']

  @config[:include_notes] ||= true

  # if ENV['DOING_DEBUG'].to_i == 3
  #   if @config['default_tags'].length > 0
  #     raise "DEFAULT CONFIG CHANGED"
  #   end
  # end

  unless File.exists?(@config_file)
    File.open(@config_file, 'w') { |yf| YAML::dump(@config, yf) }
  end

  @config = @local_config.deep_merge(@config)

  @current_section = @config['current_section']
  @default_template = @config['templates']['default']['template']
  @default_date_format = @config['templates']['default']['date_format'];


end

#create(filename = nil) ⇒ Object



303
304
305
306
307
308
309
310
311
312
# File 'lib/doing/wwid.rb', line 303

def create(filename=nil)
  if filename.nil?
    filename = @doing_file
  end
  unless File.exists?(filename) && File.stat(filename).size > 0
    File.open(filename,'w+') do |f|
      f.puts @current_section + ":"
    end
  end
end

#css_templateString

Returns CSS template.

Returns:



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

def css_template
  IO.read(File.join(File.dirname(__FILE__), '../templates/doing.css'))
end

#do_archive(section, destination, opt = {}) ⇒ Object

Parameters:

  • section (String)

    The source section

  • destination (String)

    The destination section

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

    Additional Options



1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
# File 'lib/doing/wwid.rb', line 1409

def do_archive(section, destination, opt={})
  count = opt[:count] || 5
  tags = opt[:tags] || []
  bool = opt[:bool] || "AND"
  label = opt[:label] || false

  items = @content[section]['items']
  moved_items = []

  if tags && !tags.empty?
    items.delete_if {|item|
      if bool =~ /(AND|ALL)/
        score = 0
        tags.each {|tag|
          score += 1 if item['title'] =~ /@#{tag}/i
        }
        res = score < tags.length
        moved_items.push(item) if res
        res
      elsif bool =~ /NONE/
        del = false
        tags.each {|tag|
          del = true if item['title'] =~ /@#{tag}/i
        }
        moved_items.push(item) if del
        del
      elsif bool =~ /(OR|ANY)/
        del = true
        tags.each {|tag|
          del = false if item['title'] =~ /@#{tag}/i
        }
        moved_items.push(item) if del
        del
      end
    }
    moved_items.each {|item|
      if label
        item['title'] = item['title'].sub(/(?:@from\(.*?\))?(.*)$/,"\\1 @from(#{section})")  unless section == "Currently"
      end
    }
    @content[section]['items'] = moved_items
    @content[destination]['items'] += items
    @results.push("Archived #{items.length} items from #{section} to #{destination}")
  else

    return if items.length < count
    if count == 0
      @content[section]['items'] = []
    else
      @content[section]['items'] = items[0..count-1]
    end

    items.each{|item|
      if label
        item['title'] = item['title'].sub(/(?:@from\(.*?\))?(.*)$/,"\\1 @from(#{section})")  unless section == "Currently"
      end
    }

    @content[destination]['items'] += items[count..-1]
    @results.push("Archived #{items.length - count} items from #{section} to #{destination}")
  end
end

#find_local_configString

Returns A file path.

Returns:



64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
# File 'lib/doing/wwid.rb', line 64

def find_local_config

  config = {}
  dir = Dir.pwd

  local_config_files = []

  while (dir != '/' && (dir =~ /[A-Z]:\//) == nil)
    if File.exists? File.join(dir, @default_config_file)
      local_config_files.push(File.join(dir, @default_config_file))
    end

    dir = File.dirname(dir)
  end

  local_config_files
end

#fork_editor(input = "") ⇒ Object

Parameters:

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

    Text input for editor



319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
# File 'lib/doing/wwid.rb', line 319

def fork_editor(input="")
  tmpfile = Tempfile.new(['doing','.md'])

  File.open(tmpfile.path,'w+') do |f|
    f.puts input
    f.puts "\n# The first line is the entry title, any lines after that are added as a note"
  end

  pid = Process.fork { system("$EDITOR #{tmpfile.path}") }

  trap("INT") {
    Process.kill(9, pid) rescue Errno::ESRCH
    tmpfile.unlink
    tmpfile.close!
    exit 0
  }

  Process.wait(pid)

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

  input
end

#format_input(input) ⇒ Array

Returns [(String)title, (Array)note].

Parameters:

  • input (String)

    The string to parse

Returns:

  • (Array)
    (String)title, (Array)note


359
360
361
362
363
364
365
366
367
368
369
370
371
# File 'lib/doing/wwid.rb', line 359

def format_input(input)
  raise "No content in entry" if input.nil? || input.strip.length == 0
  input_lines = input.split(/[\n\r]+/)
  title = input_lines[0].strip
  note = input_lines.length > 1 ? input_lines[1..-1] : []
  note.map! { |line|
    line.strip
  }.delete_if { |line|
    line =~ /^\s*$/ || line =~ /^#/
  }

  [title, note]
end

#get_view(title) ⇒ Object

Parameters:

  • title (String)

    The title of the view to retrieve



975
976
977
978
979
980
# File 'lib/doing/wwid.rb', line 975

def get_view(title)
  if @config['views'].has_key?(title)
    return @config['views'][title]
  end
  false
end

#guess_section(frag, guessed = false) ⇒ Object

Parameters:

  • frag (String)

    The user-provided string

  • guessed (Boolean) (defaults to: false)

    already guessed and failed



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

def guess_section(frag,guessed=false)
  return "All" if frag =~ /all/i
  sections.each {|section| return section.cap_first if frag.downcase == section.downcase }
  section = false
  re = frag.split('').join(".*?")
  sections.each {|sect|
    if sect =~ /#{re}/i
      $stderr.puts "Assuming you meant #{sect}"
      section = sect
      break
    end
  }
  unless section || guessed
    alt = guess_view(frag,true)
    if alt
      raise "Did you mean `doing view #{alt}`?"
    else
      res = yn("Section #{frag} not found, create it",false)

      if res
        add_section(frag.cap_first)
        write(@doing_file)
        return frag.cap_first
      end
      raise "Unknown section: #{frag}"
    end
  end
  section ? section.cap_first : guessed
end

#guess_view(frag, guessed = false) ⇒ Object

Parameters:

  • frag (String)

    The user-provided string

  • guessed (Boolean) (defaults to: false)

    already guessed



548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
# File 'lib/doing/wwid.rb', line 548

def guess_view(frag,guessed=false)
  views.each {|view| return view if frag.downcase == view.downcase}
  view = false
  re = frag.split('').join(".*?")
  views.each {|v|
    if v =~ /#{re}/i
      $stderr.puts "Assuming you meant #{v}"
      view = v
      break
    end
  }
  unless view || guessed
    alt = guess_section(frag,true)
    if alt
      raise "Did you mean `doing show #{alt}`?"
    else
      raise "Unknown view: #{frag}"
    end
  end
  view
end

#haml_templateString

Returns HAML template.

Returns:



287
288
289
# File 'lib/doing/wwid.rb', line 287

def haml_template
  IO.read(File.join(File.dirname(__FILE__), '../templates/doing.haml'))
end

#init_doing_file(path = nil) ⇒ Object

Parameters:

  • path (String) (defaults to: nil)

    Override path to a doing file, optional



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

def init_doing_file(path=nil)
  @doing_file = File.expand_path(@config['doing_file'])

  input = path

  if input.nil?
    create(@doing_file) unless File.exists?(@doing_file)
    input = IO.read(@doing_file)
    input = input.force_encoding('utf-8') if input.respond_to? :force_encoding
  elsif File.exists?(File.expand_path(input)) && File.file?(File.expand_path(input)) && File.stat(File.expand_path(input)).size > 0
    @doing_file = File.expand_path(input)
    input = IO.read(File.expand_path(input))
    input = input.force_encoding('utf-8') if input.respond_to? :force_encoding
  elsif input.length < 256
    @doing_file = File.expand_path(input)
    create(input)
    input = IO.read(File.expand_path(input))
    input = input.force_encoding('utf-8') if input.respond_to? :force_encoding
  end

  @other_content_top = []
  @other_content_bottom = []

  section = "Uncategorized"
  lines = input.split(/[\n\r]/)
  current = 0

  lines.each {|line|
    next if line =~ /^\s*$/
    if line =~ /^(\S[\S ]+):\s*(@\S+\s*)*$/
      section = $1
      @content[section] = {}
      @content[section]['original'] = line
      @content[section]['items'] = []
      current = 0
    elsif line =~ /^\s*- (\d{4}-\d\d-\d\d \d\d:\d\d) \| (.*)/
      date = Time.parse($1)
      title = $2
      @content[section]['items'].push({'title' => title, 'date' => date, 'section' => section})
      current += 1
    else
      # if content[section]['items'].length - 1 == current
        if current == 0
          @other_content_top.push(line)
        else
          if line =~ /^\S/
            @other_content_bottom.push(line)
          else
            unless @content[section]['items'][current - 1].has_key? 'note'
              @content[section]['items'][current - 1]['note'] = []
            end
            @content[section]['items'][current - 1]['note'].push(line.gsub(/ *$/,''))
          end
        end
      # end
    end
  }
end

#last(times = true, section = nil) ⇒ Object

Parameters:

  • times (Bool) (defaults to: true)

    Show times

  • section (String) (defaults to: nil)

    Section to pull from, default Currently



1597
1598
1599
1600
1601
1602
# File 'lib/doing/wwid.rb', line 1597

def last(times=true,section=nil)
  section ||= @current_section
  section = guess_section(section)
  cfg = @config['templates']['last']
  list_section({:section => section, :wrap_width => cfg['wrap_width'], :count => 1, :format => cfg['date_format'], :template => cfg['template'], :times => times})
end

#last_note(section = "All") ⇒ Object

Parameters:

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

    The section to retrieve from, default All



634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
# File 'lib/doing/wwid.rb', line 634

def last_note(section="All")
  section = guess_section(section)
  if section =~ /^all$/i
    combined = {'items' => []}
    @content.each {|k,v|
      combined['items'] += v['items']
    }
    section = combined['items'].dup.sort_by{|item| item['date'] }.reverse[0]['section']
  end

  if @content.has_key?(section)
    last_item = @content[section]['items'].dup.sort_by{|item| item['date'] }.reverse[0]
    $stderr.puts "Editing note for #{last_item['title']}"
    note = ''
    unless last_item['note'].nil?
      note = last_item['note'].map{|line| line.strip }.join("\n")
    end
    return "#{last_item['title']}\n# EDIT BELOW THIS LINE ------------\n#{note}"
  else
    raise "Section #{section} not found"
  end
end

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

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) (defaults to: {})

    Additional Options



1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
# File 'lib/doing/wwid.rb', line 1546

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

  list_section({:section => section, :count => 0, :order => "asc", :date_filter => dates, :times => times, :output => output, :totals => opt[:totals], :sort_tags => opt[:sort_tags] })
end

#list_section(opt = {}) ⇒ Object

Parameters:

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

    Additional Options



988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
# File 'lib/doing/wwid.rb', line 988

def list_section(opt={})
  opt[:count] ||= 0
  count = opt[:count] - 1
  opt[:section] ||= nil
  opt[:format] ||= @default_date_format
  opt[:template] ||= @default_template
  opt[:age] ||= "newest"
  opt[:order] ||= "desc"
  opt[:today] ||= false
  opt[:tag_filter] ||= false
  opt[:tags_color] ||= false
  opt[:times] ||= false
  opt[:totals] ||= false
  opt[:sort_tags] ||= false
  opt[:search] ||= false
  opt[:only_timed] ||= false
  opt[:date_filter] ||= []

  # opt[:highlight] ||= true
  section = ""
  if opt[:section].nil?
    section = choose_section
    opt[:section] = @content[section]
  elsif opt[:section].class == String
    if opt[:section] =~ /^all$/i
      combined = {'items' => []}
      @content.each {|k,v|
        combined['items'] += v['items']
      }
      section = opt[:tag_filter] && opt[:tag_filter]['bool'] != 'NONE' ? opt[:tag_filter]['tags'].map {|tag| "@#{tag}"}.join(" + ") : "doing"
      opt[:section] = combined
    else
      section = guess_section(opt[:section])
      opt[:section] = @content[section]
    end
  end

  if opt[:section].class != Hash
    $stderr.puts "Invalid section object"
    return
  end

  items = opt[:section]['items'].sort_by{|item| item['date'] }

  if opt[:date_filter].length == 2
    start_date = opt[:date_filter][0]
    end_date = opt[:date_filter][1]
    items.keep_if {|item|
      if end_date
        item['date'] >= start_date && item['date'] <= end_date
      else
        item['date'].strftime('%F') == start_date.strftime('%F')
      end
    }
  end

  if opt[:tag_filter] && !opt[:tag_filter]['tags'].empty?
    items.delete_if {|item|
      if opt[:tag_filter]['bool'] =~ /(AND|ALL)/
        score = 0
        opt[:tag_filter]['tags'].each {|tag|
          score += 1 if item['title'] =~ /@#{tag}/
        }
        score < opt[:tag_filter]['tags'].length
      elsif opt[:tag_filter]['bool'] =~ /NONE/
        del = false
        opt[:tag_filter]['tags'].each {|tag|
          del = true if item['title'] =~ /@#{tag}/
        }
        del
      elsif opt[:tag_filter]['bool'] =~ /(OR|ANY)/
        del = true
        opt[:tag_filter]['tags'].each {|tag|
          del = false if item['title'] =~ /@#{tag}/
        }
        del
      end
    }
  end

  if opt[:search]
    items.keep_if {|item|
      text = item['note'] ? item['title'] + item['note'].join(" ") : item['title']
      if opt[:search].strip =~ /^\/.*?\/$/
        pattern = opt[:search].sub(/\/(.*?)\//,'\1')
      else
        pattern = opt[:search].split('').join('.{0,3}')
      end
      text =~ /#{pattern}/i
    }
  end

  if opt[:only_timed]
    items.delete_if {|item|
      get_interval(item) == false
    }
  end

  if opt[:today]
    items.delete_if {|item|
      item['date'] < Date.today.to_time
    }.reverse!
    section = Time.now.strftime('%A, %B %d')
  elsif opt[:yesterday]
    items.delete_if {|item| item['date'] <= Date.today.prev_day.to_time or
                     item['date'] >= Date.today.to_time
                    }.reverse!
  else
    if opt[:age] =~ /oldest/i
      items = items[0..count]
    else
      items = items.reverse[0..count]
    end
  end

  if opt[:order] =~ /^a/i
    items.reverse!
  end

  out = ""

  if opt[:output]
    raise "Unknown output format" unless opt[:output] =~ /(template|html|csv|json|timeline)/
  end
  if opt[:output] == "csv"
    output = [CSV.generate_line(['date','title','note','timer','section'])]
    items.each {|i|
      note = ""
      if i['note']
        arr = i['note'].map{|line| line.strip}.delete_if{|e| e =~ /^\s*$/}
        note = arr.join("\n") unless arr.nil?
      end
      if i['title'] =~ /@done\((\d{4}-\d\d-\d\d \d\d:\d\d.*?)\)/ && opt[:times]
        interval = get_interval(i, false)
      end
      interval ||= 0
      output.push(CSV.generate_line([i['date'],i['title'],note,interval,i['section']]))
    }
    out = output.join("")
  elsif opt[:output] == "json" || opt[:output] == "timeline"

    items_out = []
    max = items[-1]['date'].strftime('%F')
    min = items[0]['date'].strftime('%F')
    items.each_with_index {|i,index|
      if String.method_defined? :force_encoding
        title = i['title'].force_encoding('utf-8')
        note = i['note'].map {|line| line.force_encoding('utf-8').strip } if i['note']
      else
        title = i['title']
        note = i['note'].map { |line| line.strip } if i['note']
      end

      if i['title'] =~ /@done\((\d{4}-\d\d-\d\d \d\d:\d\d.*?)\)/ && opt[:times]
        end_date = Time.parse($1)
        interval = get_interval(i,false)
      end
      end_date ||= ""
      interval ||= 0
      note ||= ""

      tags = []
      skip_tags = ['meanwhile', 'done', 'cancelled', 'flagged']
      i['title'].scan(/@([^\(\s]+)(?:\((.*?)\))?/).each {|tag|
        tags.push(tag[0]) unless skip_tags.include?(tag[0])
      }
      if opt[:output] == "json"
        items_out << {
          :date => i['date'],
          :end_date => end_date,
          :title => title.strip, #+ " #{note}"
          :note => note.class == Array ? note.join("\n") : note,
          :time => "%02d:%02d:%02d" % fmt_time(interval),
          :tags => tags
        }
      elsif opt[:output] == "timeline"
        new_item = {
          'id' => index + 1,
          'content' => title.strip, #+ " #{note}"
          'title' => title.strip + " (#{"%02d:%02d:%02d" % fmt_time(interval)})",
          'start' => i['date'].strftime('%F'),
          'type' => 'point'
        }

        if interval && interval > 0
          new_item['end'] = end_date.strftime('%F')
          if interval > 3600 * 3
            new_item['type'] = 'range'
          end
        end
        items_out.push(new_item)
      end
    }
    if opt[:output] == "json"
      out = {
        'section' => section,
        'items' => items_out,
        'timers' => tag_times("json", opt[:sort_tags])
      }.to_json
    elsif opt[:output] == "timeline"
              template ="<!doctype html>\n<html>\n<head>\n<link href=\"http://visjs.org/dist/vis.css\" rel=\"stylesheet\" type=\"text/css\" />\n<script src=\"http://visjs.org/dist/vis.js\"></script>\n</head>\n<body>\n<div id=\"mytimeline\"></div>\n\n<script type=\"text/javascript\">\n  // DOM element where the Timeline will be attached\n  var container = document.getElementById('mytimeline');\n\n  // Create a DataSet with data (enables two way data binding)\n  var data = new vis.DataSet(\#{items_out.to_json});\n\n  // Configuration for the Timeline\n  var options = {\n    width: '100%',\n    height: '800px',\n    margin: {\n      item: 20\n    },\n    stack: true,\n    min: '\#{min}',\n    max: '\#{max}'\n  };\n\n  // Create a Timeline\n  var timeline = new vis.Timeline(container, data, options);\n</script>\n</body>\n</html>\n"
      return template
    end
  elsif opt[:output] == "html"
    page_title = section
    items_out = []
    items.each {|i|
      # if i.has_key?('note')
      #   note = '<span class="note">' + i['note'].map{|n| n.strip }.join('<br>') + '</span>'
      # else
      #   note = ''
      # end
      if String.method_defined? :force_encoding
        title = i['title'].force_encoding('utf-8').link_urls
        note = i['note'].map {|line| line.force_encoding('utf-8').strip.link_urls } if i['note']
      else
        title = i['title'].link_urls
        note = i['note'].map { |line| line.strip.link_urls } if i['note']
      end

      if i['title'] =~ /@done\((\d{4}-\d\d-\d\d \d\d:\d\d.*?)\)/ && opt[:times]
        interval = get_interval(i)
      end
      interval ||= false

      items_out << {
        :date => i['date'].strftime('%a %-I:%M%p'),
        :title => title.gsub(/(@[^ \(]+(\(.*?\))?)/im,'<span class="tag">\1</span>').strip, #+ " #{note}"
        :note => note,
        :time => interval,
        :section => i['section']
      }
    }

    if @config['html_template']['haml'] && File.exists?(File.expand_path(@config['html_template']['haml']))
      template = IO.read(File.expand_path(@config['html_template']['haml']))
    else
      template = haml_template
    end

    if @config['html_template']['css'] && File.exists?(File.expand_path(@config['html_template']['css']))
      style = IO.read(File.expand_path(@config['html_template']['css']))
    else
      style = css_template
    end

    totals = opt[:totals] ? tag_times("html", opt[:sort_tags]) : ""
    engine = Haml::Engine.new(template)
    puts engine.render(Object.new, { :@items => items_out, :@page_title => page_title, :@style => style, :@totals => totals })
  else
    items.each {|item|

      if opt[:highlight] && item['title'] =~ /@#{@config['marker_tag']}\b/i
        flag = colors[@config['marker_color']]
        reset = colors['default']
      else
        flag = ""
        reset = ""
      end

      if (item.has_key?('note') && !item['note'].empty?) && @config[:include_notes]
        note_lines = item['note'].delete_if{|line| line =~ /^\s*$/ }.map{|line| "\t" + line.sub(/^\t*/,'') + "  " }
        if opt[:wrap_width] && opt[:wrap_width] > 0
          width = opt[:wrap_width]
          note_lines.map! {|line|
            line.strip.gsub(/(.{1,#{width}})(\s+|\Z)/, "\t\\1\n")
          }
        end
        note = "\n#{note_lines.join("\n").chomp}"
      else
        note = ""
      end
      output = opt[:template].dup

      output.gsub!(/%[a-z]+/) do |m|
        if colors.has_key?(m.sub(/^%/,''))
          colors[m.sub(/^%/,'')]
        else
          m
        end
      end

      output.sub!(/%date/,item['date'].strftime(opt[:format]))

      if item['title'] =~ /@done\((\d{4}-\d\d-\d\d \d\d:\d\d.*?)\)/ && opt[:times]
        interval = get_interval(item)
      end
      interval ||= ""
      output.sub!(/%interval/,interval)

      output.sub!(/%shortdate/) {
        if item['date'] > Date.today.to_time
          item['date'].strftime('%_I:%M%P')
        elsif item['date'] > (Date.today - 7).to_time
          item['date'].strftime('%a %-I:%M%P')
        elsif item['date'].year == Date.today.year
          item['date'].strftime('%b %d, %-I:%M%P')
        else
          item['date'].strftime('%b %d %Y, %-I:%M%P')
        end
      }

      output.sub!(/%title/) {|m|
        if opt[:wrap_width] && opt[:wrap_width] > 0
          flag+item['title'].gsub(/(.{1,#{opt[:wrap_width]}})(\s+|\Z)/, "\\1\n\t ").chomp+reset
        else
          flag+item['title'].chomp+reset
        end
      }

      output.sub!(/%section/,item['section']) if item['section']

      if opt[:tags_color]
        escapes = output.scan(/(\e\[[\d;]+m)[^\e]+@/)
        if escapes.length > 0
          last_color = escapes[-1][0]
        else
          last_color = colors['default']
        end
        output.gsub!(/\s(@[^ \(]+)/," #{colors[opt[:tags_color]]}\\1#{last_color}")
      end
      output.sub!(/%note/,note)
      output.sub!(/%odnote/,note.gsub(/^\t*/,""))
      output.sub!(/%chompnote/,note.gsub(/\n+/,' ').gsub(/(^\s*|\s*$)/,'').gsub(/\s+/,' '))
      output.gsub!(/%hr(_under)?/) do |m|
        o = ""
        `tput cols`.to_i.times do
          o += $1.nil? ? "-" : "_"
        end
        o
      end
      output.gsub!(/%n/,"\n")
      output.gsub!(/%t/,"\t")

      out += output + "\n"
    }
    out += tag_times("text", opt[:sort_tags]) if opt[:totals]
  end
  return out
end

#note_last(section, note, replace = false) ⇒ Object

Parameters:

  • section (String)

    The section, default “All”

  • note (String)

    The note to add

  • replace (Bool) (defaults to: false)

    Should replace existing note



789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
# File 'lib/doing/wwid.rb', line 789

def note_last(section, note, replace=false)
  section = guess_section(section)

  if section =~ /^all$/i
    combined = {'items' => []}
    @content.each {|k,v|
      combined['items'] += v['items']
    }
    section = combined['items'].dup.sort_by{|item| item['date'] }.reverse[0]['section']
  end

  if @content.has_key?(section)
    # sort_section(opt[:section])
    items = @content[section]['items'].dup.sort_by{|item| item['date'] }.reverse

    current_note = items[0]['note']
    current_note = [] if current_note.nil?
    title = items[0]['title']
    if replace
      items[0]['note'] = note
      if note.empty? && !current_note.empty?
        @results.push(%Q{Removed note from "#{title}"})
      elsif current_note.length > 0 && note.length > 0
        @results.push(%Q{Replaced note from "#{title}"})
      elsif note.length > 0
        @results.push(%Q{Added note to "#{title}"})
      else
        @results.push(%Q{Entry "#{title}" has no note})
      end
    elsif current_note.class == Array
      items[0]['note'] = current_note.concat(note)
      @results.push(%Q{Added note to "#{title}"}) if note.length > 0
    else
      items[0]['note'] = note
      @results.push(%Q{Added note to "#{title}"}) if note.length > 0
    end

    @content[section]['items'] = items
  else
    raise "Section #{section} not found"
  end
end

#read_config(opt = {}) ⇒ Object



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

def read_config(opt={})
  unless @config_file
    if Dir.respond_to?('home')
      @config_file = File.join(Dir.home, @default_config_file)
    else
      @config_file = File.join(File.expand_path("~"), @default_config_file)
    end
  end

  if opt[:ignore_local]
    additional_configs = []
  else
    additional_configs = find_local_config
  end

  begin
    @local_config = {}

    @config = YAML.load_file(@config_file) || {} if File.exists?(@config_file)
    additional_configs.each { |cfg|
      new_config = YAML.load_file(cfg) || {} if cfg
      @local_config = @local_config.deep_merge(new_config)
    }

    # @config.deep_merge(@local_config)
  rescue
    @config = {}
    @local_config = {}
    # raise "error reading config"
  end
end

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

Parameters:

  • count (Integer) (defaults to: 10)

    The number to show

  • section (String) (defaults to: nil)

    The section to show from, default Currently

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

    Additional Options



1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
# File 'lib/doing/wwid.rb', line 1580

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

  cfg = @config['templates']['recent']
  section ||= @current_section
  section = guess_section(section)
  list_section({:section => section, :wrap_width => cfg['wrap_width'], :count => count, :format => cfg['date_format'], :template => cfg['template'], :order => "asc", :times => times, :totals => opt[:totals], :sort_tags => opt[:sort_tags] })
end

#restore_backup(file) ⇒ Object

Parameters:

  • file (String)

    The filepath to restore



922
923
924
925
926
927
928
# File 'lib/doing/wwid.rb', line 922

def restore_backup(file)
  if File.exists?(file+"~")
    puts file+"~"
    FileUtils.cp(file+"~",file)
    @results.push("Restored #{file}")
  end
end

#stop_start(tag, opt = {}) ⇒ Object

Parameters:

  • tag (String)

    Tag to replace

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

    Additional Options



843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
# File 'lib/doing/wwid.rb', line 843

def stop_start(tag,opt={})
  opt[:section] ||= @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[opt[:section]]['items'].each_with_index {|item, i|
    if item['title'] =~ /@#{tag}/
      title = item['title'].gsub(/(^| )@(#{tag}|done)(\([^\)]*\))?/,'')
      title += " @done(#{opt[:back].strftime('%F %R')})"

      @content[opt[:section]]['items'][i]['title'] = title
      found_items += 1

      if opt[:archive] && opt[:section] != "Archive"
        @results.push(%Q{Completed and archived "#{@content[opt[:section]]['items'][i]['title']}"})
        archive_item = @content[opt[:section]]['items'][i]
        archive_item['title'] = i['title'].sub(/(?:@from\(.*?\))?(.*)$/,"\\1 @from(#{i['section']})")
        @content['Archive']['items'].push(archive_item)
        @content[opt[:section]]['items'].delete_at(i)
      else
        @results.push(%Q{Completed "#{@content[opt[:section]]['items'][i]['title']}"})
      end
    end
  }

  @results.push("No active @#{tag} tasks found.") if found_items == 0

  if opt[:new_item]
    title, note = format_input(opt[:new_item])
    note.push(opt[:note].gsub(/ *$/,'')) if opt[:note]
    title += " @#{tag}"
    add_item(title.cap_first, opt[:section], {:note => note.join(' ').rstrip, :back => opt[:back]})
  end

  write(@doing_file)
end

#tag_last(opt = {}) ⇒ Object

Parameters:

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

    Additional Options



662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
# File 'lib/doing/wwid.rb', line 662

def tag_last(opt={})
  opt[:section] ||= @current_section
  opt[:count] ||= 1
  opt[:archive] ||= false
  opt[:tags] ||= ["done"]
  opt[:sequential] ||= false
  opt[:date] ||= false
  opt[:remove] ||= false
  opt[:autotag] ||= false
  opt[:back] ||= false


  sec_arr = []

  if opt[:section].nil?
    sec_arr = [@current_section]
  elsif opt[:section].class == String
    if opt[:section] =~ /^all$/i
      if opt[:count] == 1
        combined = {'items' => []}
        @content.each {|k,v|
          combined['items'] += v['items']
        }
        items = combined['items'].dup.sort_by{|item| item['date'] }.reverse
        sec_arr.push(items[0]['section'])
      elsif opt[:count] > 1
        raise "A count greater than one requires a section to be specified"
      else
        sec_arr = sections
      end
    else
      sec_arr = [guess_section(opt[:section])]
    end
  end



  sec_arr.each {|section|
    if @content.has_key?(section)

      items = @content[section]['items'].dup.sort_by{|item| item['date'] }.reverse

      index = 0
      done_date = Time.now
      next_start = Time.now
      count = opt[:count] == 0 ? items.length : opt[:count]
      items.map! {|item|
        break if index == count

        unless opt[:autotag]
          if opt[:sequential]
            done_date = next_start - 1
            next_start = item['date']
          elsif opt[:back]
            done_date = item['date'] + (opt[:back] - item['date'])
          else
            done_date = Time.now
          end

          title = item['title']
          opt[:tags].each {|tag|
            tag.strip!
            if opt[:remove]
              if title =~ /@#{tag}\b/
                title.gsub!(/(^| )@#{tag}(\([^\)]*\))?/,'')
                @results.push(%Q{Removed @#{tag}: "#{title}" in #{section}})
              end
            else
              unless title =~ /@#{tag}/
                title.chomp!
                if opt[:date]
                  title += " @#{tag}(#{done_date.strftime('%F %R')})"
                else
                  title += " @#{tag}"
                end
                @results.push(%Q{Added @#{tag}: "#{title}" in #{section}})
              end
            end
          }
          item['title'] = title
        else
          new_title = autotag(item['title']) if @auto_tag
          unless new_title == item['title']
            @results.push("Tags updated: #{new_title}")
            item['title'] = new_title
          else
            @results.push(%Q{Autotag: No changes})
          end
        end

        index += 1

        item
      }

      @content[section]['items'] = items

      if opt[:archive] && section != "Archive" && opt[:count] > 0
        # concat [count] items from [section] and archive section
        archived = @content[section]['items'][0..opt[:count]-1].map {|i|
          i['title'].sub(/(?:@from\(.*?\))?(.*)$/,"\\1 @from(#{i['section']})")
        }.concat(@content['Archive']['items'])
        # chop [count] items off of [section] items
        @content[opt[:section]]['items'] = @content[opt[:section]]['items'][opt[:count]..-1]
        # overwrite archive section with concatenated array
        @content['Archive']['items'] = archived
        # log it
        result = opt[:count] == 1 ? "1 entry" : "#{opt[:count]} entries"
        @results.push("Archived #{result} from #{section}")
      elsif opt[:archive] && opt[:count] == 0
        @results.push("Archiving is skipped when operating on all entries") if opt[:count] == 0
      end
    else
      raise "Section not found: #{section}"
    end
  }

  write(@doing_file)
end

#tag_times(format = "text", sort_by_name = false) ⇒ Object

Parameters:

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

    return format (html, json, or text)



1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
# File 'lib/doing/wwid.rb', line 1609

def tag_times(format="text", sort_by_name = false)

  return "" if @timers.empty?

  max = @timers.keys.sort_by {|k| k.length }.reverse[0].length + 1

  total = @timers.delete("All")

  tags_data = @timers.delete_if { |k,v| v == 0}
  if sort_by_name
    sorted_tags_data = tags_data.sort_by{|k,v| k }.reverse
  else
    sorted_tags_data = tags_data.sort_by{|k,v| v }
  end

  if format == "html"
    output ="      <table>\n      <caption id=\"tagtotals\">Tag Totals</caption>\n      <colgroup>\n      <col style=\"text-align:left;\"/>\n      <col style=\"text-align:left;\"/>\n      </colgroup>\n      <thead>\n      <tr>\n        <th style=\"text-align:left;\">project</th>\n        <th style=\"text-align:left;\">time</th>\n      </tr>\n      </thead>\n      <tbody>\n"
    sorted_tags_data.reverse.each {|k,v|
      output += "<tr><td style='text-align:left;'>#{k}</td><td style='text-align:left;'>#{"%02d:%02d:%02d" % fmt_time(v)}</td></tr>\n" if v > 0
    }
    tail ="    <tr>\n      <td style=\"text-align:left;\" colspan=\"2\"></td>\n    </tr>\n    </tbody>\n    <tfoot>\n    <tr>\n      <td style=\"text-align:left;\"><strong>Total</strong></td>\n      <td style=\"text-align:left;\">\#{\"%02d:%02d:%02d\" % fmt_time(total)}</td>\n    </tr>\n    </tfoot>\n    </table>\n"
    output + tail
  elsif format == "json"
    output = []
    sorted_tags_data.reverse.each {|k,v|
      output << {
        'tag' => k,
        'seconds' => v,
        'formatted' => "%02d:%02d:%02d" % fmt_time(v)
      }
    }
    output
  else
    output = []
    sorted_tags_data.reverse.each {|k,v|
      spacer = ""
      (max - k.length).times do
        spacer += " "
      end
      output.push("#{k}:#{spacer}#{"%02d:%02d:%02d" % fmt_time(v)}")
    }

    output = output.empty? ? "" : "\n--- Tag Totals ---\n" + output.join("\n")
    output += "\n\nTotal tracked: #{"%02d:%02d:%02d" % fmt_time(total)}\n"
    output
  end
end

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

Parameters:

  • times (Boolean) (defaults to: true)

    show times

  • output (String) (defaults to: nil)

    output format

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

    Options



1529
1530
1531
1532
1533
1534
1535
# File 'lib/doing/wwid.rb', line 1529

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

  cfg = @config['templates']['today']
  list_section({:section => opt[:section], :wrap_width => cfg['wrap_width'], :count => 0, :format => cfg['date_format'], :template => cfg['template'], :order => "asc", :today => true, :times => times, :output => output, :totals => opt[:totals], :sort_tags => opt[:sort_tags]})
end

#viewsArray

Returns View names.

Returns:

  • (Array)

    View names



951
952
953
# File 'lib/doing/wwid.rb', line 951

def views
  @config.has_key?('views') ? @config['views'].keys : []
end

#write(file = nil) ⇒ Object

Parameters:

  • file (String) (defaults to: nil)

    The filepath to write to



892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
# File 'lib/doing/wwid.rb', line 892

def write(file=nil)
  unless @other_content_top
    output = ""
  else
    output = @other_content_top.join("\n") + "\n"
  end
  @content.each {|title, section|
    output += section['original'] + "\n"
    output += list_section({:section => title, :template => "\t- %date | %title%note", :highlight => false})
  }
  output += @other_content_bottom.join("\n") unless @other_content_bottom.nil?
  if file.nil?
    $stdout.puts output
  else
    if File.exists?(File.expand_path(file))
      # Create a backup copy for the undo command
      FileUtils.cp(file,file+"~")

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

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

Parameters:

  • section (String)

    The section

  • times (Bool) (defaults to: nil)

    Show times

  • output (String) (defaults to: nil)

    Output format

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

    Additional Options



1566
1567
1568
1569
1570
1571
# File 'lib/doing/wwid.rb', line 1566

def yesterday(section,times=nil,output=nil,opt={})
  opt[:totals] ||= false
  opt[:sort_tags] ||= false
  section = guess_section(section)
  list_section({:section => section, :count => 0, :order => "asc", :yesterday => true, :times => times, :output => output, :totals => opt[:totals], :sort_tags => opt[:sort_tags] })
end

#yn(question, default_response = false) ⇒ Bool

Returns yes or no.

Parameters:

  • question (String)

    The question to ask

  • default (Bool)

    default response if no input

Returns:

  • (Bool)

    yes or no



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

def yn(question, default_response=false)
  if default_response
    default = 'y'
  else
    default = 'n'
  end
  # if this isn't an interactive shell, answer default
  unless $stdout.isatty
    if default.downcase == 'y'
      return true
    else
      return false
    end
  end
  # clear the buffer
  if ARGV.length
    ARGV.length.times do
      ARGV.shift
    end
  end
  system 'stty cbreak'
  if default
    if default =~ /y/i
      options = "#{colors['white']}[#{colors['boldgreen']}Y#{colors['white']}/#{colors['boldwhite']}n#{colors['white']}]#{colors['default']}"
    else
      options = "#{colors['white']}[#{colors['boldwhite']}y#{colors['white']}/#{colors['boldgreen']}N#{colors['white']}]#{colors['default']}"
    end
  else
    options = "#{colors['white']}[#{colors['boldwhite']}y#{colors['white']}/#{colors['boldwhite']}n#{colors['white']}]#{colors['default']}"
  end
  $stdout.syswrite "#{colors['boldwhite']}#{question.sub(/\?$/,'')} #{options}#{colors['boldwhite']}?#{colors['default']} "
  res = $stdin.sysread 1
  puts
  system 'stty cooked'

  res.chomp!
  res.downcase!

  res = default.downcase if res == ""

  return res =~ /y/i
end