Class: Howzit::Topic

Inherits:
Object
  • Object
show all
Includes:
Comparable
Defined in:
lib/howzit/topic.rb

Overview

Topic Class

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(title, content) ⇒ Topic

Initialize a topic object

Parameters:

  • title (String)

    The topic title

  • content (String)

    The raw topic content



18
19
20
21
22
23
24
25
26
27
28
# File 'lib/howzit/topic.rb', line 18

def initialize(title, content)
  @title = title
  @content = content
  @parent = nil
  @nest_level = 0
  @named_args = {}
  arguments

  @tasks = gather_tasks
  @results = { total: 0, success: 0, errors: 0, message: ''.c }
end

Instance Attribute Details

#contentObject

Returns the value of attribute content.



8
9
10
# File 'lib/howzit/topic.rb', line 8

def content
  @content
end

#named_argsObject (readonly)

Returns the value of attribute named_args.



10
11
12
# File 'lib/howzit/topic.rb', line 10

def named_args
  @named_args
end

#parent=(value) ⇒ Object (writeonly)

Sets the attribute parent

Parameters:

  • value

    the value to set the attribute parent to.



6
7
8
# File 'lib/howzit/topic.rb', line 6

def parent=(value)
  @parent = value
end

#postreqsObject (readonly)

Returns the value of attribute postreqs.



10
11
12
# File 'lib/howzit/topic.rb', line 10

def postreqs
  @postreqs
end

#prereqsObject (readonly)

Returns the value of attribute prereqs.



10
11
12
# File 'lib/howzit/topic.rb', line 10

def prereqs
  @prereqs
end

#resultsObject (readonly)

Returns the value of attribute results.



10
11
12
# File 'lib/howzit/topic.rb', line 10

def results
  @results
end

#tasksObject (readonly)

Returns the value of attribute tasks.



10
11
12
# File 'lib/howzit/topic.rb', line 10

def tasks
  @tasks
end

#titleObject (readonly)

Returns the value of attribute title.



10
11
12
# File 'lib/howzit/topic.rb', line 10

def title
  @title
end

Instance Method Details

#<=>(other) ⇒ Object



282
283
284
# File 'lib/howzit/topic.rb', line 282

def <=>(other)
  @title <=> other.title
end

#argumentsObject

Get named arguments from title



31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
# File 'lib/howzit/topic.rb', line 31

def arguments
  return unless @title =~ /\(.*?\) *$/

  a = @title.match(/\((?<args>.*?)\) *$/)
  args = a['args'].split(/ *, */).each(&:strip)

  args.each_with_index do |arg, idx|
    arg_name, default = arg.split(/:/).map(&:strip)

    @named_args[arg_name] = if Howzit.arguments.count >= idx + 1
                              Howzit.arguments[idx]
                            else
                              default
                            end
  end

  @title = @title.sub(/\(.*?\) *$/, '').strip
end

#ask_task(task) ⇒ Object



59
60
61
62
63
64
65
66
67
68
# File 'lib/howzit/topic.rb', line 59

def ask_task(task)
  note = if task.type == :include
           task_count = Howzit.buildnote.find_topic(task.action)[0].tasks.count
           " (#{task_count} tasks)"
         else
           ''
         end
  q = %({bg}#{task.type.to_s.capitalize} {xw}"{bw}#{task.title}{xw}"#{note}{x}).c
  Prompt.yn(q, default: task.default)
end

#check_colsObject



70
71
72
73
74
# File 'lib/howzit/topic.rb', line 70

def check_cols
  TTY::Screen.columns > 60 ? 60 : TTY::Screen.columns
rescue StandardError
  60
end

#color_directive_yn(keys) ⇒ Object



198
199
200
201
202
203
204
205
# File 'lib/howzit/topic.rb', line 198

def color_directive_yn(keys)
  optional, default = define_optional(keys[:optional])
  if optional
    default ? ' {xk}[{g}Y{xk}/{dbw}n{xk}]{x}'.c : ' {xk}[{dbw}y{xk}/{g}N{xk}]{x}'.c
  else
    ''
  end
end

#colored_option(color, topic, keys) ⇒ Object



134
135
136
137
138
139
140
141
142
143
144
145
146
# File 'lib/howzit/topic.rb', line 134

def colored_option(color, topic, keys)
  if topic.tasks.empty?
    ''
  else
    optional = keys[:optional] =~ /[?!]+/ ? true : false
    default = keys[:optional] =~ /!/ ? false : true
    if optional
      colored_yn(color, default)
    else
      ''
    end
  end
end

#colored_yn(color, default) ⇒ Object



148
149
150
151
152
153
154
# File 'lib/howzit/topic.rb', line 148

def colored_yn(color, default)
  if default
    " {xKk}[{gbK}Y{xKk}/{dbwK}n{xKk}]{x}#{color}".c
  else
    " {xKk}[{dbwK}y{xKk}/{bgK}N{xKk}]{x}#{color}".c
  end
end

#define_optional(optional) ⇒ Object



225
226
227
228
229
# File 'lib/howzit/topic.rb', line 225

def define_optional(optional)
  is_optional = optional =~ /[?!]+/ ? true : false
  default = optional =~ /!/ ? false : true
  [is_optional, default]
end

#define_task_args(keys) ⇒ Object



286
287
288
289
290
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
# File 'lib/howzit/topic.rb', line 286

def define_task_args(keys)
  cmd = keys[:cmd]
  obj = keys[:action]
  title = keys[:title].nil? ? obj : keys[:title].strip
  title = Howzit.options[:show_all_code] ? obj : title
  task_args = { type: :include,
                arguments: nil,
                title: title,
                action: obj,
                parent: self }
  case cmd
  when /include/i
    if title =~ /\[(.*?)\] *$/
      Howzit.named_arguments = @named_args
      args = Regexp.last_match(1).split(/ *, */).map(&:render_arguments)
      Howzit.arguments = args
      arguments
      title.sub!(/ *\[.*?\] *$/, '')
    end

    task_args[:type] = :include
    task_args[:arguments] = Howzit.named_arguments
  when /run/i
    task_args[:type] = :run
  when /copy/i
    task_args[:type] = :copy
    task_args[:action] = Shellwords.escape(obj)
  when /open|url/i
    task_args[:type] = :open
  end

  task_args
end

#grep(term) ⇒ Object

Search title and contents for a pattern

Parameters:

  • term (String)

    the search pattern



55
56
57
# File 'lib/howzit/topic.rb', line 55

def grep(term)
  @title =~ /#{term}/i || @content =~ /#{term}/i
end

Output a topic with fancy title and bright white text.

Parameters:

  • options (Hash) (defaults to: {})

    The options

Returns:

  • (Array)

    array of formatted lines



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
270
271
272
273
274
275
276
277
278
279
# File 'lib/howzit/topic.rb', line 245

def print_out(options = {})
  defaults = { single: false, header: true }
  opt = defaults.merge(options)

  output = []
  if opt[:header]
    output.push(@title.format_header)
    output.push('')
  end
  topic = @content.dup
  unless Howzit.options[:show_all_code]
    topic.gsub!(/(?mix)^(`{3,})run([?!]*)\s*
                ([^\n]*)[\s\S]*?\n\1\s*$/, '@@@run\2 \3')
  end
  topic.split(/\n/).each do |l|
    case l
    when /@(before|after|prereq|end)/
      next
    when /@include(?<optional>[!?]{1,2})?\((?<action>[^)]+)\)/
      output.concat(process_include(Regexp.last_match.named_captures.symbolize_keys, opt))
    when /@(?<cmd>run|copy|open|url)(?<optional>[?!]{1,2})?\((?<action>.*?)\) *(?<title>.*?)$/
      output.push(process_directive(Regexp.last_match.named_captures.symbolize_keys))
    when /(?<fence>`{3,})run(?<optional>[!?]{1,2})? *(?<title>.*?)$/i
      desc = title_code_block(Regexp.last_match.named_captures.symbolize_keys)
      output.push("{bmK}\u{25B6} {bwK}#{desc}{x}\n```".c)
    when /@@@run(?<optional>[!?]{1,2})? *(?<title>.*?)$/i
      output.push("{bmK}\u{25B6} {bwK}#{title_code_block(Regexp.last_match.named_captures.symbolize_keys)}{x}".c)
    else
      l.wrap!(Howzit.options[:wrap]) if Howzit.options[:wrap].positive?
      output.push(l)
    end
  end
  Howzit.named_arguments = @named_args
  output.push('').map(&:render_arguments)
end

#process_directive(keys) ⇒ Object



207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
# File 'lib/howzit/topic.rb', line 207

def process_directive(keys)
  cmd = keys[:cmd]
  obj = keys[:action]
  title = keys[:title].empty? ? obj : keys[:title].strip
  title = Howzit.options[:show_all_code] ? obj : title
  option = color_directive_yn(keys)
  icon = case cmd
         when 'run'
           "\u{25B6}"
         when 'copy'
           "\u{271A}"
         when /open|url/
           "\u{279A}"
         end

  "{bmK}#{icon} {bwK}#{title.preserve_escapes}{x}#{option}".c
end

#process_include(keys, opt) ⇒ Object

Handle an include statement

Parameters:

  • keys (Hash)

    The symbolized keys and values from the regex that found the statement

  • opt (Hash)

    Options



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
# File 'lib/howzit/topic.rb', line 163

def process_include(keys, opt)
  output = []

  if keys[:action] =~ / *\[(.*?)\] *$/
    Howzit.named_arguments = @named_args
    Howzit.arguments = Regexp.last_match(1).split(/ *, */).map!(&:render_arguments)
  end

  matches = Howzit.buildnote.find_topic(keys[:action].sub(/ *\[.*?\] *$/, ''))

  return [] if matches.empty?

  topic = matches[0]

  rule = '{kKd}'
  color = '{Kyd}'
  title = title_option(color, topic, keys, opt)
  options = { color: color, hr: '.', border: rule }

  output.push("#{'> ' * @nest_level}#{title}".format_header(options)) unless Howzit.inclusions.include?(topic)

  if opt[:single] && Howzit.inclusions.include?(topic)
    output.push("#{'> ' * @nest_level}#{title} included above".format_header(options))
  elsif opt[:single]
    @nest_level += 1

    output.concat(topic.print_out({ single: true, header: false }))
    output.push("#{'> ' * @nest_level}...".format_header(options))
    @nest_level -= 1
  end
  Howzit.inclusions.push(topic)

  output
end

#run(nested: false) ⇒ Object

Handle run command, execute directives in topic



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
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
# File 'lib/howzit/topic.rb', line 77

def run(nested: false)
  output = []

  cols = check_cols

  if @tasks.count.positive?
    unless @prereqs.empty?
      puts TTY::Box.frame("{by}#{@prereqs.join("\n\n").wrap(cols - 4)}{x}".c, width: cols)
      res = Prompt.yn('Have the above prerequisites been met?', default: true)
      Process.exit 1 unless res

    end

    @tasks.each do |task|
      next if (task.optional || Howzit.options[:ask]) && !ask_task(task)

      run_output, total, success = task.run

      output.concat(run_output)
      @results[:total] += total

      if success
        @results[:success] += total
      else
        Howzit.console.warn %({bw}\u{2297} {br}Error running task {bw}"#{task.title}"{x}).c

        @results[:errors] += total

        break unless Howzit.options[:force]
      end
    end

    total = "{bw}#{@results[:total]}{by} #{@results[:total] == 1 ? 'task' : 'tasks'}".c
    errors = "{bw}#{@results[:errors]}{by} #{@results[:errors] == 1 ? 'error' : 'errors'}".c
    @results[:message] += if @results[:errors].zero?
                            "{bg}\u{2713} {by}Ran #{total}{x}".c
                          elsif Howzit.options[:force]
                            "{br}\u{2715} {by}Completed #{total} with #{errors}{x}".c
                          else
                            "{br}\u{2715} {by}Ran #{total}, terminated due to error{x}".c
                          end
  else
    Howzit.console.warn "{r}--run: No {br}@directive{xr} found in {bw}#{@title}{x}".c
  end

  output.push(@results[:message]) if Howzit.options[:log_level] < 2 && !nested

  puts TTY::Box.frame("{bw}#{@postreqs.join("\n\n").wrap(cols - 4)}{x}".c, width: cols) unless @postreqs.empty?

  output
end

#title_code_block(keys) ⇒ Object



231
232
233
234
235
236
237
# File 'lib/howzit/topic.rb', line 231

def title_code_block(keys)
  if keys[:title].length.positive?
    "Block: #{keys[:title]}#{color_directive_yn(keys)}"
  else
    "Code Block#{color_directive_yn(keys)}"
  end
end

#title_option(color, topic, keys, opt) ⇒ Object



129
130
131
132
# File 'lib/howzit/topic.rb', line 129

def title_option(color, topic, keys, opt)
  option = colored_option(color, topic, keys)
  "#{opt[:single] ? 'From' : 'Include'} #{topic.title}#{option}:"
end