Class: Uniword::TocCLI

Inherits:
Thor
  • Object
show all
Includes:
CLIHelpers
Defined in:
lib/uniword/cli/toc_cli.rb

Overview

TOC subcommands for Uniword CLI.

Provides commands for generating, inserting, and updating Table of Contents in DOCX documents:

  • generate: list heading entries from a document

  • insert: insert a TOC field into a document

  • update: refresh an existing TOC field

Instance Method Summary collapse

Methods included from CLIHelpers

included

Instance Method Details

#generate(path) ⇒ Object



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

def generate(path)
  doc = load_document(path)
  generator = Uniword::Toc::TocGenerator.new(doc)
  entries = generator.generate(max_level: options[:max_level])

  if entries.empty?
    say "No headings found in document.", :yellow
    return
  end

  if options[:json]
    puts JSON.pretty_generate(entries.map(&:to_h))
  else
    display_entries(entries)
  end
rescue Uniword::Error => e
  handle_error(e)
rescue StandardError => e
  handle_error(e, verbose: options[:verbose])
end

#insert(path) ⇒ Object



74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
# File 'lib/uniword/cli/toc_cli.rb', line 74

def insert(path)
  doc = load_document(path)
  generator = Uniword::Toc::TocGenerator.new(doc)
  entries = generator.generate(max_level: options[:max_level])

  if entries.empty?
    say "No headings found. Nothing to insert.", :yellow
    return
  end

  generator.insert(entries,
                   position: options[:position],
                   max_level: options[:max_level])

  doc.save(options[:output])

  say "TOC inserted with #{entries.count} entries at " \
      "position #{options[:position]}.", :green
  say "Saved to: #{options[:output]}", :green
rescue Uniword::Error => e
  handle_error(e)
rescue StandardError => e
  handle_error(e, verbose: options[:verbose])
end

#update(path) ⇒ Object



115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
# File 'lib/uniword/cli/toc_cli.rb', line 115

def update(path)
  doc = load_document(path)
  generator = Uniword::Toc::TocGenerator.new(doc)
  entries = generator.update(max_level: options[:max_level])

  if entries.empty?
    say "No existing TOC found or no headings in document.", :yellow
    return
  end

  doc.save(options[:output])

  say "TOC updated with #{entries.count} entries.", :green
  say "Saved to: #{options[:output]}", :green
rescue Uniword::Error => e
  handle_error(e)
rescue StandardError => e
  handle_error(e, verbose: options[:verbose])
end