Method: Doing::WWID#rotate

Defined in:
lib/doing/wwid/filetools.rb

#rotate(opt) ⇒ Object

Rename doing file with date and start fresh one



105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
# File 'lib/doing/wwid/filetools.rb', line 105

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

  section = guess_section(sect)

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

  counter = 0
  new_content = Items.new

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

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

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

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

  write(@doing_file)

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

  write(file, backup: false)
end