-
Notifications
You must be signed in to change notification settings - Fork 240
Generating warnings
JSDuck generates lots of helpful warnings, and by writing a custom tag you can give your own custom warnings.
To print a warning you simply call the builtin JsDuck::Logger.warn method. It takes three arguments:
JsDuck::Logger.warn(warning_type, message, position)
-
warning_typeis either one of the builtin types ornil. Because we are creating custom warnings we'll be usingnilfor the rest of this tutorial. -
messageis the actual warning message to print. -
positiondefines a file name and line number to give the context for the warning. Inparse_docandprocess_docthe position gets passed in as parameter. In other methods we'll get the position fromcontexthash.
Extending the @license tag example we can print a warning when @license isn't followed by a name of any kind:
require "jsduck/tag/tag"
require "jsduck/logger"
class License < JsDuck::Tag::Tag
def parse_doc(scanner, position)
text = scanner.match(/.*$/)
if text.length == 0
JsDuck::Logger.warn(nil, "@license expects a name as argument", position)
end
return { :tagname => :license, :text => text }
end
...
endWhen we now run JSDuck over a file with such invalid @license tag, we get a warning like this:
Warning: /home/user/license-example.js:12: @license expects a name as argument
We can print the same kind of warning inside process_doc in pretty much the same way:
def process_doc(context, license_tags, position)
context[:license] = license_tags.map do |tag|
if tag[:text].length == 0
JsDuck::Logger.warn(nil, "@license expects a name as argument", position)
end
tag[:text]
end
endIn to_html method no position parameter gets passed in, but the position is available within the context hash:
def to_html(context)
if context[:license].any? {|license| license[:name].length == 0 }
position = context[:files][0]
JsDuck::Logger.warn(nil, "@license expects a name as argument", position)
end
licenses = context[:license].map {|license| "<b>#{license}</b>" }.join(" and ")
<<-EOHTML
<p>This software is licensed under: #{licenses}.</p>
EOHTML
endDocumentation of a class can be merged together from several /** @class */ doc-comments. That's why the context[:files] is an array of the positions of all those merged doc-comments. This kind of code is quite rare though, and no such merging happens for class members. So normally it's good enough to just take the first position out of this array and ignore the rest.