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



17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
# File 'lib/tasku/cli.rb', line 17

def self.start(args = ARGV, **opts)
  pastel = Pastel.new
  $stdout.puts ""
  $stdout.puts pastel.bright_cyan(LOGO)
  $stdout.puts pastel.bright_cyan("  #{TAGLINE}")
  $stdout.puts ""

  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



112
113
114
115
116
117
118
119
120
121
122
123
# File 'lib/tasku/cli.rb', line 112

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



270
271
272
273
274
275
276
277
278
279
280
281
282
283
# File 'lib/tasku/cli.rb', line 270

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

#delete(id) ⇒ Object



234
235
236
237
238
239
240
241
242
243
244
245
# File 'lib/tasku/cli.rb', line 234

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



226
227
228
229
230
# File 'lib/tasku/cli.rb', line 226

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

#edit(id) ⇒ Object



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
219
220
221
222
223
# File 'lib/tasku/cli.rb', line 189

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

#listObject



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

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
  terminal.render_list(tasks)
end

#projectsObject



254
255
256
257
258
259
260
261
262
263
264
265
266
267
# File 'lib/tasku/cli.rb', line 254

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

  puts ""
  projects.each do |p|
    count = Task.where(project: p).count
    puts "  #{pastel.bold(p)} #{pastel.dim("(#{count} task(s))")}"
  end
  puts ""
end

#show(id) ⇒ Object



170
171
172
173
# File 'lib/tasku/cli.rb', line 170

def show(id)
  task = find_task(id)
  terminal.render_show(task)
end

#sql(query) ⇒ Object



43
44
45
46
47
48
49
50
51
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
# File 'lib/tasku/cli.rb', line 43

def sql(query)
  if query.strip.upcase.start_with?("SELECT")
    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[description tags 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



248
249
250
251
# File 'lib/tasku/cli.rb', line 248

def stats
  tasks = Task.dataset.all
  terminal.render_stats(tasks) if tasks
end

#versionObject



286
287
288
# File 'lib/tasku/cli.rb', line 286

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