comparison vendor/plugins/coderay-0.9.2/lib/coderay/encoders/lines_of_code.rb @ 0:513646585e45

* Import Redmine trunk SVN rev 3859
author Chris Cannam
date Fri, 23 Jul 2010 15:52:44 +0100
parents
children
comparison
equal deleted inserted replaced
-1:000000000000 0:513646585e45
1 ($:.unshift '../..'; require 'coderay') unless defined? CodeRay
2 module CodeRay
3 module Encoders
4
5 # Counts the LoC (Lines of Code). Returns an Integer >= 0.
6 #
7 # Alias: :loc
8 #
9 # Everything that is not comment, markup, doctype/shebang, or an empty line,
10 # is considered to be code.
11 #
12 # For example,
13 # * HTML files not containing JavaScript have 0 LoC
14 # * in a Java class without comments, LoC is the number of non-empty lines
15 #
16 # A Scanner class should define the token kinds that are not code in the
17 # KINDS_NOT_LOC constant, which defaults to [:comment, :doctype].
18 class LinesOfCode < Encoder
19
20 register_for :lines_of_code
21
22 NON_EMPTY_LINE = /^\s*\S.*$/
23
24 def compile tokens, options
25 if scanner = tokens.scanner
26 kinds_not_loc = scanner.class::KINDS_NOT_LOC
27 else
28 warn ArgumentError, 'Tokens have no scanner.' if $VERBOSE
29 kinds_not_loc = CodeRay::Scanners::Scanner::KINDS_NOT_LOC
30 end
31 code = tokens.token_class_filter :exclude => kinds_not_loc
32 @loc = code.text.scan(NON_EMPTY_LINE).size
33 end
34
35 def finish options
36 @loc
37 end
38
39 end
40
41 end
42 end
43
44 if $0 == __FILE__
45 $VERBOSE = true
46 $: << File.join(File.dirname(__FILE__), '..')
47 eval DATA.read, nil, $0, __LINE__ + 4
48 end
49
50 __END__
51 require 'test/unit'
52
53 class LinesOfCodeTest < Test::Unit::TestCase
54
55 def test_creation
56 assert CodeRay::Encoders::LinesOfCode < CodeRay::Encoders::Encoder
57 filter = nil
58 assert_nothing_raised do
59 filter = CodeRay.encoder :loc
60 end
61 assert_kind_of CodeRay::Encoders::LinesOfCode, filter
62 assert_nothing_raised do
63 filter = CodeRay.encoder :lines_of_code
64 end
65 assert_kind_of CodeRay::Encoders::LinesOfCode, filter
66 end
67
68 def test_lines_of_code
69 tokens = CodeRay.scan <<-RUBY, :ruby
70 #!/usr/bin/env ruby
71
72 # a minimal Ruby program
73 puts "Hello world!"
74 RUBY
75 assert_equal 1, CodeRay::Encoders::LinesOfCode.new.encode_tokens(tokens)
76 assert_equal 1, tokens.lines_of_code
77 assert_equal 1, tokens.loc
78 end
79
80 def test_filtering_block_tokens
81 tokens = CodeRay::Tokens.new
82 tokens << ["Hello\n", :world]
83 tokens << ["Hello\n", :space]
84 tokens << ["Hello\n", :comment]
85 assert_equal 2, CodeRay::Encoders::LinesOfCode.new.encode_tokens(tokens)
86 assert_equal 2, tokens.lines_of_code
87 assert_equal 2, tokens.loc
88 end
89
90 end