Class: Tasku::CLI::App

Inherits:
Thor
  • Object
show all
Defined in:
lib/tasku/cli.rb

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.start(args = ARGV, **opts) ⇒ Object



51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
# File 'lib/tasku/cli.rb', line 51

def self.start(args = ARGV, **opts)
  sql_index = args.index("--sql")
  if sql_index
    args.delete_at(sql_index)
    query = args[sql_index]
    if query.nil? || query.empty?
      puts pastel.red("  No query provided after --sql.")
      return
    end
    args.delete_at(sql_index)
    new.invoke(:sql, [query])
    return
  end

  super
end

Instance Method Details

#addObject



153
154
155
156
157
158
159
160
161
162
163
164
# File 'lib/tasku/cli.rb', line 153

def add
  attrs = if options[:interactive] || options.values_at(:name, :description, :project, :category).all?(&:nil?)
            interactive_add
          else
            option_add
          end

  task = Task.create(attrs)
  terminal.render_added(task)
rescue Sequel::ValidationFailed => e
  abort pastel.red("Validation error: #{e.message}")
end

#categoriesObject



335
336
337
338
339
340
341
342
343
344
345
346
347
348
# File 'lib/tasku/cli.rb', line 335

def categories
  categories = Task.dataset.select(:category).where(Sequel.~(category: nil)).distinct.order(:category).map(:category)
  if categories.empty?
    puts pastel.yellow("  No categories found.")
    return
  end

  puts ""
  categories.each do |c|
    count = Task.where(category: c).count
    puts "  #{pastel.bold(c)} #{pastel.dim("(#{count} task(s))")}"
  end
  puts ""
end

#colour(project, hex = nil) ⇒ Object



316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
# File 'lib/tasku/cli.rb', line 316

def colour(project, hex = nil)
  if hex.nil?
    proj = Project[project]
    if proj
      proj.update(colour: nil)
      puts pastel.green("  Colour cleared for project '#{project}'.")
    else
      puts pastel.yellow("  No colour set for project '#{project}'.")
    end
    return
  end

  validated = validate_hex!(hex)
  Project.find_or_create(name: project).update(colour: validated)
  swatch = hex_colour_str("", validated)
  puts "  #{swatch} Colour #{pastel.bold(validated)} set for project '#{pastel.bold(project)}'."
end

#delete(id) ⇒ Object



276
277
278
279
280
281
282
283
284
285
286
287
# File 'lib/tasku/cli.rb', line 276

def delete(id)
  task = find_task(id)

  unless options[:force]
    prompt = TTY::Prompt.new
    confirmed = prompt.yes?(pastel.red("Delete task ##{id} (#{task.name})?"))
    return unless confirmed
  end

  task.destroy
  terminal.render_deleted(task)
end

#done(id) ⇒ Object



268
269
270
271
272
# File 'lib/tasku/cli.rb', line 268

def done(id)
  task = find_task(id)
  task.update(status: "done")
  terminal.render_updated(task)
end

#edit(id) ⇒ Object



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

def edit(id)
  task = find_task(id)

  attrs = option_edit
  if attrs.empty? && !options[:clear]
    puts pastel.yellow("No changes specified. Use --help to see available options.")
    return
  end

  if options[:clear]
    clear_fields = options[:clear].split(",").map(&:strip)
    clear_map = {
      "description" => :description,
      "start"       => :start_day,
      "due"         => :due_day,
      "model"       => :model_name,
      "tags"        => :tags,
      "hours"       => :estimated_hours,
      "code"        => :code
    }
    clear_fields.each do |f|
      col = clear_map[f]
      if col
        attrs[col] = nil
      else
        puts pastel.yellow("Unknown field to clear: #{f}")
      end
    end
  end

  task.update(attrs)
  terminal.render_updated(task)
rescue Sequel::ValidationFailed => e
  abort pastel.red("Validation error: #{e.message}")
end

#help(*args) ⇒ Object



73
74
75
76
77
78
79
80
81
# File 'lib/tasku/cli.rb', line 73

def help(*args)
  if args.empty?
    puts ""
    puts pastel.bold(LOGO)
    puts "  #{pastel.bold(TAGLINE)}"
    puts ""
  end
  super
end

#listObject



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

def list
  dataset = Task.dataset

  dataset = dataset.where(status: options[:status]) if options[:status]
  dataset = dataset.where(priority: options[:priority]) if options[:priority]
  dataset = dataset.where(project: options[:project]) if options[:project]
  dataset = dataset.where(category: options[:category]) if options[:category]

  if options[:tags]
    tag_filter = options[:tags].split(",").map(&:strip)
    tag_filter.each do |t|
      dataset = dataset.where(Sequel.ilike(:tags, "%#{t}%"))
    end
  end

  if options[:overdue]
    today = Date.today
    dataset = dataset.where { due_day < today }.exclude(status: %w[done cancelled])
  end

  sort_col = case options[:sort]
             when "name"     then :name
             when "priority" then Sequel.case(Task::VALID_PRIORITIES.each_with_index.to_h, 999, :priority)
             when "due"      then :due_day
             when "status"   then Sequel.case(Task::VALID_STATUSES.each_with_index.to_h, 999, :status)
             else :created_at
             end

  order = options[:order] == "desc" ? Sequel.desc(sort_col) : Sequel.asc(sort_col)
  dataset = dataset.order(order)

  tasks = dataset.all
  bar = { "bar_project" => Config.get("bar_project"), "bar_priority" => Config.get("bar_priority"), "bar_status" => Config.get("bar_status") }
  terminal.render_list(tasks, colour_map: Project.colour_map, spacing: Config.get("list_spacing"), bar: bar)
end

#projectsObject



296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
# File 'lib/tasku/cli.rb', line 296

def projects
  project_names = Task.dataset.select(:project).where(Sequel.~(project: nil)).distinct.order(:project).map(:project)
  if project_names.empty?
    puts pastel.yellow("  No projects found.")
    return
  end

  colour_map = Project.colour_map
  puts ""
  project_names.each do |p|
    count = Task.where(project: p).count
    colour = colour_map[p]
    swatch = colour ? "#{hex_colour_str("", colour)} " : "  "
    name_str = colour ? hex_bold_str(p, colour) : pastel.bold(p)
    puts "  #{swatch}#{name_str} #{pastel.dim("(#{count} task(s))")}"
  end
  puts ""
end

#show(id) ⇒ Object



212
213
214
215
# File 'lib/tasku/cli.rb', line 212

def show(id)
  task = find_task(id)
  terminal.render_show(task, colour_map: Project.colour_map)
end

#sql(query) ⇒ Object



84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
# File 'lib/tasku/cli.rb', line 84

def sql(query)
  if query.strip.upcase.match?(/\A(SELECT|PRAGMA|EXPLAIN)/)
    dataset = Tasku::Database.db.fetch(query)
    rows = dataset.all

    if rows.empty?
      puts pastel.yellow("  Query returned no results.")
      return
    end

    raw_keys = rows.first.keys
    has_code = raw_keys.include?(:code)
    columns = raw_keys.reject { |c| %i[model_name created_at updated_at code].include?(c.to_sym) }

    display_cols = columns.map { |c| c == :id ? "CODE-ID" : c.to_s }
    code_id_keys = columns.include?(:id) && has_code

    col_widths = columns.each_with_index.map do |c, i|
      data_vals = rows.map do |r|
        v = if c == :id && code_id_keys && r[:code] && !r[:code].to_s.empty?
              "#{r[:code]}-#{r[:id]}"
            else
              r[c].to_s
            end
        v.length
      end
      [display_cols[i].length, data_vals.max || 0].max
    end

    puts ""
    header = display_cols.each_with_index.map { |c, i| pastel.bold(c.ljust(col_widths[i])) }
    puts "  #{header.join('  ')}"
    puts "  #{display_cols.each_with_index.map { |_c, i| pastel.dim("\u2500" * col_widths[i]) }.join('  ')}"

    rows.each do |row|
      cells = columns.each_with_index.map do |col, i|
        val = if col == :id && code_id_keys && row[:code] && !row[:code].to_s.empty?
                "#{row[:code]}-#{row[:id]}"
              else
                row[col].to_s
              end
        colour_cell(col, val.ljust(col_widths[i]), row)
      end
      puts "  #{cells.join('  ')}"
      puts "  #{display_cols.each_with_index.map { |_c, i| pastel.dim("\u2500" * col_widths[i]) }.join('  ')}"
    end
    puts ""
  else
    affected = Tasku::Database.db.run(query)
    puts pastel.green("  Query executed successfully.")
  end
rescue Sequel::DatabaseError => e
  abort pastel.red("SQL error: #{e.message}")
end

#statsObject



290
291
292
293
# File 'lib/tasku/cli.rb', line 290

def stats
  tasks = Task.dataset.all
  terminal.render_stats(tasks, colour_map: Project.colour_map) if tasks
end

#versionObject



351
352
353
# File 'lib/tasku/cli.rb', line 351

def version
  puts "tasku #{Tasku::VERSION}"
end