Class: Howzit::BuildNotes

Inherits:
Object
  • Object
show all
Includes:
Color, Prompt
Defined in:
lib/howzit/buildnotes.rb

Overview

Primary Class for this module

Constant Summary

Constants included from Color

Color::ATTRIBUTES, Color::ATTRIBUTE_NAMES, Color::COLORED_REGEXP, Color::ESCAPE_REGEX

Instance Attribute Summary collapse

Instance Method Summary collapse

Methods included from Color

#attributes, coloring?, #rgb, #support?, template, #uncolor

Methods included from Prompt

#yn

Constructor Details

#initialize(args = []) ⇒ BuildNotes

Returns a new instance of BuildNotes.



691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
# File 'lib/howzit/buildnotes.rb', line 691

def initialize(args = [])
  Color.coloring = $stdout.isatty
  flags = {
    run: false,
    list_topics: false,
    list_topic_titles: false,
    list_runnable: false,
    list_runnable_titles: false,
    title_only: false,
    choose: false,
    quiet: false,
    verbose: false,
    default: false
  }

  defaults = {
    color: true,
    highlight: true,
    paginate: true,
    wrap: 0,
    output_title: false,
    highlighter: 'auto',
    pager: 'auto',
    matching: 'partial', # exact, partial, fuzzy, beginswith
    show_all_on_error: false,
    include_upstream: false,
    show_all_code: false,
    grep: nil,
    log_level: 1 # 0: debug, 1: info, 2: warn, 3: error
  }

  @metadata = {}
  @included = []
  @nest_level = 0

  parts = Shellwords.shelljoin(args).split(/ -- /)
  args = parts[0] ? Shellwords.shellsplit(parts[0]) : []
  @arguments = parts[1] ? Shellwords.shellsplit(parts[1]) : []

  config = load_config(defaults)
  @options = flags.merge(config)

  OptionParser.new do |opts|
    opts.banner = "Usage: #{__FILE__} [OPTIONS] [TOPIC]"
    opts.separator ''
    opts.separator 'Show build notes for the current project (buildnotes.md).
    Include a topic name to see just that topic, or no argument to display all.'
    opts.separator ''
    opts.separator 'Options:'

    opts.on('-c', '--create', 'Create a skeleton build note in the current working directory') do
      create_note
      Process.exit 0
    end

    opts.on('-e', '--edit', "Edit buildnotes file in current working directory
            using $EDITOR") do
      edit_note
      Process.exit 0
    end

    opts.on('--grep PATTERN', 'Display sections matching a search pattern') do |pat|
      @options[:grep] = pat
    end

    opts.on('-L', '--list-completions', 'List topics for completion') do
      @options[:list_topics] = true
      @options[:list_topic_titles] = true
    end

    opts.on('-l', '--list', 'List available topics') do
      @options[:list_topics] = true
    end

    opts.on('-m', '--matching TYPE', MATCHING_OPTIONS,
            'Topics matching type', "(#{MATCHING_OPTIONS.join(', ')})") do |c|
      @options[:matching] = c
    end

    opts.on('-R', '--list-runnable', 'List topics containing @ directives (verbose)') do
      @options[:list_runnable] = true
    end

    opts.on('-r', '--run', 'Execute @run, @open, and/or @copy commands for given topic') do
      @options[:run] = true
    end

    opts.on('-s', '--select', 'Select topic from menu') do
      @options[:choose] = true
    end

    opts.on('-T', '--task-list', 'List topics containing @ directives (completion-compatible)') do
      @options[:list_runnable] = true
      @options[:list_runnable_titles] = true
    end

    opts.on('-t', '--title', 'Output title with build notes') do
      @options[:output_title] = true
    end

    opts.on('-q', '--quiet', 'Silence info message') do
      @options[:log_level] = 3
    end

    opts.on('-v', '--verbose', 'Show all messages') do
      @options[:log_level] = 0
    end

    opts.on('-u', '--[no-]upstream', 'Traverse up parent directories for additional build notes') do |p|
      @options[:include_upstream] = p
    end

    opts.on('--show-code', 'Display the content of fenced run blocks') do
      @options[:show_all_code] = true
    end

    opts.on('-w', '--wrap COLUMNS', 'Wrap to specified width (default 80, 0 to disable)') do |w|
      @options[:wrap] = w.to_i
    end

    opts.on('--edit-config', "Edit configuration file using default $EDITOR") do
      edit_config(defaults)
      Process.exit 0
    end

    opts.on('--title-only', 'Output title only') do
      @options[:output_title] = true
      @options[:title_only] = true
    end

    opts.on('--templates', 'List available templates') do
      Dir.chdir(template_folder)
      Dir.glob('*.md').each do |file|
        template = File.basename(file, '.md')
        puts Color.template("{Mk}template:{Yk}#{template}{x}")
        puts Color.template("{bk}[{bl}tasks{bk}]──────────────────────────────────────┐{x}")
         = file.
        topics = read_help_file(file)
        topics.each_key do |topic|
          puts Color.template(" {bk}│{bw}-{x} {bcK}#{template}:#{topic.sub(/^.*?:/, '')}{x}")
        end
        if .size > 0
          meta = []
          meta << ['required'].split(/\s*,\s*/).map {|m| "*{bw}#{m}{xw}" } if .key?('required')
          meta << ['optional'].split(/\s*,\s*/).map {|m| "#{m}" } if .key?('optional')
          puts Color.template("{bk}[{bl}meta{bk}]───────────────────────────────────────┤{x}")
          puts Color.template(" {bk}│ {xw}#{meta.join(", ")}{x}")
        end
        puts Color.template(" {bk}└───────────────────────────────────────────┘{x}")
      end
      Process.exit 0
    end

    opts.on('--[no-]color', 'Colorize output (default on)') do |c|
      @options[:color] = c
      @options[:highlight] = false unless c
    end

    opts.on('--[no-]md-highlight', 'Highlight Markdown syntax (default on), requires mdless or mdcat') do |m|
      @options[:highlight] = @options[:color] ? m : false
    end

    opts.on('--[no-]pager', 'Paginate output (default on)') do |p|
      @options[:paginate] = p
    end

    opts.on('-h', '--help', 'Display this screen') do
      puts opts
      Process.exit 0
    end

    opts.on('-v', '--version', 'Display version number') do
      puts "Howzit v#{VERSION}"
      Process.exit 0
    end

    opts.on('--default', 'Answer all prompts with default response') do
      @options[:default] = true
    end
  end.parse!(args)

  @cli_args = args
end

Instance Attribute Details

#argumentsObject

Returns the value of attribute arguments.



7
8
9
# File 'lib/howzit/buildnotes.rb', line 7

def arguments
  @arguments
end

#cli_argsObject

Returns the value of attribute cli_args.



7
8
9
# File 'lib/howzit/buildnotes.rb', line 7

def cli_args
  @cli_args
end

#metadataObject

Returns the value of attribute metadata.



7
8
9
# File 'lib/howzit/buildnotes.rb', line 7

def 
  @metadata
end

#optionsObject

Returns the value of attribute options.



7
8
9
# File 'lib/howzit/buildnotes.rb', line 7

def options
  @options
end

Instance Method Details

#choose(matches) ⇒ Object



1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
# File 'lib/howzit/buildnotes.rb', line 1002

def choose(matches)
  if command_exist?('fzf')
    res = `echo #{Shellwords.escape(matches.join("\n"))} | fzf -0 -1 --height #{matches.count + 2} --prompt 'Select a section > '`.strip
    if res.nil? || res.empty?
      warn 'Cancelled'
      Process.exit 0
    end
    return res
  end

  res = matches[0..9]
  stty_save = `stty -g`.chomp

  trap('INT') do
    system('stty', stty_save)
    exit
  end

  options_list(matches)

  begin
    printf("Type 'q' to cancel, enter for first item", res.length)
    while (line = Readline.readline(': ', true))
      if line =~ /^[a-z]/i
        system('stty', stty_save) # Restore
        exit
      end
      line = line == '' ? 1 : line.to_i

      return matches[line - 1] if line.positive? && line <= matches.length

      puts 'Out of range'
      options_list(matches)
    end
  rescue Interrupt
    system('stty', stty_save)
    exit
  end
end

#color_single_options(choices = %w[y n])) ⇒ Object



144
145
146
147
148
149
150
151
152
153
154
155
# File 'lib/howzit/buildnotes.rb', line 144

def color_single_options(choices = %w[y n])
  out = []
  choices.each do |choice|
    case choice
    when /[A-Z]/
      out.push(Color.template("{bg}#{choice}{xg}"))
    else
      out.push(Color.template("{w}#{choice}"))
    end
  end
  Color.template("{g}[#{out.join('/')}{g}]{x}")
end

#command_exist?(command) ⇒ Boolean

Returns:

  • (Boolean)


988
989
990
991
992
993
994
995
996
997
998
999
1000
# File 'lib/howzit/buildnotes.rb', line 988

def command_exist?(command)
  exts = ENV.fetch('PATHEXT', '').split(::File::PATH_SEPARATOR)
  if Pathname.new(command).absolute?
    ::File.exist?(command) ||
      exts.any? { |ext| ::File.exist?("#{command}#{ext}") }
  else
    ENV.fetch('PATH', '').split(::File::PATH_SEPARATOR).any? do |dir|
      file = ::File.join(dir, command)
      ::File.exist?(file) ||
        exts.any? { |ext| ::File.exist?("#{file}#{ext}") }
    end
  end
end

#config_dirObject



1042
1043
1044
# File 'lib/howzit/buildnotes.rb', line 1042

def config_dir
  File.expand_path(CONFIG_DIR)
end

#config_fileObject



1046
1047
1048
# File 'lib/howzit/buildnotes.rb', line 1046

def config_file
  File.join(config_dir, CONFIG_FILE)
end

#create_config(defaults) ⇒ Object



1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
# File 'lib/howzit/buildnotes.rb', line 1058

def create_config(defaults)
  dir, file = [config_dir, config_file]
  unless File.directory?(dir)
    warn "Creating config directory at #{dir}"
    FileUtils.mkdir_p(dir)
  end

  unless File.exist?(file)
    warn "Writing fresh config file to #{file}"
    write_config(defaults)
  end
  file
end

#create_noteObject

Create a buildnotes skeleton



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
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
# File 'lib/howzit/buildnotes.rb', line 158

def create_note
  trap('SIGINT') do
    warn "\nCanceled"
    exit!
  end
  default = !$stdout.isatty || @options[:default]
  # First make sure there isn't already a buildnotes file
  if note_file
    fname = Color.template("{by}#{note_file}{bw}")
    unless default
      res = yn("#{fname} exists and appears to be a build note, continue anyway?", false)
      unless res
        puts 'Canceled'
        Process.exit 0
      end
    end
  end

  title = File.basename(Dir.pwd)
  if default
    input = title
  else
    printf Color.template("{bw}Project name {xg}[#{title}]{bw}: {x}")
    input = $stdin.gets.chomp
    title = input unless input.empty?
  end
  summary = ''
  unless default
    printf Color.template('{bw}Project summary: {x}')
    input = $stdin.gets.chomp
    summary = input unless input.empty?
  end

  fname = 'buildnotes.md'
  unless default
    printf Color.template("{bw}Build notes filename (must begin with 'howzit' or 'build')\n{xg}[#{fname}]{bw}: {x}")
    input = $stdin.gets.chomp
    fname = input unless input.empty?
  end

  note = <<~EOBUILDNOTES
    # #{title}

    #{summary}

    ## File Structure

    Where are the main editable files? Is there a dist/build folder that should be ignored?

    ## Build

    What build system/parameters does this use?

    @run(./build command)

    ## Deploy

    What are the procedures/commands to deploy this project?

    ## Other

    Version control notes, additional gulp/rake/make/etc tasks...

  EOBUILDNOTES

  if File.exist?(fname) && !default
    file = Color.template("{by}#{fname}")
    res = yn("Are you absolutely sure you want to overwrite #{file}", false)

    unless res
      puts 'Canceled'
      Process.exit 0
    end
  end

  File.open(fname, 'w') do |f|
    f.puts note
    puts Color.template("{by}Build notes for #{title} written to #{fname}")
  end
end

#edit_config(defaults) ⇒ Object



1084
1085
1086
1087
1088
1089
# File 'lib/howzit/buildnotes.rb', line 1084

def edit_config(defaults)
  raise 'No EDITOR variable defined in environment' if ENV['EDITOR'].nil?

  load_config(defaults)
  `#{ENV['EDITOR']} "#{config_file}"`
end

#edit_noteObject



875
876
877
878
879
880
881
882
883
884
885
886
# File 'lib/howzit/buildnotes.rb', line 875

def edit_note
  raise 'No EDITOR variable defined in environment' if ENV['EDITOR'].nil?

  if note_file.nil?
    res = yn("No build notes file found, create one?", true)

    create_note if res
    edit_note
  else
    `#{ENV['EDITOR']} "#{note_file}"`
  end
end

#ensure_requirements(template) ⇒ Object



537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
# File 'lib/howzit/buildnotes.rb', line 537

def ensure_requirements(template)
  t_leader = IO.read(template).split(/^#/)[0].strip
  if t_leader.length > 0
    t_meta = t_leader.
    if t_meta.key?('required')
      required = t_meta['required'].strip.split(/\s*,\s*/)
      required.each do |req|
        unless @metadata.keys.include?(req.downcase)
          warn Color.template(%({xr}ERROR: Missing required metadata key from template '{bw}#{File.basename(template, '.md')}{xr}'{x}))
          warn Color.template(%({xr}Please define {by}#{req.downcase}{xr} in build notes{x}))
          Process.exit 1
        end
      end
    end
  end
end

#find_note_fileObject



957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
# File 'lib/howzit/buildnotes.rb', line 957

def find_note_file
  filename = glob_note

  if filename.nil? && 'git'.available?
    proj_dir = `git rev-parse --show-toplevel 2>/dev/null`.strip
    unless proj_dir == ''
      Dir.chdir(proj_dir)
      filename = glob_note
    end
  end

  if filename.nil? && @options[:include_upstream]
    upstream_notes = glob_upstream
    filename = upstream_notes[-1] unless upstream_notes.empty?
  end

  return nil if filename.nil?

  File.expand_path(filename)
end

#format_header(title, opts = {}) ⇒ Object

Make a fancy title line for the topic



240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
# File 'lib/howzit/buildnotes.rb', line 240

def format_header(title, opts = {})
  options = {
    hr: "\u{254C}",
    color: '{bg}',
    border: '{x}',
    mark: false
  }

  options.merge!(opts)

  cols = TTY::Screen.columns

  cols = @options[:wrap] if (@options[:wrap]).positive? && cols > @options[:wrap]
  title = Color.template("#{options[:border]}#{options[:hr] * 2}( #{options[:color]}#{title}#{options[:border]} )")

  tail = if should_mark_iterm?
           "#{options[:hr] * (cols - title.uncolor.length - 15)}#{options[:mark] ? iterm_marker : ''}"
         else
           options[:hr] * (cols - title.uncolor.length)
         end
  Color.template("#{title}#{tail}{x}")
end

#get_note_title(truncate = 0) ⇒ Object



470
471
472
473
474
475
476
477
478
479
480
481
# File 'lib/howzit/buildnotes.rb', line 470

def get_note_title(truncate = 0)
  title = nil
  help = IO.read(note_file).strip
  title = help.match(/(?:^(\S.*?)(?=\n==)|^# ?(.*?)$)/)
  title = if title
            title[1].nil? ? title[2] : title[1]
          else
           note_file.sub(/(\.\w+)?$/, '')
         end

  title && truncate.positive? ? title.trunc(truncate) : title
end

#get_template_topics(content) ⇒ Object



554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
# File 'lib/howzit/buildnotes.rb', line 554

def get_template_topics(content)
  leader = content.split(/^#/)[0].strip

  template_topics = {}
  if leader.length > 0
    data = leader.
    @metadata = @metadata.merge(data)

    if data.key?('template')
      templates = data['template'].strip.split(/\s*,\s*/)
      templates.each do |t|
        tasks = nil
        if t =~ /\[(.*?)\]$/
          tasks = Regexp.last_match[1].split(/\s*,\s*/).map {|t| t.gsub(/\*/, '.*?')}
          t = t.sub(/\[.*?\]$/, '').strip
        end

        t_file = t.sub(/(\.md)?$/, '.md')
        template = File.join(template_folder, t_file)
        if File.exist?(template)
          ensure_requirements(template)

          t_topics = read_help_file(template)
          if tasks
            tasks.each do |task|
              t_topics.keys.each do |topic|
                if topic =~ /^(.*?:)?#{task}$/i
                  template_topics[topic] = t_topics[topic]
                end
              end
            end
          else
            template_topics = template_topics.merge(t_topics)
          end
        end
      end
    end
  end
  template_topics
end

#glob_noteObject



939
940
941
942
943
944
945
946
947
948
949
950
951
# File 'lib/howzit/buildnotes.rb', line 939

def glob_note
  filename = nil
  # Check for a build note file in the current folder. Filename must start
  # with "build" and have an extension of txt, md, or markdown.

  Dir.glob('*.{txt,md,markdown}').each do |f|
    if is_build_notes(f)
      filename = f
      break
    end
  end
  filename
end

#glob_upstreamObject

Traverse up directory tree looking for build notes

Returns:

  • topics dictionary



893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
# File 'lib/howzit/buildnotes.rb', line 893

def glob_upstream
  home = Dir.pwd
  dir = File.dirname(home)
  buildnotes = []
  filename = nil

  while dir != '/' && (dir =~ %r{[A-Z]:/}).nil?
    Dir.chdir(dir)
    filename = glob_note
    unless filename.nil?
      note = File.join(dir, filename)
      buildnotes.push(note) unless note == note_file
    end
    dir = File.dirname(dir)
  end

  Dir.chdir(home)

  buildnotes.reverse
end

#grep_topics(pat) ⇒ Object



284
285
286
287
288
289
290
291
292
# File 'lib/howzit/buildnotes.rb', line 284

def grep_topics(pat)
  matching_topics = []
  topics.each do |topic, content|
    if content =~ /#{pat}/i || topic =~ /#{pat}/i
      matching_topics.push(topic)
    end
  end
  matching_topics
end

#ignore_fileObject



1050
1051
1052
# File 'lib/howzit/buildnotes.rb', line 1050

def ignore_file
  File.join(config_dir, IGNORE_FILE)
end

#include_file(m) ⇒ Object



595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
# File 'lib/howzit/buildnotes.rb', line 595

def include_file(m)
  file = File.expand_path(m[1])

  return m[0] unless File.exist?(file)

  content = IO.read(file)
  home = ENV['HOME']
  short_path = File.dirname(file.sub(/^#{home}/, '~'))
  prefix = "#{short_path}/#{File.basename(file)}:"
  parts = content.split(/^##+/)
  parts.shift
  if parts.empty?
    content
  else
    "## #{parts.join('## ')}".gsub(/^(##+ *)(?=\S)/, "\\1#{prefix}")
  end
end

#is_build_notes(filename) ⇒ Object



914
915
916
917
918
# File 'lib/howzit/buildnotes.rb', line 914

def is_build_notes(filename)
  return false if filename.downcase !~ /(^howzit[^.]*|build[^.]+)/
  return false if should_ignore(filename)
  true
end

#iterm_markerObject



140
141
142
# File 'lib/howzit/buildnotes.rb', line 140

def iterm_marker
  "\e]1337;SetMark\a" if should_mark_iterm?
end

#list_runnableObject



498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
# File 'lib/howzit/buildnotes.rb', line 498

def list_runnable
  output = []
  output.push(Color.template(%({bg}"Runnable" Topics:{x}\n)))
  topics.each do |title, sect|
    s_out = []
    lines = sect.split(/\n/)
    lines.each do |l|
      case l
      when /@run\((.*?)\)(.*)?/
        m = Regexp.last_match
        run = m[2].strip.length.positive? ? m[2].strip : m[1]
        s_out.push("    * run: #{run.gsub(/\\n/, '\​n')}")
      when /@(copy|open|url)\((.*?)\)/
        m = Regexp.last_match
        s_out.push("    * #{m[1]}: #{m[2]}")
      when /`{3,}run(.*)?/m
        run = '    * run code block'
        title = Regexp.last_match(1).strip
        run += " (#{title})" if title.length.positive?
        s_out.push(run)
      end
    end
    unless s_out.empty?
      output.push(Color.template("- {bw}#{title}{x}"))
      output.push(s_out.join("\n"))
    end
  end
  output.join("\n")
end

#list_runnable_titlesObject



483
484
485
486
487
488
489
490
491
492
493
494
495
496
# File 'lib/howzit/buildnotes.rb', line 483

def list_runnable_titles
  output = []
  topics.each do |title, sect|
    runnable = false
    sect.split(/\n/).each do |l|
      if l =~ /(@(run|copy|open|url)\((.*?)\)|`{3,}run)/
        runnable = true
        break
      end
    end
    output.push(title) if runnable
  end
  output.join("\n")
end

#list_topic_titlesObject

Output a list of topic titles for shell completion



466
467
468
# File 'lib/howzit/buildnotes.rb', line 466

def list_topic_titles
  topics.keys.join("\n")
end

#list_topicsObject

Output a list of topic titles



456
457
458
459
460
461
462
463
# File 'lib/howzit/buildnotes.rb', line 456

def list_topics
  output = []
  output.push(Color.template("{bg}Topics:{x}\n"))
  topics.each_key do |title|
    output.push(Color.template("- {bw}#{title}{x}"))
  end
  output.join("\n")
end

#load_config(defaults) ⇒ Object



1072
1073
1074
1075
1076
1077
1078
# File 'lib/howzit/buildnotes.rb', line 1072

def load_config(defaults)
  file = create_config(defaults)
  config = YAML.load(IO.read(file))
  newconfig = config ? defaults.merge(config) : defaults
  write_config(newconfig)
  newconfig
end

#match_topic(search) ⇒ Object



670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
# File 'lib/howzit/buildnotes.rb', line 670

def match_topic(search)
  matches = []

  rx = case @options[:matching]
       when 'exact'
         /^#{search}$/i
       when 'beginswith'
         /^#{search}/i
       when 'fuzzy'
         search = search.split(//).join('.*?') if @options[:matching] == 'fuzzy'
         /#{search}/i
       else
         /#{search}/i
       end

  topics.each_key do |k|
    matches.push(k) if k.downcase =~ rx
  end
  matches
end

#note_fileObject



953
954
955
# File 'lib/howzit/buildnotes.rb', line 953

def note_file
  @note_file ||= find_note_file
end

#options_list(matches) ⇒ Object



978
979
980
981
982
983
984
985
986
# File 'lib/howzit/buildnotes.rb', line 978

def options_list(matches)
  counter = 1
  puts
  matches.each do |match|
    printf("%<counter>2d ) %<option>s\n", counter: counter, option: match)
    counter += 1
  end
  puts
end

#os_open(command) ⇒ Object



263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
# File 'lib/howzit/buildnotes.rb', line 263

def os_open(command)
  os = RbConfig::CONFIG['target_os']
  out = Color.template("{bg}Opening {bw}#{command}")
  case os
  when /darwin.*/i
    warn Color.template("#{out} (macOS){x}") if @options[:log_level] < 2
    `open #{Shellwords.escape(command)}`
  when /mingw|mswin/i
    warn Color.template("#{out} (Windows){x}") if @options[:log_level] < 2
    `start #{Shellwords.escape(command)}`
  else
    if 'xdg-open'.available?
      warn Color.template("#{out} (Linux){x}") if @options[:log_level] < 2
      `xdg-open #{Shellwords.escape(command)}`
    else
      warn out if @options[:log_level] < 2
      warn 'Unable to determine executable for `open`.'
    end
  end
end

#output_topic(key, options = {}) ⇒ Object

Output a topic with fancy title and bright white text.



363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
# File 'lib/howzit/buildnotes.rb', line 363

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

  output = []
  if opt[:header]
    output.push(format_header(key, { mark: should_mark_iterm? }))
    output.push('')
  end
  topic = topics[key].strip
  topic.gsub!(/(?mi)^(`{3,})run *([^\n]*)[\s\S]*?\n\1\s*$/, '@@@run \2') unless @options[:show_all_code]
  topic.split(/\n/).each do |l|
    case l
    when /@(before|after|prereq|end)/
      next
    when /@include\((.*?)\)/

      m = Regexp.last_match
      matches = match_topic(m[1])
      unless matches.empty?
        if opt[:single]
          title = "From #{matches[0]}:"
          color = '{yK}'
          rule = '{kK}'
        else
          title = "Include #{matches[0]}"
          color = '{yK}'
          rule = '{x}'
        end
        output.push(format_header("#{'> ' * @nest_level}#{title}", { color: color, hr: '.', border: rule })) unless @included.include?(matches[0])

        if opt[:single]
          if @included.include?(matches[0])
            output.push(format_header("#{'> ' * @nest_level}#{title} included above", { color: color, hr: '.', border: rule }))
          else
            @nest_level += 1
            output.concat(output_topic(matches[0], {single: true, header: false}))
            @nest_level -= 1
          end
          output.push(format_header("#{'> ' * @nest_level}...", { color: color, hr: '.', border: rule })) unless @included.include?(matches[0])
        end
        @included.push(matches[0])
      end

    when /@(run|copy|open|url|include)\((.*?)\)/
      m = Regexp.last_match
      cmd = m[1]
      obj = m[2]
      icon = case cmd
             when 'run'
               "\u{25B6}"
             when 'copy'
               "\u{271A}"
             when /open|url/
               "\u{279A}"
             end
      output.push(Color.template("{bmK}#{icon} {bwK}#{obj}{x}"))
    when /(`{3,})run *(.*?)$/i
      m = Regexp.last_match
      desc = m[2].length.positive? ? "Block: #{m[2]}" : 'Code Block'
      output.push(Color.template("{bmK}\u{25B6} {bwK}#{desc}{x}\n```"))
    when /@@@run *(.*?)$/i
      m = Regexp.last_match
      desc = m[1].length.positive? ? "Block: #{m[1]}" : 'Code Block'
      output.push(Color.template("{bmK}\u{25B6} {bwK}#{desc}{x}"))
    else
      l.wrap!(@options[:wrap]) if (@options[:wrap]).positive?
      output.push(l)
    end
  end
  output.push('')
end

#page(text) ⇒ Object

Paginate the output



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

def page(text)
  read_io, write_io = IO.pipe

  input = $stdin

  pid = Kernel.fork do
    write_io.close
    input.reopen(read_io)
    read_io.close

    # Wait until we have input before we start the pager
    IO.select [input]

    pager = which_pager
    begin
      exec(pager)
    rescue SystemCallError => e
      @log.error(e)
      exit 1
    end
  end

  read_io.close
  write_io.write(text)
  write_io.close

  _, status = Process.waitpid2(pid)
  status.success?
end

#processObject



1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
# File 'lib/howzit/buildnotes.rb', line 1091

def process
  output = []

  unless note_file
    Process.exit 0 if @options[:list_runnable_titles] || @options[:list_topic_titles]

    # clear the buffer
    ARGV.length.times do
      ARGV.shift
    end
    res = yn("No build notes file found, create one?", true)
    create_note if res
    Process.exit 1
  end

  if @options[:title_only]
    out = get_note_title(20)
    $stdout.print(out.strip)
    Process.exit(0)
  elsif @options[:output_title]
    title = get_note_title
    if title && !title.empty?
      header = format_header(title, { hr: "\u{2550}", color: '{bwK}' })
      output.push("#{header}\n")
    end
  end

  if @options[:list_runnable]
    if @options[:list_runnable_titles]
      out = list_runnable_titles
      $stdout.print(out.strip)
    else
      out = list_runnable
      show(out, { color: @options[:color], paginate: false, highlight: false })
    end
    Process.exit(0)
  end

  if @options[:list_topics]
    if @options[:list_topic_titles]
      $stdout.print(list_topic_titles)
    else
      out = list_topics
      show(out, { color: @options[:color], paginate: false, highlight: false })
    end
    Process.exit(0)
  end

  topic_match = nil
  if @options[:grep]
    topic_match = choose(grep_topics(@options[:grep]))
  elsif @options[:choose]
    topic_match = choose(topics.keys)
  # If there are arguments use those to search for a matching topic
  elsif !@cli_args.empty?

    search = @cli_args.join(' ').strip.downcase
    matches = match_topic(search)

    if matches.empty?
      output.push(Color.template(%({bR}ERROR:{xr} No topic match found for {bw}#{search}{x}\n)))
      unless @options[:show_all_on_error]
        show(output.join("\n"), { color: true, highlight: false, paginate: false, wrap: 0 })
        Process.exit 1
      end
    elsif matches.length == 1
      topic_match = matches[0]
    else
      topic_match = choose(matches)
    end
  end

  if topic_match
    # If we found a match
    output.push(process_topic(topic_match, @options[:run], true))
  else
    # If there's no argument or no match found, output all
    topics.each_key { |k| output.push(process_topic(k, false, false)) }
  end
  @options[:paginate] = false if @options[:run]
  show(output.join("\n").strip, @options)
end

#process_topic(key, run, single = false) ⇒ Object



436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
# File 'lib/howzit/buildnotes.rb', line 436

def process_topic(key, run, single = false)
  # Handle variable replacement
  content = topics[key]
  unless @arguments.empty?
    content.gsub!(/\$(\d+)/) do |m|
      idx = m[1].to_i - 1
      @arguments.length > idx ? @arguments[idx] : m
    end
    content.gsub!(/\$[@*]/, Shellwords.join(@arguments))
  end

  output = if run
             run_topic(key)
           else
             output_topic(key, {single: single})
           end
  output.nil? ? '' : output.join("\n")
end

#read_helpObject



655
656
657
658
659
660
661
662
663
664
665
666
667
# File 'lib/howzit/buildnotes.rb', line 655

def read_help
  topics = read_help_file
  if @options[:include_upstream]
    upstream_topics = read_upstream
    upstream_topics.each do |topic, content|
      unless topics.key?(topic.sub(/^.*?:/, ''))
        topics[topic] = content
      end
    end
    # topics = upstream_topics.merge(topics)
  end
  topics
end

#read_help_file(path = nil) ⇒ Object

Read in the build notes file and output a hash of "Title" => contents



614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
# File 'lib/howzit/buildnotes.rb', line 614

def read_help_file(path = nil)
  filename = path.nil? ? note_file : path
  topics_dict = {}
  help = IO.read(filename)

  help.gsub!(/@include\((.*?)\)/) do
    include_file(Regexp.last_match)
  end

  template_topics = get_template_topics(help)

  split = help.split(/^##+/)
  split.slice!(0)
  split.each do |sect|
    next if sect.strip.empty?

    lines = sect.split(/\n/)
    title = lines.slice!(0).strip
    prefix = ''
    if path
      if path =~ /#{template_folder}/
        short_path = File.basename(path, '.md')
      else
        home = ENV['HOME']
        short_path = File.dirname(path.sub(/^#{home}/, '~'))
        prefix = "_from #{short_path}_\n\n"
      end
      title = "#{short_path}:#{title}"
    end
    topics_dict[title] = prefix + lines.join("\n").strip.render_template(@metadata)
  end

  template_topics.each do |title, content|
    unless topics_dict.key?(title.sub(/^.+:/, ''))
      topics_dict[title] = content
    end
  end

  topics_dict
end

#read_upstreamObject



528
529
530
531
532
533
534
535
# File 'lib/howzit/buildnotes.rb', line 528

def read_upstream
  buildnotes = glob_upstream
  topics_dict = {}
  buildnotes.each do |path|
    topics_dict = topics_dict.merge(read_help_file(path))
  end
  topics_dict
end

#run_topic(key) ⇒ Object

Handle run command, execute directives



295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
# File 'lib/howzit/buildnotes.rb', line 295

def run_topic(key)
  output = []
  tasks = 0
  if topics[key] =~ /(@(include|run|copy|open|url)\((.*?)\)|`{3,}run)/i
    prereqs = topics[key].scan(/(?<=@before\n).*?(?=\n@end)/im).map(&:strip)
    postreqs = topics[key].scan(/(?<=@after\n).*?(?=\n@end)/im).map(&:strip)

    unless prereqs.empty?
      puts prereqs.join("\n\n")
      res = yn('This task has prerequisites, have they been met?', true)
      Process.exit 1 unless res

    end
    directives = topics[key].scan(/(?:@(include|run|copy|open|url)\((.*?)\)|(`{3,})run(?: +([^\n]+))?(.*?)\3)/mi)

    tasks += directives.length
    directives.each do |c|
      if c[0].nil?
        title = c[3] ? c[3].strip : ''
        warn Color.template("{bg}Running block {bw}#{title}{x}") if @options[:log_level] < 2
        block = c[4].strip
        script = Tempfile.new('howzit_script')
        begin
          script.write(block)
          script.close
          File.chmod(0777, script.path)
          system(%(/bin/sh -c "#{script.path}"))
        ensure
          script.close
          script.unlink
        end
      else
        cmd = c[0]
        obj = c[1]
        case cmd
        when /include/i
          matches = match_topic(obj)
          if matches.empty?
            warn "No topic match for @include(#{search})"
          else
            if @included.include?(matches[0])
              warn Color.template("{by}Tasks from {bw}#{matches[0]} already included, skipping{x}") if @options[:log_level] < 2
            else
              warn Color.template("{by}Including tasks from {bw}#{matches[0]}{x}") if @options[:log_level] < 2
              process_topic(matches[0], true)
              warn Color.template("{by}End include {bw}#{matches[0]}{x}") if @options[:log_level] < 2
            end
          end
        when /run/i
          warn Color.template("{bg}Running {bw}#{obj}{x}") if @options[:log_level] < 2
          system(obj)
        when /copy/i
          warn Color.template("{bg}Copied {bw}#{obj}{bg} to clipboard{x}") if @options[:log_level] < 2
          `echo #{Shellwords.escape(obj)}'\\c'|pbcopy`
        when /open|url/i
          os_open(obj)
        end
      end
    end
  else
    warn Color.template("{r}--run: No {br}@directive{xr} found in {bw}#{key}{x}")
  end
  output.push("Ran #{tasks} #{tasks == 1 ? 'task' : 'tasks'}") if @options[:log_level] < 2

  puts postreqs.join("\n\n")
end

#should_ignore(filename) ⇒ Object



920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
# File 'lib/howzit/buildnotes.rb', line 920

def should_ignore(filename)
  return false unless File.exist?(ignore_file)

  unless @ignore_patterns
    @ignore_patterns = YAML.load(IO.read(ignore_file))
  end

  ignore = false

  @ignore_patterns.each do |pat|
    if filename =~ /#{pat}/
      ignore = true
      break
    end
  end

  ignore
end

#should_mark_iterm?Boolean

Returns:

  • (Boolean)


136
137
138
# File 'lib/howzit/buildnotes.rb', line 136

def should_mark_iterm?
  ENV['TERM_PROGRAM'] =~ /^iTerm/ && !@options[:run] && !@options[:paginate]
end

#show(string, opts = {}) ⇒ Object

print output to terminal



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

def show(string, opts = {})
  options = {
    color: true,
    highlight: false,
    wrap: 0
  }

  options.merge!(opts)

  string = string.uncolor unless options[:color]

  pipes = ''
  if options[:highlight]
    hl = which_highlighter
    pipes = "|#{hl}" if hl
  end

  output = `echo #{Shellwords.escape(string.strip)}#{pipes}`

  if @options[:paginate]
    page(output)
  else
    puts output
  end
end

#template_folderObject



1054
1055
1056
# File 'lib/howzit/buildnotes.rb', line 1054

def template_folder
  File.join(config_dir, 'templates')
end

#topicsObject



9
10
11
# File 'lib/howzit/buildnotes.rb', line 9

def topics
  @topics ||= read_help
end

#which_highlighterObject

If either mdless or mdcat are installed, use that for highlighting markdown



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

def which_highlighter
  if @options[:highlighter] =~ /auto/i
    highlighters = %w[mdcat mdless]
    highlighters.delete_if(&:nil?).select!(&:available?)
    return nil if highlighters.empty?

    hl = highlighters.first
    args = case hl
           when 'mdless'
             '--no-pager'
           end

    [hl, args].join(' ')
  else
    hl = @options[:highlighter].split(/ /)[0]
    if hl.available?
      @options[:highlighter]
    else
      warn 'Specified highlighter not found, switching to auto' if @options[:log_level] < 2
      @options[:highlighter] = 'auto'
      which_highlighter
    end
  end
end

#which_pagerObject

When pagination is enabled, find the best (in my opinion) option, favoring environment settings



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

def which_pager
  if @options[:pager] =~ /auto/i
    pagers = [ENV['PAGER'], ENV['GIT_PAGER'],
              'bat', 'less', 'more', 'pager']
    pagers.delete_if(&:nil?).select!(&:available?)
    return nil if pagers.empty?

    pg = pagers.first
    args = case pg
           when 'delta'
             '--pager="less -FXr"'
           when /^(less|more)$/
             '-FXr'
           when 'bat'
             if @options[:highlight]
               '--language Markdown --style plain --pager="less -FXr"'
             else
               '--style plain --pager="less -FXr"'
             end
           else
             ''
           end

    [pg, args].join(' ')
  else
    pg = @options[:pager].split(/ /)[0]
    if pg.available?
      @options[:pager]
    else
      warn 'Specified pager not found, switching to auto' if @options[:log_level] < 2
      @options[:pager] = 'auto'
      which_pager
    end
  end
end

#write_config(config) ⇒ Object



1080
1081
1082
# File 'lib/howzit/buildnotes.rb', line 1080

def write_config(config)
  File.open(config_file, 'w') { |f| f.puts config.to_yaml }
end