Class: MPS::CLI::MPS

Inherits:
Thor
  • Object
show all
Includes:
Thor::Actions
Defined in:
lib/cli/mps.rb

Constant Summary collapse

VALID_TYPES =
%w[task note log reminder].freeze

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.exit_on_failure?Boolean

Returns:

  • (Boolean)


21
22
23
# File 'lib/cli/mps.rb', line 21

def self.exit_on_failure?
  true
end

Instance Method Details

#append(type, *body_parts) ⇒ Object



95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
# File 'lib/cli/mps.rb', line 95

def append(type, *body_parts)
  init
  begin
    type = type.downcase
    unless VALID_TYPES.include?(type)
      raise Thor::Error, "Unknown type '#{type}'. Valid: #{VALID_TYPES.join(', ')}"
    end
    body  = body_parts.join(" ")
    tags  = options[:tags]&.split(",")&.map(&:strip) || []
    attrs = {}
    attrs[:status] = options[:status]     if options[:status]
    attrs[:at]     = options[:at]          if options[:at]
    attrs[:start]  = options[:start_time]  if options[:start_time]
    attrs[:end]    = options[:end_time]    if options[:end_time]

    store = ::MPS::Store.new(@config.storage_dir)
    path  = store.append(type: type, body: body, tags: tags, attrs: attrs)
    say_status :appended, "#{type_badge(type)} #{body}", :green
    @config.logger.info("Appended #{type} to #{File.basename(path)}\n")
  rescue StandardError => e
    raise Thor::Error, e
  end
end

#autogitObject



296
297
298
299
300
301
302
303
304
305
306
# File 'lib/cli/mps.rb', line 296

def autogit
  init
  begin
    cmd = "git add . && git commit -m \"$(date)\" && " \
          "git pull #{@config.git_remote} #{@config.git_branch} && " \
          "git push #{@config.git_remote} #{@config.git_branch}"
    inside(@config.storage_dir) { run cmd }
  rescue StandardError => e
    raise Thor::Error, e
  end
end

#cmd(*commands) ⇒ Object



309
310
311
312
313
314
315
316
317
# File 'lib/cli/mps.rb', line 309

def cmd(*commands)
  init
  begin
    cmds = commands.map { |c| c.include?(" ") ? "\"#{c}\"" : c }
    inside(@config.storage_dir) { run cmds.join(" ") }
  rescue StandardError => e
    raise Thor::Error, e
  end
end

#export(datesign = "today") ⇒ Object



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
# File 'lib/cli/mps.rb', line 228

def export(datesign = "today")
  init
  begin
    store = ::MPS::Store.new(@config.storage_dir)
    date  = ::MPS.get_date(datesign)
    dates = options[:since] ? date_range(options[:since], date) : [date.to_date]
    fmt   = options[:format].downcase

    unless %w[json csv].include?(fmt)
      raise Thor::Error, "Unknown format '#{fmt}'. Use: json, csv"
    end

    records = []
    dates.each do |d|
      store.parse_date(d).each do |ref, el|
        next if el.is_a?(::MPS::Elements::MPS)
        next if options[:type] && el.class::SIGNATURE_STAMP != options[:type].downcase
        extra = el.parsed_args.reject { |k, _| k == :tags }
        records << {
          date:  d.strftime("%Y-%m-%d"),
          ref:   ref,
          type:  el.class::SIGNATURE_STAMP,
          tags:  el.tags.join(","),
          body:  el.body_str.strip
        }.merge(extra)
      end
    end

    if fmt == "json"
      say JSON.pretty_generate(records)
    else
      keys = %i[date ref type tags body] +
             (records.flat_map(&:keys) - %i[date ref type tags body]).uniq
      say CSV.generate { |csv|
        csv << keys.map(&:to_s)
        records.each { |r| csv << keys.map { |k| r[k] } }
      }
    end
  rescue StandardError => e
    raise Thor::Error, e
  end
end

#git(*commands) ⇒ Object



274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
# File 'lib/cli/mps.rb', line 274

def git(*commands)
  init
  begin
    git_command = if commands.first == "auto"
      "git add . && git commit -m \"$(date)\" && " \
      "git pull #{@config.git_remote} #{@config.git_branch} && " \
      "git push #{@config.git_remote} #{@config.git_branch}"
    elsif commands.first == "autocommit"
      "git add . && git commit -m \"$(date)\""
    elsif commands.size > 0
      cmds = commands.map { |c| c.include?(" ") ? "\"#{c}\"" : c }
      "git #{cmds.join(' ')}"
    else
      "git status"
    end
    inside(@config.storage_dir) { run git_command }
  rescue StandardError => e
    raise Thor::Error, e
  end
end

#list(datesign = "today") ⇒ Object



67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
# File 'lib/cli/mps.rb', line 67

def list(datesign = "today")
  init
  begin
    store = ::MPS::Store.new(@config.storage_dir)
    date  = ::MPS.get_date(datesign)
    dates = options[:since] ? date_range(options[:since], date) : [date.to_date]

    shown = 0
    dates.each do |d|
      all = store.parse_date(d)
      next if all.empty?
      say set_color("── #{d.strftime('%Y-%m-%d')} ─────────────", :white) if dates.size > 1
      shown += print_tree(all, options)
    end
    say set_color("(no elements found)", :yellow) if shown.zero?
  rescue StandardError => e
    raise Thor::Error, e
  end
end

#open(datesign = "today") ⇒ Object



35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
# File 'lib/cli/mps.rb', line 35

def open(datesign = "today")
  init
  begin
    date  = ::MPS.get_date(datesign)
    store = ::MPS::Store.new(@config.storage_dir)
    files = store.find_files(date)
    file_path = if files.size > 1
      ::CLI::UI::Prompt.ask("#{files.size} files found:") do |h|
        files.each { |f| h.option(File.basename(f)) { |_| f } }
      end
    else
      store.find_or_create_path(date)
    end
    @config.logger.info("Open MPS in text editor\n")
    written = ::MPS.open_editor(file_path)
    @config.logger.info("Done written Size: #{written} bytes\n")
    say_status :written, "#{written} bytes", :green
  rescue StandardError => e
    raise Thor::Error, e
  end
end

#search(query) ⇒ Object



125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
# File 'lib/cli/mps.rb', line 125

def search(query)
  init
  begin
    store      = ::MPS::Store.new(@config.storage_dir)
    since_date = options[:since] ? ::MPS.get_date(options[:since]).to_date : nil
    results    = store.search(
      query,
      type_filter: options[:type]&.downcase,
      tag_filter:  options[:tag],
      since_date:  since_date
    )
    if results.empty?
      say set_color("No results for '#{query}'", :yellow)
      return
    end
    results.each do |r|
      el       = r[:element]
      tags_str = el.tags.empty? ? "" : " #{set_color("[#{el.tags.join(', ')}]", :white)}"
      body_line = el.body_str.strip.lines.first&.strip
      say "#{set_color(r[:date_str], :white)} #{type_badge(el.class::SIGNATURE_STAMP)} " \
          "#{element_extra(el)}#{body_line}#{tags_str}"
    end
    say set_color("(#{results.size} result#{results.size == 1 ? '' : 's'})", :white)
  rescue StandardError => e
    raise Thor::Error, e
  end
end

#stats(datesign = "today") ⇒ Object



158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
# File 'lib/cli/mps.rb', line 158

def stats(datesign = "today")
  init
  begin
    store  = ::MPS::Store.new(@config.storage_dir)
    date   = ::MPS.get_date(datesign)
    dates  = options[:since] ? date_range(options[:since], date) : [date.to_date]

    total  = Hash.new(0)
    total_log_mins = 0
    any = false

    dates.each do |d|
      elements = store.parse_date(d).values
                   .reject { |e| e.is_a?(::MPS::Elements::MPS) }
      next if elements.empty?
      any = true
      counts   = elements.group_by { |e| e.class::SIGNATURE_STAMP }.transform_values(&:size)
      log_mins = elements.select { |e| e.is_a?(::MPS::Elements::Log) }
                         .sum { |e| e.duration_minutes || 0 }
      tasks    = elements.select { |e| e.is_a?(::MPS::Elements::Task) }

      parts = []
      if (n = counts["task"])
        open_n = tasks.count(&:open?)
        done_n = tasks.count(&:done?)
        parts << "#{n} task#{n != 1 ? 's' : ''} " \
                 "(#{set_color("#{open_n} open", :yellow)}, " \
                 "#{set_color("#{done_n} done", :green)})"
      end
      parts << "#{counts['note']} note#{counts['note'] != 1 ? 's' : ''}"       if counts["note"]
      parts << "#{counts['reminder']} reminder#{counts['reminder'] != 1 ? 's':''}" if counts["reminder"]
      if (n = counts["log"])
        h, m = log_mins.divmod(60)
        dur  = log_mins > 0 ? " (#{h}h#{m > 0 ? "#{m}m" : ""})" : ""
        parts << "#{n} log#{n != 1 ? 's' : ''}#{dur}"
      end

      say "#{set_color(d.strftime('%Y-%m-%d'), :white)}#{parts.join(', ')}"
      counts.each { |k, v| total[k] += v }
      total_log_mins += log_mins
    end

    say set_color("(no data found)", :yellow) unless any

    if dates.size > 1 && any
      say set_color("" * 44, :white)
      tparts = []
      tparts << "#{total['task']} tasks"      if total["task"] > 0
      tparts << "#{total['note']} notes"      if total["note"] > 0
      tparts << "#{total['reminder']} reminders" if total["reminder"] > 0
      if total["log"] > 0
        h, m = total_log_mins.divmod(60)
        dur  = total_log_mins > 0 ? " (#{h}h#{m > 0 ? "#{m}m" : ""} total)" : ""
        tparts << "#{total['log']} logs#{dur}"
      end
      say "Total: #{tparts.join(', ')}"
    end
  rescue StandardError => e
    raise Thor::Error, e
  end
end

#versionObject



28
29
30
# File 'lib/cli/mps.rb', line 28

def version
  say "mps (v#{::MPS::VERSION})"
end