Class: Doing::WWID
- Inherits:
-
Object
- Object
- Doing::WWID
- Defined in:
- lib/doing/wwid.rb
Overview
Main "What Was I Doing" methods
Instance Attribute Summary collapse
-
#additional_configs ⇒ Object
readonly
Returns the value of attribute additional_configs.
-
#auto_tag ⇒ Object
Returns the value of attribute auto_tag.
-
#config ⇒ Object
Returns the value of attribute config.
-
#config_file ⇒ Object
Returns the value of attribute config_file.
-
#content ⇒ Object
readonly
Returns the value of attribute content.
-
#current_section ⇒ Object
readonly
Returns the value of attribute current_section.
-
#default_option ⇒ Object
Returns the value of attribute default_option.
-
#doing_file ⇒ Object
readonly
Returns the value of attribute doing_file.
Instance Method Summary collapse
-
#act_on(items, opt = {}) ⇒ Object
Perform actions on a set of entries.
-
#add_item(title, section = nil, opt = {}) ⇒ Object
Adds an entry.
-
#add_section(title) ⇒ Object
Adds a section.
- #all_tags(items, opt: {}) ⇒ Object
-
#archive(section = , options = {}) ⇒ Object
Move entries from a section to Archive or other specified section.
-
#autotag(text) ⇒ Object
Uses 'autotag' configuration to turn keywords into tags for time tracking.
-
#choose_from(options, prompt: 'Make a selection: ', multiple: false, sorted: true, fzf_args: []) ⇒ String
Generate a menu of options and allow user selection.
-
#choose_from_items(items, opt = {}, include_section: false) ⇒ Object
Create an interactive menu to select from a set of Items.
-
#choose_section ⇒ String
Generate a menu of sections and allow user selection.
-
#choose_view ⇒ String
Generate a menu of views and allow user selection.
-
#chronify(input, future: false, guess: :begin) ⇒ DateTime
Converts input string into a Time object when input takes on the following formats: - interval format e.g.
-
#chronify_qty(qty) ⇒ Integer
Converts simple strings into seconds that can be added to a Time object.
-
#create(filename = nil) ⇒ Object
Create a new doing file.
-
#dedup(items, no_overlap = false) ⇒ Object
Remove items from a list that already exist in @content.
-
#delete_item(item, single: false) ⇒ Object
Delete an item from the index.
-
#edit_last(section: 'All', options: {}) ⇒ Object
Edit the last entry.
-
#filter_items(items = [], opt: {}) ⇒ Object
Filter items based on search criteria.
-
#fork_editor(input = '') ⇒ Object
Create a process for an editor and wait for the file handle to return.
-
#format_input(input) ⇒ Array
Takes a multi-line string and formats it as an entry.
-
#format_time(seconds, human: false) ⇒ Object
Format human readable time from seconds.
- #fuzzy_filter_items(items, opt: {}) ⇒ Object
- #fzf ⇒ Object
-
#get_interval(item, formatted: true, record: true) ⇒ Object
Gets the interval between entry's start date and @done date.
-
#get_view(title) ⇒ Object
Gets a view from configuration.
-
#guess_section(frag, guessed: false, suggest: false) ⇒ Object
Attempt to match a string with an existing section.
-
#guess_view(frag, guessed: false, suggest: false) ⇒ Object
Attempt to match a string with an existing view.
-
#import(paths, opt = {}) ⇒ Object
Imports external entries.
-
#init_doing_file(path = nil) ⇒ Object
Initializes the doing file.
-
#initialize ⇒ WWID
constructor
Initializes the object.
-
#interactive(opt = {}) ⇒ Object
Display an interactive menu of entries.
-
#last(times: true, section: nil, options: {}) ⇒ Object
Show the last entry.
-
#last_entry(opt = {}) ⇒ Object
Get the last entry.
-
#last_note(section = 'All') ⇒ Object
Return the content of the last note for a given section.
-
#list_date(dates, section, times = nil, output = nil, opt = {}) ⇒ Object
Display entries within a date range.
-
#list_section(opt = {}) ⇒ Object
Display contents of a section based on options.
-
#logger ⇒ Object
Logger.
-
#move_item(item, section, label: true) ⇒ Item
Move item from current section to destination section.
-
#next_item(item, options = {}) ⇒ Item
Get next item in the index.
-
#recent(count = 10, section = nil, opt = {}) ⇒ Object
Show recent entries.
- #repeat_item(item, opt = {}) ⇒ Object
-
#repeat_last(opt = {}) ⇒ Object
Restart the last entry.
- #reset_item(item, resume: false) ⇒ Object
-
#restore_backup(file) ⇒ Object
Restore a backed up version of a file.
-
#rotate(opt = {}) ⇒ Object
Rename doing file with date and start fresh one.
-
#sections ⇒ Array
List sections.
-
#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.
- #tag_groups(items, opt: {}) ⇒ Object
-
#tag_item(item, tags, remove: false, date: false, single: false) ⇒ Item
Tag an item from the index.
-
#tag_last(opt = {}) ⇒ Object
Tag the last entry or X entries.
-
#tag_times(format: :text, sort_by_name: false, sort_order: 'asc') ⇒ Object
Get total elapsed time for all tags in selection.
-
#today(times = true, output = nil, opt = {}) ⇒ Object
Show all entries from the current day.
-
#update_item(old_item, new_item) ⇒ Object
Update an item in the index with a modified item.
-
#views ⇒ Array
List available views.
-
#write(file = nil, backup: true) ⇒ Object
Write content to file or STDOUT.
-
#yesterday(section, times = nil, output = nil, opt = {}) ⇒ Object
Show entries from the previous day.
-
#yn(question, default_response: false) ⇒ Bool
Ask a yes or no question in the terminal.
Constructor Details
#initialize ⇒ WWID
Initializes the object.
24 25 26 27 28 29 30 31 32 |
# File 'lib/doing/wwid.rb', line 24 def initialize @timers = {} @recorded_items = [] @content = {} @doingrc_needs_update = false @default_config_file = '.doingrc' @auto_tag = true @user_home = Util.user_home end |
Instance Attribute Details
#additional_configs ⇒ Object (readonly)
Returns the value of attribute additional_configs.
15 16 17 |
# File 'lib/doing/wwid.rb', line 15 def additional_configs @additional_configs end |
#auto_tag ⇒ Object
Returns the value of attribute auto_tag.
17 18 19 |
# File 'lib/doing/wwid.rb', line 17 def auto_tag @auto_tag end |
#config ⇒ Object
Returns the value of attribute config.
17 18 19 |
# File 'lib/doing/wwid.rb', line 17 def config @config end |
#config_file ⇒ Object
Returns the value of attribute config_file.
17 18 19 |
# File 'lib/doing/wwid.rb', line 17 def config_file @config_file end |
#content ⇒ Object (readonly)
Returns the value of attribute content.
15 16 17 |
# File 'lib/doing/wwid.rb', line 15 def content @content end |
#current_section ⇒ Object (readonly)
Returns the value of attribute current_section.
15 16 17 |
# File 'lib/doing/wwid.rb', line 15 def current_section @current_section end |
#default_option ⇒ Object
Returns the value of attribute default_option.
17 18 19 |
# File 'lib/doing/wwid.rb', line 17 def default_option @default_option end |
#doing_file ⇒ Object (readonly)
Returns the value of attribute doing_file.
15 16 17 |
# File 'lib/doing/wwid.rb', line 15 def doing_file @doing_file 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
944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 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 |
# File 'lib/doing/wwid.rb', line 944 def act_on(items, 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', 'cancel', 'delete', 'finish', 'flag', 'archive', 'move', 'edit', 'output formatted' ] actions.concat(['resume/repeat', 'begin/reset']) if items.count == 1 choice = choose_from(actions, 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/) to_do.each do |action| case action when /resume/ opt[:resume] = true when /reset/ opt[:reset] = 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] print "#{Color.yellow}Tag to #{type}: #{Color.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 = choose_from(plugins, prompt: 'Which output format? > ', fzf_args: ["--height=#{plugins.count + 3}", '--tac', '--no-sort', '--info=hidden']) next if tag =~ /^ *$/ raise UserCancelled unless output_format opt[:output] = output_format.strip res = opt[:force] ? false : yn('Save to file?', default_response: 'n') if res print "#{Color.yellow}File path/name: #{Color.reset}" filename = $stdin.gets.strip next if filename.empty? opt[:save_to] = filename end when /archive/ opt[:archive] = true when /delete/ opt[:delete] = true when /edit/ opt[:editor] = true when /finish/ opt[:finish] = true when /cancel/ opt[:cancel] = true when /move/ section = choose_section.strip opt[:move] = section.strip unless section =~ /^ *$/ when /flag/ opt[:flag] = true end end end if opt[:resume] || opt[:reset] if items.count > 1 raise InvalidArgument, 'resume and restart can only be used on a single entry' else item = items[0] if opt[:resume] && !opt[:reset] repeat_item(item, { editor: opt[:editor] }) elsif opt[:reset] if item.('done', :and) && !opt[:resume] res = opt[:force] ? true : yn('Remove @done tag?', default_response: 'y') else res = opt[:resume] end update_item(item, reset_item(item, resume: res)) end write(@doing_file) end return end if opt[:delete] res = opt[:force] ? true : yn("Delete #{items.size} items?", default_response: 'y') if res items.each { |item| delete_item(item, single: items.count == 1) } write(@doing_file) end return end if opt[:flag] tag = @config['marker_tag'] || 'flagged' items.map! do |item| tag_item(item, tag, date: false, remove: opt[:remove], single: single) end end if opt[:finish] || opt[:cancel] tag = 'done' items.map! do |item| if item.should_finish? should_date = !opt[:cancel] && item.should_time? tag_item(item, tag, date: should_date, remove: opt[:remove], single: single) end end end if opt[:tag] tag = opt[:tag] items.map! do |item| tag_item(item, tag, date: false, remove: opt[:remove], single: single) end end if opt[:archive] || opt[:move] section = opt[:archive] ? 'Archive' : guess_section(opt[:move]) items.map! {|item| move_item(item, section) } end write(@doing_file) if opt[:editor] editable_items = [] items.each do |item| editable = "#{item.date} | #{item.title}" old_note = item.note ? item.note.to_s : nil editable += "\n#{old_note}" unless old_note.nil? editable_items << editable end divider = "\n-----------\n" input = editable_items.map(&:strip).join(divider) + "\n\n# You may delete entries, but leave all divider lines in place" new_items = fork_editor(input).split(/#{divider}/) new_items.each_with_index do |new_item, i| input_lines = new_item.split(/[\n\r]+/).delete_if(&:ignore?) title = input_lines[0]&.strip if title.nil? || title =~ /^#{divider.strip}$/ || title.strip.empty? delete_item(items[i], single: new_items.count == 1) else note = input_lines.length > 1 ? input_lines[1..-1] : [] note.map!(&:strip) note.delete_if(&:ignore?) date = title.match(/^([\d\-: ]+) \| /)[1] title.sub!(/^([\d\-: ]+) \| /, '') item = items[i] item.title = title item.note = note item.date = Time.parse(date) || items[i].date end end write(@doing_file) end if opt[:output] items.map! do |item| item.title = "#{item.title} @project(#{item.section})" item end @content = { 'Export' => { :original => 'Export:', :items => items } } = { section: 'Export' } if opt[:output] =~ /doing/ [:output] = 'template' [:template] = '- %date | %title%note' else [:output] = opt[:output] [:template] = opt[:template] || nil end output = list_section() if opt[:save_to] file = File.(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 end |
#add_item(title, section = nil, opt = {}) ⇒ Object
Adds an entry
419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 |
# File 'lib/doing/wwid.rb', line 419 def add_item(title, section = nil, opt = {}) section ||= @config['current_section'] add_section(section) unless @content.key?(section) opt[:date] ||= Time.now opt[:note] ||= [] opt[:back] ||= Time.now opt[:timed] ||= false opt[:note] = opt[:note].lines if opt[:note].is_a?(String) title = [title.strip.cap_first] title = title.join(' ') if @auto_tag title = autotag(title) title.(@config['default_tags']) unless @config['default_tags'].empty? end title.gsub!(/ +/, ' ') entry = Item.new(opt[:back], title.strip, section) entry.note = opt[:note].map(&:chomp) unless opt[:note].join('').strip == '' items = @content[section][:items] if opt[:timed] items.reverse! items.each_with_index do |i, x| next if i.title =~ / @done/ items[x].title = "#{i.title} @done(#{opt[:back].strftime('%F %R')})" break end items.reverse! end items.push(entry) # logger.count(:added, level: :debug) logger.info('New entry:', %(added "#{entry.title}" to #{section})) end |
#add_section(title) ⇒ Object
Adds a section.
276 277 278 279 280 281 282 283 |
# File 'lib/doing/wwid.rb', line 276 def add_section(title) if @content.key?(title.cap_first) raise InvalidSection, %(section "#{title.cap_first}" already exists) end @content[title.cap_first] = { :original => "#{title}:", :items => [] } logger.info('New section:', %("#{title.cap_first}")) end |
#all_tags(items, opt: {}) ⇒ Object
653 654 655 656 657 |
# File 'lib/doing/wwid.rb', line 653 def (items, opt: {}) = [] items.each { |item| .concat(item.).uniq! } .sort end |
#archive(section = , options = {}) ⇒ Object
Move entries from a section to Archive or other specified section
1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 |
# File 'lib/doing/wwid.rb', line 1722 def archive(section = @config['current_section'], = {}) count = [:keep] || 0 destination = [:destination] || 'Archive' = [:tags] || [] bool = [: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 add_section('Archive') if destination =~ /^archive$/i && !sections.include?('Archive') destination = guess_section(destination) if sections.include?(destination) && (sections.include?(section) || archive_all) do_archive(section, destination, { count: count, tags: , bool: bool, search: [:search], label: [:label], before: [:before] }) write(doing_file) else raise InvalidArgument, 'Either source or destination does not exist' end end |
#autotag(text) ⇒ 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
1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 |
# File 'lib/doing/wwid.rb', line 1907 def autotag(text) return unless text return text unless @auto_tag original = text.dup = text.scan(/@\w+/).map { |t| t.sub(/^@/, '') } tagged = { whitelisted: [], synonyms: [], transformed: [], replaced: [] } @config['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 @config['autotag']['synonyms'].each do |tag, v| v.each do |word| next unless text =~ /\b#{word}\b/i unless .include?(tag) || tagged[:whitelisted].include?(tag) tagged[:synonyms].push(tag) tagged[:synonyms] = tagged[:synonyms].uniq end end end if @config['autotag'].key? 'transform' @config['autotag']['transform'].each do |tag| next unless tag =~ /\S+:\S+/ rx, r = tag.split(/:/) 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| 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? = tagged[:synonyms].concat(tagged[:transformed]) .sort! .uniq! text.() unless .empty? if text == original logger.debug('Autotag:', "no change to \"#{text}\"") else = tagged[:whitelisted].concat().concat(tagged[:replaced]) logger.debug('Autotag:', "added #{new_tags.log_tags} to \"#{text}\"") logger.count(:autotag, level: :info, count: 1, message: 'autotag updated %count %items') end text. end |
#choose_from(options, prompt: 'Make a selection: ', multiple: false, sorted: true, fzf_args: []) ⇒ String
Generate a menu of options and allow user selection
638 639 640 641 642 643 644 645 646 647 648 649 650 651 |
# File 'lib/doing/wwid.rb', line 638 def choose_from(, prompt: 'Make a selection: ', multiple: false, sorted: true, fzf_args: []) return nil unless $stdout.isatty # fzf_args << '-1' # User is expecting a menu, and even if only one it seves as confirmation fzf_args << %(--prompt "#{prompt}") fzf_args << '--multi' if multiple header = "esc: cancel,#{multiple ? ' tab: multi-select, ctrl-a: select all,' : ''} return: confirm" fzf_args << %(--header "#{header}") .sort! if sorted res = `echo #{Shellwords.escape(options.join("\n"))}|#{fzf} #{fzf_args.join(' ')}` return false if res.strip.size.zero? res end |
#choose_from_items(items, opt = {}, include_section: false) ⇒ Object
Create an interactive menu to select from a set of Items
860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 |
# File 'lib/doing/wwid.rb', line 860 def choose_from_items(items, opt = {}, include_section: false) return items unless $stdout.isatty return nil unless items.count.positive? opt[:case] ||= :smart opt[:header] ||= "Arrows: navigate, tab: mark for selection, ctrl-a: select all, enter: commit" opt[:prompt] ||= "Select entries to act on > " pad = items.length.to_s.length = items.map.with_index do |item, i| out = [ format("%#{pad}d", i), ') ', format('%13s', item.date.relative_date), ' | ', item.title ] if include_section out.concat([ ' (', item.section, ') ' ]) end out.join('') end fzf_args = [ %(--header="#{opt[:header]}"), %(--prompt="#{opt[:prompt].sub(/ *$/, ' ')}"), opt[:multiple] ? '--multi' : '--no-multi', '-0', '--bind ctrl-a:select-all', %(-q "#{opt[:query]}"), '--info=inline' ] fzf_args.push('-1') unless opt[:show_if_single] fzf_args << case opt[:case].normalize_case when :sensitive '+i' when :ignore '-i' end fzf_args << '-e' if opt[:exact] unless opt[:menu] raise InvalidArgument, "Can't skip menu when no query is provided" unless opt[:query] && !opt[:query].empty? fzf_args.concat([%(--filter="#{opt[:query]}"), opt[:sort] ? '' : '--no-sort']) end res = `echo #{Shellwords.escape(options.join("\n"))}|#{fzf} #{fzf_args.join(' ')}` selected = [] res.split(/\n/).each do |item| idx = item.match(/^ *(\d+)\)/)[1].to_i selected.push(items[idx]) end opt[:multiple] ? selected : selected[0] end |
#choose_section ⇒ String
Generate a menu of sections and allow user selection
1613 1614 1615 1616 |
# File 'lib/doing/wwid.rb', line 1613 def choose_section choice = choose_from(sections.sort, prompt: 'Choose a section > ', fzf_args: ['--height=60%']) choice ? choice.strip : choice end |
#choose_view ⇒ String
Generate a menu of views and allow user selection
1632 1633 1634 1635 |
# File 'lib/doing/wwid.rb', line 1632 def choose_view choice = choose_from(views.sort, prompt: 'Choose a view > ', fzf_args: ['--height=60%']) choice ? choice.strip : choice end |
#chronify(input, future: false, guess: :begin) ⇒ DateTime
Converts input string into a Time object when input takes on the following formats: - interval format e.g. '1d2h30m', '45m' etc. - a semantic phrase e.g. 'yesterday 5:30pm' - a strftime e.g. '2016-03-15 15:32:04 PDT'
208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 |
# File 'lib/doing/wwid.rb', line 208 def chronify(input, future: false, guess: :begin) now = Time.now raise InvalidTimeExpression, "Invalid time expression #{input.inspect}" if input.to_s.strip == '' secs_ago = if input.match(/^(\d+)$/) # plain number, assume minutes Regexp.last_match(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, { guess: guess, context: future ? :future : :past, ambiguous_time_range: 8 }) end end |
#chronify_qty(qty) ⇒ Integer
Converts simple strings into seconds that can be added to a Time object
238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 |
# File 'lib/doing/wwid.rb', line 238 def chronify_qty(qty) minutes = 0 case qty.strip when /^(\d+):(\d\d)$/ minutes += Regexp.last_match(1).to_i * 60 minutes += Regexp.last_match(2).to_i when /^(\d+(?:\.\d+)?)([hmd])?$/ amt = Regexp.last_match(1) type = Regexp.last_match(2).nil? ? 'm' : Regexp.last_match(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 |
#create(filename = nil) ⇒ Object
Create a new doing file
111 112 113 114 115 116 117 118 |
# File 'lib/doing/wwid.rb', line 111 def create(filename = nil) filename = @doing_file if filename.nil? return if File.exist?(filename) && File.stat(filename).size.positive? File.open(filename, 'w+') do |f| f.puts "#{@config['current_section']}:" end end |
#dedup(items, no_overlap = false) ⇒ Object
Remove items from a list that already exist in @content
463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 |
# File 'lib/doing/wwid.rb', line 463 def dedup(items, no_overlap = false) combined = [] @content.each do |_k, v| combined += v[:items] end items.delete_if do |item| duped = false combined.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_item(item, single: false) ⇒ Object
Delete an item from the index
1375 1376 1377 1378 1379 1380 1381 1382 |
# File 'lib/doing/wwid.rb', line 1375 def delete_item(item, single: false) section = item.section section_items = @content[section][:items] deleted = section_items.delete(item) logger.count(:deleted) logger.info('Entry deleted:', deleted.title) if single end |
#edit_last(section: 'All', options: {}) ⇒ Object
Edit the last entry
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 |
# File 'lib/doing/wwid.rb', line 1411 def edit_last(section: 'All', options: {}) [:section] = guess_section(section) item = last_entry() if item.nil? logger.debug('Skipped:', 'No entries found') return end content = [item.title.dup] content << item.note.to_s unless item.note.empty? new_item = fork_editor(content.join("\n")) title, note = format_input(new_item) if title.nil? || title.empty? logger.debug('Skipped:', 'No content provided') elsif title == item.title && note.equal?(item.note) logger.debug('Skipped:', 'No change in content') else item.title = title item.note.add(note, replace: true) logger.info('Edited:', item.title) write(@doing_file) end end |
#filter_items(items = [], opt: {}) ⇒ Object
Filter items based on search criteria
720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 |
# File 'lib/doing/wwid.rb', line 720 def filter_items(items = [], opt: {}) if items.nil? || items.empty? section = opt[:section] ? guess_section(opt[:section]) : 'All' items = if section =~ /^all$/i @content.each_with_object([]) { |(_k, v), arr| arr.concat(v[:items].dup) } else @content[section][:items].dup end end items.sort_by! { |item| [item.date, item.title.downcase] }.reverse filtered_items = items.select do |item| keep = true if opt[:unfinished] finished = item.('done', :and) finished = opt[:not] ? !finished : finished keep = false if finished end if keep && opt[:tag] opt[:tag_bool] ||= :and tag_match = opt[:tag].nil? || opt[:tag].empty? ? true : item.(opt[:tag], opt[:tag_bool]) keep = false unless tag_match keep = opt[:not] ? !keep : keep end if keep && opt[:search] search_match = if opt[:search].nil? || opt[:search].empty? true else item.search(opt[:search], case_type: opt[:case].normalize_case, fuzzy: opt[:fuzzy]) end keep = false unless search_match keep = opt[:not] ? !keep : keep end if keep && opt[:date_filter]&.length == 2 start_date = opt[:date_filter][0] end_date = opt[:date_filter][1] in_date_range = if end_date item.date >= start_date && item.date <= end_date else item.date.strftime('%F') == start_date.strftime('%F') end keep = false unless in_date_range keep = opt[:not] ? !keep : keep end keep = false if keep && opt[:only_timed] && !item.interval if keep && opt[:tag_filter] && !opt[:tag_filter]['tags'].empty? keep = item.(opt[:tag_filter]['tags'], opt[:tag_filter]['bool']) keep = opt[:not] ? !keep : keep end if keep && opt[:before] time_string = opt[:before] cutoff = chronify(time_string, guess: :begin) keep = cutoff && item.date <= cutoff keep = opt[:not] ? !keep : keep end if keep && opt[:after] time_string = opt[:after] cutoff = chronify(time_string, guess: :end) keep = cutoff && item.date >= cutoff keep = opt[:not] ? !keep : keep end if keep && opt[:today] keep = item.date >= Date.today.to_time && item.date < Date.today.next_day.to_time keep = opt[:not] ? !keep : keep elsif keep && opt[:yesterday] keep = item.date >= Date.today.prev_day.to_time && item.date < Date.today.to_time keep = opt[:not] ? !keep : keep end keep end count = opt[:count] && opt[:count].positive? ? opt[:count] : filtered_items.length if opt[:age] =~ /^o/i filtered_items.slice(0, count).reverse else filtered_items.reverse.slice(0, count) end end |
#fork_editor(input = '') ⇒ Object
Create a process for an editor and wait for the file handle to return
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 |
# File 'lib/doing/wwid.rb', line 125 def fork_editor(input = '') # 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', '.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("#{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
173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 |
# File 'lib/doing/wwid.rb', line 173 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? 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+\((.*?)\)$/) do m = Regexp.last_match note.add(m[1]) '' end end note.strip_lines! note.compress [title, note] end |
#format_time(seconds, human: false) ⇒ Object
Format human readable time from seconds
2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 |
# File 'lib/doing/wwid.rb', line 2166 def format_time(seconds, human: false) return [0, 0, 0] if seconds.nil? if seconds.class == String && seconds =~ /(\d+):(\d+):(\d+)/ h = Regexp.last_match(1) m = Regexp.last_match(2) s = Regexp.last_match(3) seconds = (h.to_i * 60 * 60) + (m.to_i * 60) + s.to_i end minutes = (seconds / 60).to_i hours = (minutes / 60).to_i if human minutes = (minutes % 60).to_i [0, hours, minutes] else days = (hours / 24).to_i hours = (hours % 24).to_i minutes = (minutes % 60).to_i [days, hours, minutes] end end |
#fuzzy_filter_items(items, opt: {}) ⇒ Object
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 |
# File 'lib/doing/wwid.rb', line 671 def fuzzy_filter_items(items, opt: {}) scannable = items.map.with_index { |item, idx| "#{item.title} #{item.note.join(' ')}".gsub(/[|*?!]/, '') + "|#{idx}" }.join("\n") fzf_args = [ '--multi', %(--filter="#{opt[:search].sub(/^'?/, "'")}"), '--no-sort', '-d "\|"', '--nth=1' ] if opt[:case] fzf_args << case opt[:case].normalize_case when :sensitive '+i' when :ignore '-i' end end # fzf_args << '-e' if opt[:exact] # puts fzf_args.join(' ') res = `echo #{Shellwords.escape(scannable)}|#{fzf} #{fzf_args.join(' ')}` selected = [] res.split(/\n/).each do |item| idx = item.match(/\|(\d+)$/)[1].to_i selected.push(items[idx]) end selected end |
#fzf ⇒ Object
614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 |
# File 'lib/doing/wwid.rb', line 614 def fzf fzf_dir = File.join(File.dirname(__FILE__), '../helpers/fzf') FileUtils.mkdir_p(fzf_dir) unless File.directory?(fzf_dir) fzf_bin = File.join(fzf_dir, 'bin/fzf') return fzf_bin if File.exist?(fzf_bin) Doing.logger.log_now(:warn, 'Compiling and installing FZF -- this will only happen once') Doing.logger.log_now(:warn, 'fzf is copyright Junegunn Choi <https://github.com/junegunn/fzf/blob/master/LICENSE>') res = system("#{fzf_dir}/install --bin --no-key-bindings --no-completion --no-update-rc --no-bash --no-zsh --no-fish") unless res Doing.logger.log_now(:warn, 'Error installing, trying again as root') system("sudo #{fzf_dir}/install --bin --no-key-bindings --no-completion --no-update-rc --no-bash --no-zsh --no-fish") end raise RuntimeError.new('Error installing fzf, please report at https://github.com/ttscoff/doing/issues') unless File.exist?(fzf_bin) fzf_bin end |
#get_interval(item, formatted: true, record: true) ⇒ Object
Gets the interval between entry's start date and @done date
2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 |
# File 'lib/doing/wwid.rb', line 2149 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? ? format('%02d:%02d:%02d', *format_time(seconds)) : false end false end |
#get_view(title) ⇒ Object
Gets a view from configuration
1642 1643 1644 1645 1646 |
# File 'lib/doing/wwid.rb', line 1642 def get_view(title) return @config['views'][title] if @config['views'].has_key?(title) false end |
#guess_section(frag, guessed: false, suggest: false) ⇒ Object
Attempt to match a string with an existing section
291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 |
# File 'lib/doing/wwid.rb', line 291 def guess_section(frag, guessed: false, suggest: false) return 'All' if frag =~ /^all$/i frag ||= @config['current_section'] sections.each { |sect| return sect.cap_first if frag.downcase == sect.downcase } section = false re = frag.split('').join('.*?') sections.each do |sect| next unless sect =~ /#{re}/i logger.debug('Match:', %(Assuming "#{sect}" from "#{frag}")) section = sect break end return section if suggest unless section || guessed alt = guess_view(frag, guessed: true, suggest: true) if alt meant_view = yn("#{Color.boldwhite}Did you mean `#{Color.yellow}doing view #{alt}#{Color.boldwhite}`?", default_response: 'n') raise WrongCommand.new("run again with #{"doing view #{alt}".boldwhite}", topic: 'Try again:') if meant_view end res = yn("#{Color.boldwhite}Section #{frag.yellow}#{Color.boldwhite} not found, create it", default_response: 'n') if res add_section(frag.cap_first) write(@doing_file) return frag.cap_first end raise InvalidSection.new("unknown section #{frag.yellow}", 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
390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 |
# File 'lib/doing/wwid.rb', line 390 def guess_view(frag, guessed: false, suggest: false) views.each { |view| return view if frag.downcase == view.downcase } view = false re = frag.split('').join('.*?') 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) meant_view = yn("Did you mean `doing show #{alt}`?", default_response: 'n') raise WrongCommand.new("run again with #{"doing show #{alt}".yellow}", topic: 'Try again:') if meant_view raise InvalidView.new(%(unkown view #{alt.yellow}), topic: 'Missing:') end view end |
#import(paths, opt = {}) ⇒ Object
Imports external entries
488 489 490 491 492 493 494 495 496 497 498 499 500 501 |
# File 'lib/doing/wwid.rb', line 488 def import(paths, opt = {}) Plugins.plugins[:import].each do |_, | next unless opt[:type] =~ /^(#{options[:trigger].normalize_trigger})$/i if paths.count.positive? paths.each do |path| [:class].import(self, path, options: opt) end else [:class].import(self, nil, options: opt) end break end end |
#init_doing_file(path = nil) ⇒ Object
Initializes the doing file.
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 |
# File 'lib/doing/wwid.rb', line 52 def init_doing_file(path = nil) @doing_file = File.(@config['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 elsif File.exist?(File.(path)) && File.file?(File.(path)) && File.stat(File.(path)).size.positive? @doing_file = File.(path) input = IO.read(File.(path)) input = input.force_encoding('utf-8') if input.respond_to? :force_encoding elsif path.length < 256 @doing_file = File.(path) create(path) input = IO.read(File.(path)) 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 do |line| next if line =~ /^\s*$/ if line =~ /^(\S[\S ]+):\s*(@\S+\s*)*$/ section = Regexp.last_match(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 = Regexp.last_match(1).strip title = Regexp.last_match(2).strip item = Item.new(date, title, section) @content[section][:items].push(item) current += 1 elsif current.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[section][:items][current - 1] prev_item.note = Note.new unless prev_item.note prev_item.note.add(line) # end end end Hooks.trigger :post_read, self end |
#interactive(opt = {}) ⇒ Object
Display an interactive menu of entries
Options hash is shared with #filter_items and #act_on
820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 |
# File 'lib/doing/wwid.rb', line 820 def interactive(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[:not] opt[:multiple] = true opt[:show_if_single] = true items = filter_items([], opt: { section: section, search: opt[:search], fuzzy: opt[:fuzzy], case: opt[:case], not: opt[:not] }) selection = choose_from_items(items, opt, include_section: section =~ /^all$/i) 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
1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 |
# File 'lib/doing/wwid.rb', line 1868 def last(times: true, section: nil, options: {}) section = section.nil? || section =~ /all/i ? 'All' : guess_section(section) cfg = @config['templates']['last'].deep_merge(@config['templates']['default']).deep_merge({ 'wrap_width' => @config['wrap_width'] || 0, 'date_format' => @config['default_date_format'], 'order' => @config['order'] || 'asc', 'tags_color' => @config['tags_color'] }) opts = { section: section, wrap_width: cfg['wrap_width'], count: 1, format: cfg['date_format'], template: cfg['template'], times: times } if [:tag] opts[:tag_filter] = { 'tags' => [:tag], 'bool' => [:tag_bool] } end opts[:search] = [:search] if [:search] opts[:case] = [:case] opts[:not] = [:negate] opts[:config_template] = 'last' list_section(opts) end |
#last_entry(opt = {}) ⇒ Object
Get the last entry
590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 |
# File 'lib/doing/wwid.rb', line 590 def last_entry(opt = {}) opt[:tag_bool] ||= :and opt[:section] ||= @config['current_section'] items = filter_items([], opt: opt) logger.debug('Filtered:', "Parameters matched #{items.count} entries") if opt[:interactive] last_entry = choose_from_items(items, { menu: true, header: '', prompt: 'Select an entry > ', multiple: false, sort: false, show_if_single: true }, include_section: opt[:section] =~ /^all$/i ) 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
509 510 511 512 513 514 515 516 517 518 519 520 |
# File 'lib/doing/wwid.rb', line 509 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
1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 |
# File 'lib/doing/wwid.rb', line 1790 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 dates = [dates, dates] if dates.instance_of?(String) list_section({ section: section, count: 0, order: 'asc', date_filter: dates, times: times, output: output, totals: opt[:totals], sort_tags: opt[:sort_tags], config_template: 'default' }) end |
#list_section(opt = {}) ⇒ Object
Display contents of a section based on options
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 1682 1683 1684 1685 1686 1687 1688 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 |
# File 'lib/doing/wwid.rb', line 1653 def list_section(opt = {}) opt[:config_template] ||= 'default' cfg = @config.dig('templates', opt[:config_template]).deep_merge({ 'wrap_width' => @config['wrap_width'] || 0, 'date_format' => @config['default_date_format'], 'order' => @config['order'] || 'asc', 'tags_color' => @config['tags_color'] }) opt[:count] ||= 0 opt[:age] ||= 'newest' opt[:format] ||= cfg['date_format'] opt[:order] ||= cfg['order'] || 'asc' opt[:tag_order] ||= 'asc' if opt[:tags_color].nil? opt[:tags_color] = cfg['tags_color'] || false end opt[:template] ||= cfg['template'] # opt[:highlight] ||= true title = '' is_single = true if opt[:section].nil? opt[:section] = choose_section title = opt[:section] elsif opt[:section].instance_of?(String) if opt[:section] =~ /^all$/i title = 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 title = guess_section(opt[:section]) end end items = filter_items([], opt: opt).reverse items.reverse! if opt[:order] =~ /^d/i if opt[:interactive] opt[:menu] = !opt[:force] opt[:query] = '' # opt[:search] opt[:multiple] = true selected = choose_from_items(items, opt, include_section: opt[:section] =~ /^all$/i ) raise NoResults, 'no items selected' if selected.empty? act_on(selected, opt) return end opt[:output] ||= 'template' opt[:wrap_width] ||= @config['templates']['default']['wrap_width'] || 0 output(items, title, is_single, opt) end |
#logger ⇒ Object
Logger
Responds to :debug, :info, :warn, and :error
Each method takes a topic, and a message or block
Example: debug('Hooks', 'Hook 1 triggered')
43 44 45 |
# File 'lib/doing/wwid.rb', line 43 def logger @logger ||= Doing.logger end |
#move_item(item, section, label: true) ⇒ Item
Move item from current section to destination section
1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 |
# File 'lib/doing/wwid.rb', line 1339 def move_item(item, section, label: true) from = item.section new_item = @content[item.section][:items].delete(item) new_item.title.sub!(/(?:@from\(.*?\))?(.*)$/, "\\1 @from(#{from})") if label new_item.section = section @content[section][:items].concat([new_item]) logger.count(section == 'Archive' ? :archived : :moved) logger.debug("#{section == 'Archive' ? 'Archived' : 'Moved'}:", "#{new_item.title.truncate(60)} from #{from} to #{section}") new_item end |
#next_item(item, options = {}) ⇒ Item
Get next item in the index
1362 1363 1364 1365 1366 1367 1368 |
# File 'lib/doing/wwid.rb', line 1362 def next_item(item, = {}) items = filter_items([], opt: ) idx = items.index(item) idx.positive? ? items[idx - 1] : nil end |
#recent(count = 10, section = nil, opt = {}) ⇒ Object
Show recent entries
1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 |
# File 'lib/doing/wwid.rb', line 1842 def recent(count = 10, section = nil, opt = {}) times = opt[:t] || true opt[:totals] ||= false opt[:sort_tags] ||= false cfg = @config['templates']['recent'].deep_merge(@config['templates']['default']).deep_merge({ 'wrap_width' => @config['wrap_width'] || 0, 'date_format' => @config['default_date_format'], 'order' => @config['order'] || 'asc', 'tags_color' => @config['tags_color'] }) section ||= @config['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], tags_color: opt[:tags_color], config_template: 'recent' }) end |
#repeat_item(item, opt = {}) ⇒ Object
531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 |
# File 'lib/doing/wwid.rb', line 531 def repeat_item(item, opt = {}) original = item.dup if item.should_finish? if item.should_time? item.title.tag!('done', value: Time.now.strftime('%F %R')) else item.title.tag!('done') end end # Remove @done tag title = item.title.sub(/\s*@done(\(.*?\))?/, '').chomp section = opt[:in].nil? ? item.section : guess_section(opt[:in]) @auto_tag = false note = opt[:note] || Note.new if opt[:editor] to_edit = title to_edit += "\n#{note.to_s}" unless note.empty? new_item = fork_editor(to_edit) title, note = format_input(new_item) if title.nil? || title.empty? logger.warn('Skipped:', 'No content provided') return end end update_item(original, item) add_item(title, section, { note: note, back: opt[:date], timed: true }) write(@doing_file) end |
#repeat_last(opt = {}) ⇒ Object
Restart the last entry
570 571 572 573 574 575 576 577 578 579 580 581 582 583 |
# File 'lib/doing/wwid.rb', line 570 def repeat_last(opt = {}) opt[:section] ||= 'all' 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) end |
#reset_item(item, resume: false) ⇒ Object
522 523 524 525 526 527 528 529 |
# File 'lib/doing/wwid.rb', line 522 def reset_item(item, resume: false) item.date = Time.now if resume item.tag('done', remove: true) end logger.info('Reset:', %(Reset #{resume ? 'and resumed ' : ''} "#{item.title}" in #{item.section})) item end |
#restore_backup(file) ⇒ Object
Restore a backed up version of a file
1516 1517 1518 1519 1520 1521 1522 1523 |
# File 'lib/doing/wwid.rb', line 1516 def restore_backup(file) if File.exist?("#{file}~") FileUtils.cp("#{file}~", file) logger.warn('File update:', "Restored #{file.sub(/^#{@user_home}/, '~')}") else logger.error('Restore error:', 'No backup file found') end end |
#rotate(opt = {}) ⇒ Object
Rename doing file with date and start fresh one
1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 |
# File 'lib/doing/wwid.rb', line 1528 def rotate(opt = {}) keep = opt[:keep] || 0 = [] .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' if sect =~ /^all$/i all_sections = sections.dup else all_sections = [sect] end counter = 0 new_content = {} all_sections.each do |section| items = @content[section][:items].dup new_content[section] = {} new_content[section][:original] = @content[section][:original] new_content[section][:items] = [] moved_items = [] if !.empty? || opt[:search] || opt[:before] if opt[:before] time_string = opt[:before] cutoff = chronify(time_string, guess: :begin) end items.delete_if do |item| if ((!.empty? && item.(, bool)) || (opt[:search] && item.search(opt[:search].to_s)) || (opt[:before] && item.date < cutoff)) moved_items.push(item) counter += 1 true else false end end @content[section][:items] = items new_content[section][:items] = moved_items logger.warn('Rotated:', "#{moved_items.length} items from #{section}") else new_content[section][:items] = [] moved_items = [] count = items.length < keep ? items.length : keep if items.count > count moved_items.concat(items[count..-1]) else moved_items.concat(items) end @content[section][:items] = if count.zero? [] else items[0..count - 1] end new_content[section][:items] = moved_items logger.warn('Rotated:', "#{items.length - count} items from #{section}") end 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.deep_merge(new_content) 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 |
#sections ⇒ Array
List sections
267 268 269 |
# File 'lib/doing/wwid.rb', line 267 def sections @content.keys 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)
1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 |
# File 'lib/doing/wwid.rb', line 1449 def stop_start(target_tag, opt = {}) tag = target_tag.dup opt[:section] ||= @config['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 do |item, i| next unless item.title =~ /@#{tag}/ item.title.([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})") move_item(item, 'Archive', label: false) logger.count(:completed_archived) logger.info('Completed/archived:', item.title) else logger.count(:completed) logger.info('Completed:', item.title) end end logger.debug('Skipped:', "No active @#{tag} tasks found.") if found_items.zero? if opt[:new_item] title, note = format_input(opt[:new_item]) 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
659 660 661 662 663 664 665 666 667 668 669 |
# File 'lib/doing/wwid.rb', line 659 def tag_groups(items, opt: {}) all_items = filter_items(items, opt: opt) = (all_items, opt: {}) tag_groups = {} .each do |tag| tag_groups[tag] ||= [] tag_groups[tag] = filter_items(all_items, opt: { tag: tag, tag_bool: :or }) end tag_groups end |
#tag_item(item, tags, remove: false, date: false, single: false) ⇒ Item
Tag an item from the index
1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 |
# File 'lib/doing/wwid.rb', line 1183 def tag_item(item, , remove: false, date: false, single: false) added = [] removed = [] = . if .is_a? ::String done_date = Time.now .each do |tag| bool = remove ? :and : :not if item.(tag, bool) item.tag(tag, remove: remove, value: date ? done_date.strftime('%F %R') : nil) remove ? removed.push(tag) : added.push(tag) end end log_change(tags_added: added, tags_removed: removed, count: 1, item: item, single: single) item end |
#tag_last(opt = {}) ⇒ Object
Tag the last entry or X entries
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 |
# File 'lib/doing/wwid.rb', line 1213 def tag_last(opt = {}) opt[:count] ||= 1 opt[:archive] ||= false opt[:tags] ||= ['done'] opt[:sequential] ||= false opt[:date] ||= false opt[:remove] ||= false opt[:autotag] ||= false opt[:back] ||= false opt[:unfinished] ||= false opt[:section] = opt[:section] ? guess_section(opt[:section]) : 'All' items = filter_items([], opt: opt) if opt[:interactive] items = choose_from_items(items, { menu: true, header: '', prompt: 'Select entries to tag > ', multiple: true, sort: true, show_if_single: true }, include_section: opt[:section] =~ /^all$/i) raise NoResults, 'no items selected' if items.empty? end raise NoResults, 'no items matched your search' if items.empty? items.each do |item| added = [] removed = [] if opt[:autotag] new_title = autotag(item.title) if @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[:sequential] next_entry = next_item(item) done_date = if next_entry.nil? Time.now else next_entry.date - 60 end elsif opt[:took] if item.date + opt[:took] > Time.now item.date = Time.now - opt[:took] done_date = Time.now else done_date = item.date + opt[:took] end elsif opt[:back] done_date = if opt[:back].is_a? Integer item.date + opt[:back] else item.date + (opt[:back] - item.date) end else done_date = Time.now 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 opt[:remove] || opt[:rename] rename_to = nil if opt[:rename] rename_to = tag tag = opt[:rename] end old_title = item.title.dup item.title.tag!(tag, remove: opt[:remove], rename_to: rename_to, regex: opt[:regex]) 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 item.title.tag!(tag, value: should_date ? done_date.strftime('%F %R') : nil) added << tag if old_title != item.title end end end 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? move_item(item, 'Archive', label: true) elsif opt[:archive] && opt[:count].zero? logger.warn('Skipped:', 'Archiving is skipped when operating on all entries') end end write(@doing_file) end |
#tag_times(format: :text, sort_by_name: false, sort_order: 'asc') ⇒ Object
Get total elapsed time for all tags in selection
2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 |
# File 'lib/doing/wwid.rb', line 2008 def tag_times(format: :text, sort_by_name: false, sort_order: 'asc') return '' if @timers.empty? max = @timers.keys.sort_by { |k| k.length }.reverse[0].length + 1 total = @timers.delete('All') = @timers.delete_if { |_k, v| v == 0 } = if sort_by_name .sort_by { |k, _v| k } else .sort_by { |_k, v| v } end .reverse! if sort_order =~ /^asc/i case format when :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" .reverse.each do |k, v| if v > 0 output += "<tr><td style='text-align:left;'>#{k}</td><td style='text-align:left;'>#{'%02d:%02d:%02d' % format_time(v)}</td></tr>\n" end end 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' % format_time(total)}</td>\n </tr>\n </tfoot>\n </table>\n" output + tail when :markdown pad = .map {|k, v| k }.group_by(&:size).max.last[0].length output = " | \#{' ' * (pad - 7) }project | time |\n | \#{'-' * (pad - 1)}: | :------- |\n EOS\n sorted_tags_data.reverse.each do |k, v|\n if v > 0\n output += \"| \#{' ' * (pad - k.length)}\#{k} | \#{'%02d:%02d:%02d' % format_time(v)} |\\n\"\n end\n end\n tail = \"[Tag Totals]\"\n output + tail\n when :json\n output = []\n sorted_tags_data.reverse.each do |k, v|\n d, h, m = format_time(v)\n output << {\n 'tag' => k,\n 'seconds' => v,\n 'formatted' => format('%<d>02d:%<h>02d:%<m>02d', d: d, h: h, m: m)\n }\n end\n output\n when :human\n output = []\n sorted_tags_data.reverse.each do |k, v|\n spacer = ''\n (max - k.length).times do\n spacer += ' '\n end\n _d, h, m = format_time(v, human: true)\n output.push(\"\u2503 \#{spacer}\#{k}:\#{format('%<h> 4dh %<m>02dm', h: h, m: m)} \u2503\")\n end\n\n header = '\u250F\u2501\u2501 Tag Totals '\n (max - 2).times { header += '\u2501' }\n header += '\u2513'\n footer = '\u2517'\n (max + 12).times { footer += '\u2501' }\n footer += '\u251B'\n divider = '\u2523'\n (max + 12).times { divider += '\u2501' }\n divider += '\u252B'\n output = output.empty? ? '' : \"\\n\#{header}\\n\#{output.join(\"\\n\")}\"\n d, h, m = format_time(total, human: true)\n output += \"\\n\#{divider}\"\n spacer = ''\n (max - 6).times do\n spacer += ' '\n end\n total = \"\u2503 \#{spacer}total: \"\n total += format('%<h> 4dh %<m>02dm', h: h, m: m)\n total += ' \u2503'\n output += \"\\n\#{total}\"\n output += \"\\n\#{footer}\"\n output\n else\n output = []\n sorted_tags_data.reverse.each do |k, v|\n spacer = ''\n (max - k.length).times do\n spacer += ' '\n end\n d, h, m = format_time(v)\n output.push(\"\#{k}:\#{spacer}\#{format('%<d>02d:%<h>02d:%<m>02d', d: d, h: h, m: m)}\")\n end\n\n output = output.empty? ? '' : \"\\n--- Tag Totals ---\\n\#{output.join(\"\\n\")}\"\n d, h, m = format_time(total)\n output += \"\\n\\nTotal tracked: \#{format('%<d>02d:%<h>02d:%<m>02d', d: d, h: h, m: m)}\\n\"\n output\n end\nend\n" |
#today(times = true, output = nil, opt = {}) ⇒ Object
Show all entries from the current day
1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 |
# File 'lib/doing/wwid.rb', line 1751 def today(times = true, output = nil, opt = {}) opt[:totals] ||= false opt[:sort_tags] ||= false cfg = @config['templates']['today'].deep_merge(@config['templates']['default']).deep_merge({ 'wrap_width' => @config['wrap_width'] || 0, 'date_format' => @config['default_date_format'], 'order' => @config['order'] || 'asc', 'tags_color' => @config['tags_color'] }) = { after: opt[:after], before: opt[:before], count: 0, format: cfg['date_format'], order: cfg['order'] || 'asc', output: output, section: opt[:section], sort_tags: opt[:sort_tags], template: cfg['template'], times: times, today: true, totals: opt[:totals], wrap_width: cfg['wrap_width'], tags_color: cfg['tags_color'], config_template: 'today' } list_section() end |
#update_item(old_item, new_item) ⇒ Object
Update an item in the index with a modified item
1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 |
# File 'lib/doing/wwid.rb', line 1390 def update_item(old_item, new_item) section = old_item.section section_items = @content[section][:items] s_idx = section_items.index { |item| item.equal?(old_item) } raise ItemNotFound, 'Unable to find item in index, did it mutate?' unless s_idx return if section_items[s_idx].equal?(new_item) section_items[s_idx] = new_item logger.count(:updated) logger.info('Entry updated:', section_items[s_idx].title.truncate(60)) new_item end |
#views ⇒ Array
List available views
1623 1624 1625 |
# File 'lib/doing/wwid.rb', line 1623 def views @config.has_key?('views') ? @config['views'].keys : [] end |
#write(file = nil, backup: true) ⇒ Object
Write content to file or STDOUT
1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 |
# File 'lib/doing/wwid.rb', line 1499 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 @config.key?('run_after') end end |
#yesterday(section, times = nil, output = nil, opt = {}) ⇒ Object
Show entries from the previous day
1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 |
# File 'lib/doing/wwid.rb', line 1809 def yesterday(section, times = nil, output = nil, opt = {}) opt[:totals] ||= false opt[:sort_tags] ||= false 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] = { after: opt[:after], before: opt[:before], count: 0, order: opt[:order], output: output, section: section, sort_tags: opt[:sort_tags], tag_order: opt[:tag_order], times: times, totals: opt[:totals], yesterday: true, config_template: 'today' } list_section() end |
#yn(question, default_response: false) ⇒ Bool
Ask a yes or no question in the terminal
340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 |
# File 'lib/doing/wwid.rb', line 340 def yn(question, default_response: false) if default_response.is_a?(String) default = default_response =~ /y/i ? true : false else default = default_response end # if global --default is set, answer default return default if @default_option # if this isn't an interactive shell, answer default return default unless $stdout.isatty # clear the buffer if ARGV&.length ARGV.length.times do ARGV.shift end end system 'stty cbreak' cw = Color.white cbw = Color.boldwhite cbg = Color.boldgreen cd = Color.default = unless default.nil? "#{cw}[#{default ? "#{cbg}Y#{cw}/#{cbw}n" : "#{cbw}y#{cw}/#{cbg}N"}#{cw}]#{cd}" else "#{cw}[#{cbw}y#{cw}/#{cbw}n#{cw}]#{cd}" end $stdout.syswrite "#{cbw}#{question.sub(/\?$/, '')} #{options}#{cbw}?#{cd} " res = $stdin.sysread 1 puts system 'stty cooked' res.chomp! res.downcase! return default if res.empty? res =~ /y/i ? true : false end |