Adds a branch for unlimited project hierarchy.
git-svn-id: svn+ssh://rubyforge.org/var/svn/redmine/branches/work@2148 e93f8b46-1217-0410-a6f0-8f06a7374b81
This commit is contained in:
@@ -0,0 +1,340 @@
|
||||
GNU GENERAL PUBLIC LICENSE
|
||||
Version 2, June 1991
|
||||
|
||||
Copyright (C) 1989, 1991 Free Software Foundation, Inc.
|
||||
59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
|
||||
Everyone is permitted to copy and distribute verbatim copies
|
||||
of this license document, but changing it is not allowed.
|
||||
|
||||
Preamble
|
||||
|
||||
The licenses for most software are designed to take away your
|
||||
freedom to share and change it. By contrast, the GNU General Public
|
||||
License is intended to guarantee your freedom to share and change free
|
||||
software--to make sure the software is free for all its users. This
|
||||
General Public License applies to most of the Free Software
|
||||
Foundation's software and to any other program whose authors commit to
|
||||
using it. (Some other Free Software Foundation software is covered by
|
||||
the GNU Library General Public License instead.) You can apply it to
|
||||
your programs, too.
|
||||
|
||||
When we speak of free software, we are referring to freedom, not
|
||||
price. Our General Public Licenses are designed to make sure that you
|
||||
have the freedom to distribute copies of free software (and charge for
|
||||
this service if you wish), that you receive source code or can get it
|
||||
if you want it, that you can change the software or use pieces of it
|
||||
in new free programs; and that you know you can do these things.
|
||||
|
||||
To protect your rights, we need to make restrictions that forbid
|
||||
anyone to deny you these rights or to ask you to surrender the rights.
|
||||
These restrictions translate to certain responsibilities for you if you
|
||||
distribute copies of the software, or if you modify it.
|
||||
|
||||
For example, if you distribute copies of such a program, whether
|
||||
gratis or for a fee, you must give the recipients all the rights that
|
||||
you have. You must make sure that they, too, receive or can get the
|
||||
source code. And you must show them these terms so they know their
|
||||
rights.
|
||||
|
||||
We protect your rights with two steps: (1) copyright the software, and
|
||||
(2) offer you this license which gives you legal permission to copy,
|
||||
distribute and/or modify the software.
|
||||
|
||||
Also, for each author's protection and ours, we want to make certain
|
||||
that everyone understands that there is no warranty for this free
|
||||
software. If the software is modified by someone else and passed on, we
|
||||
want its recipients to know that what they have is not the original, so
|
||||
that any problems introduced by others will not reflect on the original
|
||||
authors' reputations.
|
||||
|
||||
Finally, any free program is threatened constantly by software
|
||||
patents. We wish to avoid the danger that redistributors of a free
|
||||
program will individually obtain patent licenses, in effect making the
|
||||
program proprietary. To prevent this, we have made it clear that any
|
||||
patent must be licensed for everyone's free use or not licensed at all.
|
||||
|
||||
The precise terms and conditions for copying, distribution and
|
||||
modification follow.
|
||||
|
||||
GNU GENERAL PUBLIC LICENSE
|
||||
TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
|
||||
|
||||
0. This License applies to any program or other work which contains
|
||||
a notice placed by the copyright holder saying it may be distributed
|
||||
under the terms of this General Public License. The "Program", below,
|
||||
refers to any such program or work, and a "work based on the Program"
|
||||
means either the Program or any derivative work under copyright law:
|
||||
that is to say, a work containing the Program or a portion of it,
|
||||
either verbatim or with modifications and/or translated into another
|
||||
language. (Hereinafter, translation is included without limitation in
|
||||
the term "modification".) Each licensee is addressed as "you".
|
||||
|
||||
Activities other than copying, distribution and modification are not
|
||||
covered by this License; they are outside its scope. The act of
|
||||
running the Program is not restricted, and the output from the Program
|
||||
is covered only if its contents constitute a work based on the
|
||||
Program (independent of having been made by running the Program).
|
||||
Whether that is true depends on what the Program does.
|
||||
|
||||
1. You may copy and distribute verbatim copies of the Program's
|
||||
source code as you receive it, in any medium, provided that you
|
||||
conspicuously and appropriately publish on each copy an appropriate
|
||||
copyright notice and disclaimer of warranty; keep intact all the
|
||||
notices that refer to this License and to the absence of any warranty;
|
||||
and give any other recipients of the Program a copy of this License
|
||||
along with the Program.
|
||||
|
||||
You may charge a fee for the physical act of transferring a copy, and
|
||||
you may at your option offer warranty protection in exchange for a fee.
|
||||
|
||||
2. You may modify your copy or copies of the Program or any portion
|
||||
of it, thus forming a work based on the Program, and copy and
|
||||
distribute such modifications or work under the terms of Section 1
|
||||
above, provided that you also meet all of these conditions:
|
||||
|
||||
a) You must cause the modified files to carry prominent notices
|
||||
stating that you changed the files and the date of any change.
|
||||
|
||||
b) You must cause any work that you distribute or publish, that in
|
||||
whole or in part contains or is derived from the Program or any
|
||||
part thereof, to be licensed as a whole at no charge to all third
|
||||
parties under the terms of this License.
|
||||
|
||||
c) If the modified program normally reads commands interactively
|
||||
when run, you must cause it, when started running for such
|
||||
interactive use in the most ordinary way, to print or display an
|
||||
announcement including an appropriate copyright notice and a
|
||||
notice that there is no warranty (or else, saying that you provide
|
||||
a warranty) and that users may redistribute the program under
|
||||
these conditions, and telling the user how to view a copy of this
|
||||
License. (Exception: if the Program itself is interactive but
|
||||
does not normally print such an announcement, your work based on
|
||||
the Program is not required to print an announcement.)
|
||||
|
||||
These requirements apply to the modified work as a whole. If
|
||||
identifiable sections of that work are not derived from the Program,
|
||||
and can be reasonably considered independent and separate works in
|
||||
themselves, then this License, and its terms, do not apply to those
|
||||
sections when you distribute them as separate works. But when you
|
||||
distribute the same sections as part of a whole which is a work based
|
||||
on the Program, the distribution of the whole must be on the terms of
|
||||
this License, whose permissions for other licensees extend to the
|
||||
entire whole, and thus to each and every part regardless of who wrote it.
|
||||
|
||||
Thus, it is not the intent of this section to claim rights or contest
|
||||
your rights to work written entirely by you; rather, the intent is to
|
||||
exercise the right to control the distribution of derivative or
|
||||
collective works based on the Program.
|
||||
|
||||
In addition, mere aggregation of another work not based on the Program
|
||||
with the Program (or with a work based on the Program) on a volume of
|
||||
a storage or distribution medium does not bring the other work under
|
||||
the scope of this License.
|
||||
|
||||
3. You may copy and distribute the Program (or a work based on it,
|
||||
under Section 2) in object code or executable form under the terms of
|
||||
Sections 1 and 2 above provided that you also do one of the following:
|
||||
|
||||
a) Accompany it with the complete corresponding machine-readable
|
||||
source code, which must be distributed under the terms of Sections
|
||||
1 and 2 above on a medium customarily used for software interchange; or,
|
||||
|
||||
b) Accompany it with a written offer, valid for at least three
|
||||
years, to give any third party, for a charge no more than your
|
||||
cost of physically performing source distribution, a complete
|
||||
machine-readable copy of the corresponding source code, to be
|
||||
distributed under the terms of Sections 1 and 2 above on a medium
|
||||
customarily used for software interchange; or,
|
||||
|
||||
c) Accompany it with the information you received as to the offer
|
||||
to distribute corresponding source code. (This alternative is
|
||||
allowed only for noncommercial distribution and only if you
|
||||
received the program in object code or executable form with such
|
||||
an offer, in accord with Subsection b above.)
|
||||
|
||||
The source code for a work means the preferred form of the work for
|
||||
making modifications to it. For an executable work, complete source
|
||||
code means all the source code for all modules it contains, plus any
|
||||
associated interface definition files, plus the scripts used to
|
||||
control compilation and installation of the executable. However, as a
|
||||
special exception, the source code distributed need not include
|
||||
anything that is normally distributed (in either source or binary
|
||||
form) with the major components (compiler, kernel, and so on) of the
|
||||
operating system on which the executable runs, unless that component
|
||||
itself accompanies the executable.
|
||||
|
||||
If distribution of executable or object code is made by offering
|
||||
access to copy from a designated place, then offering equivalent
|
||||
access to copy the source code from the same place counts as
|
||||
distribution of the source code, even though third parties are not
|
||||
compelled to copy the source along with the object code.
|
||||
|
||||
4. You may not copy, modify, sublicense, or distribute the Program
|
||||
except as expressly provided under this License. Any attempt
|
||||
otherwise to copy, modify, sublicense or distribute the Program is
|
||||
void, and will automatically terminate your rights under this License.
|
||||
However, parties who have received copies, or rights, from you under
|
||||
this License will not have their licenses terminated so long as such
|
||||
parties remain in full compliance.
|
||||
|
||||
5. You are not required to accept this License, since you have not
|
||||
signed it. However, nothing else grants you permission to modify or
|
||||
distribute the Program or its derivative works. These actions are
|
||||
prohibited by law if you do not accept this License. Therefore, by
|
||||
modifying or distributing the Program (or any work based on the
|
||||
Program), you indicate your acceptance of this License to do so, and
|
||||
all its terms and conditions for copying, distributing or modifying
|
||||
the Program or works based on it.
|
||||
|
||||
6. Each time you redistribute the Program (or any work based on the
|
||||
Program), the recipient automatically receives a license from the
|
||||
original licensor to copy, distribute or modify the Program subject to
|
||||
these terms and conditions. You may not impose any further
|
||||
restrictions on the recipients' exercise of the rights granted herein.
|
||||
You are not responsible for enforcing compliance by third parties to
|
||||
this License.
|
||||
|
||||
7. If, as a consequence of a court judgment or allegation of patent
|
||||
infringement or for any other reason (not limited to patent issues),
|
||||
conditions are imposed on you (whether by court order, agreement or
|
||||
otherwise) that contradict the conditions of this License, they do not
|
||||
excuse you from the conditions of this License. If you cannot
|
||||
distribute so as to satisfy simultaneously your obligations under this
|
||||
License and any other pertinent obligations, then as a consequence you
|
||||
may not distribute the Program at all. For example, if a patent
|
||||
license would not permit royalty-free redistribution of the Program by
|
||||
all those who receive copies directly or indirectly through you, then
|
||||
the only way you could satisfy both it and this License would be to
|
||||
refrain entirely from distribution of the Program.
|
||||
|
||||
If any portion of this section is held invalid or unenforceable under
|
||||
any particular circumstance, the balance of the section is intended to
|
||||
apply and the section as a whole is intended to apply in other
|
||||
circumstances.
|
||||
|
||||
It is not the purpose of this section to induce you to infringe any
|
||||
patents or other property right claims or to contest validity of any
|
||||
such claims; this section has the sole purpose of protecting the
|
||||
integrity of the free software distribution system, which is
|
||||
implemented by public license practices. Many people have made
|
||||
generous contributions to the wide range of software distributed
|
||||
through that system in reliance on consistent application of that
|
||||
system; it is up to the author/donor to decide if he or she is willing
|
||||
to distribute software through any other system and a licensee cannot
|
||||
impose that choice.
|
||||
|
||||
This section is intended to make thoroughly clear what is believed to
|
||||
be a consequence of the rest of this License.
|
||||
|
||||
8. If the distribution and/or use of the Program is restricted in
|
||||
certain countries either by patents or by copyrighted interfaces, the
|
||||
original copyright holder who places the Program under this License
|
||||
may add an explicit geographical distribution limitation excluding
|
||||
those countries, so that distribution is permitted only in or among
|
||||
countries not thus excluded. In such case, this License incorporates
|
||||
the limitation as if written in the body of this License.
|
||||
|
||||
9. The Free Software Foundation may publish revised and/or new versions
|
||||
of the General Public License from time to time. Such new versions will
|
||||
be similar in spirit to the present version, but may differ in detail to
|
||||
address new problems or concerns.
|
||||
|
||||
Each version is given a distinguishing version number. If the Program
|
||||
specifies a version number of this License which applies to it and "any
|
||||
later version", you have the option of following the terms and conditions
|
||||
either of that version or of any later version published by the Free
|
||||
Software Foundation. If the Program does not specify a version number of
|
||||
this License, you may choose any version ever published by the Free Software
|
||||
Foundation.
|
||||
|
||||
10. If you wish to incorporate parts of the Program into other free
|
||||
programs whose distribution conditions are different, write to the author
|
||||
to ask for permission. For software which is copyrighted by the Free
|
||||
Software Foundation, write to the Free Software Foundation; we sometimes
|
||||
make exceptions for this. Our decision will be guided by the two goals
|
||||
of preserving the free status of all derivatives of our free software and
|
||||
of promoting the sharing and reuse of software generally.
|
||||
|
||||
NO WARRANTY
|
||||
|
||||
11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY
|
||||
FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN
|
||||
OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES
|
||||
PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED
|
||||
OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
|
||||
MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS
|
||||
TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE
|
||||
PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING,
|
||||
REPAIR OR CORRECTION.
|
||||
|
||||
12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
|
||||
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR
|
||||
REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES,
|
||||
INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING
|
||||
OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED
|
||||
TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY
|
||||
YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER
|
||||
PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE
|
||||
POSSIBILITY OF SUCH DAMAGES.
|
||||
|
||||
END OF TERMS AND CONDITIONS
|
||||
|
||||
How to Apply These Terms to Your New Programs
|
||||
|
||||
If you develop a new program, and you want it to be of the greatest
|
||||
possible use to the public, the best way to achieve this is to make it
|
||||
free software which everyone can redistribute and change under these terms.
|
||||
|
||||
To do so, attach the following notices to the program. It is safest
|
||||
to attach them to the start of each source file to most effectively
|
||||
convey the exclusion of warranty; and each file should have at least
|
||||
the "copyright" line and a pointer to where the full notice is found.
|
||||
|
||||
<one line to give the program's name and a brief idea of what it does.>
|
||||
Copyright (C) <year> <name of author>
|
||||
|
||||
This program is free software; you can redistribute it and/or modify
|
||||
it under the terms of the GNU General Public License as published by
|
||||
the Free Software Foundation; either version 2 of the License, or
|
||||
(at your option) any later version.
|
||||
|
||||
This program is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
GNU General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU General Public License
|
||||
along with this program; if not, write to the Free Software
|
||||
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
|
||||
|
||||
|
||||
Also add information on how to contact you by electronic and paper mail.
|
||||
|
||||
If the program is interactive, make it output a short notice like this
|
||||
when it starts in an interactive mode:
|
||||
|
||||
Gnomovision version 69, Copyright (C) year name of author
|
||||
Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
|
||||
This is free software, and you are welcome to redistribute it
|
||||
under certain conditions; type `show c' for details.
|
||||
|
||||
The hypothetical commands `show w' and `show c' should show the appropriate
|
||||
parts of the General Public License. Of course, the commands you use may
|
||||
be called something other than `show w' and `show c'; they could even be
|
||||
mouse-clicks or menu items--whatever suits your program.
|
||||
|
||||
You should also get your employer (if you work as a programmer) or your
|
||||
school, if any, to sign a "copyright disclaimer" for the program, if
|
||||
necessary. Here is a sample; alter the names:
|
||||
|
||||
Yoyodyne, Inc., hereby disclaims all copyright interest in the program
|
||||
`Gnomovision' (which makes passes at compilers) written by James Hacker.
|
||||
|
||||
<signature of Ty Coon>, 1 April 1989
|
||||
Ty Coon, President of Vice
|
||||
|
||||
This General Public License does not permit incorporating your program into
|
||||
proprietary programs. If your program is a subroutine library, you may
|
||||
consider it more useful to permit linking proprietary applications with the
|
||||
library. If this is what you want to do, use the GNU Library General
|
||||
Public License instead of this License.
|
||||
@@ -0,0 +1,137 @@
|
||||
require 'rexml/document'
|
||||
require 'SVG/Graph/Graph'
|
||||
require 'SVG/Graph/BarBase'
|
||||
|
||||
module SVG
|
||||
module Graph
|
||||
# === Create presentation quality SVG bar graphs easily
|
||||
#
|
||||
# = Synopsis
|
||||
#
|
||||
# require 'SVG/Graph/Bar'
|
||||
#
|
||||
# fields = %w(Jan Feb Mar);
|
||||
# data_sales_02 = [12, 45, 21]
|
||||
#
|
||||
# graph = SVG::Graph::Bar.new(
|
||||
# :height => 500,
|
||||
# :width => 300,
|
||||
# :fields => fields
|
||||
# )
|
||||
#
|
||||
# graph.add_data(
|
||||
# :data => data_sales_02,
|
||||
# :title => 'Sales 2002'
|
||||
# )
|
||||
#
|
||||
# print "Content-type: image/svg+xml\r\n\r\n"
|
||||
# print graph.burn
|
||||
#
|
||||
# = Description
|
||||
#
|
||||
# This object aims to allow you to easily create high quality
|
||||
# SVG[http://www.w3c.org/tr/svg bar graphs. You can either use the default
|
||||
# style sheet or supply your own. Either way there are many options which
|
||||
# can be configured to give you control over how the graph is generated -
|
||||
# with or without a key, data elements at each point, title, subtitle etc.
|
||||
#
|
||||
# = Notes
|
||||
#
|
||||
# The default stylesheet handles upto 12 data sets, if you
|
||||
# use more you must create your own stylesheet and add the
|
||||
# additional settings for the extra data sets. You will know
|
||||
# if you go over 12 data sets as they will have no style and
|
||||
# be in black.
|
||||
#
|
||||
# = Examples
|
||||
#
|
||||
# * http://germane-software.com/repositories/public/SVG/test/test.rb
|
||||
#
|
||||
# = See also
|
||||
#
|
||||
# * SVG::Graph::Graph
|
||||
# * SVG::Graph::BarHorizontal
|
||||
# * SVG::Graph::Line
|
||||
# * SVG::Graph::Pie
|
||||
# * SVG::Graph::Plot
|
||||
# * SVG::Graph::TimeSeries
|
||||
class Bar < BarBase
|
||||
include REXML
|
||||
|
||||
# See Graph::initialize and BarBase::set_defaults
|
||||
def set_defaults
|
||||
super
|
||||
self.top_align = self.top_font = 1
|
||||
end
|
||||
|
||||
protected
|
||||
|
||||
def get_x_labels
|
||||
@config[:fields]
|
||||
end
|
||||
|
||||
def get_y_labels
|
||||
maxvalue = max_value
|
||||
minvalue = min_value
|
||||
range = maxvalue - minvalue
|
||||
|
||||
top_pad = range == 0 ? 10 : range / 20.0
|
||||
scale_range = (maxvalue + top_pad) - minvalue
|
||||
|
||||
scale_division = scale_divisions || (scale_range / 10.0)
|
||||
|
||||
if scale_integers
|
||||
scale_division = scale_division < 1 ? 1 : scale_division.round
|
||||
end
|
||||
|
||||
rv = []
|
||||
maxvalue = maxvalue%scale_division == 0 ?
|
||||
maxvalue : maxvalue + scale_division
|
||||
minvalue.step( maxvalue, scale_division ) {|v| rv << v}
|
||||
return rv
|
||||
end
|
||||
|
||||
def x_label_offset( width )
|
||||
width / 2.0
|
||||
end
|
||||
|
||||
def draw_data
|
||||
fieldwidth = field_width
|
||||
maxvalue = max_value
|
||||
minvalue = min_value
|
||||
|
||||
fieldheight = (@graph_height.to_f - font_size*2*top_font) /
|
||||
(get_y_labels.max - get_y_labels.min)
|
||||
bargap = bar_gap ? (fieldwidth < 10 ? fieldwidth / 2 : 10) : 0
|
||||
|
||||
subbar_width = fieldwidth - bargap
|
||||
subbar_width /= @data.length if stack == :side
|
||||
x_mod = (@graph_width-bargap)/2 - (stack==:side ? subbar_width/2 : 0)
|
||||
# Y1
|
||||
p2 = @graph_height
|
||||
# to X2
|
||||
field_count = 0
|
||||
@config[:fields].each_index { |i|
|
||||
dataset_count = 0
|
||||
for dataset in @data
|
||||
# X1
|
||||
p1 = (fieldwidth * field_count)
|
||||
# to Y2
|
||||
p3 = @graph_height - ((dataset[:data][i] - minvalue) * fieldheight)
|
||||
p1 += subbar_width * dataset_count if stack == :side
|
||||
@graph.add_element( "path", {
|
||||
"class" => "fill#{dataset_count+1}",
|
||||
"d" => "M#{p1} #{p2} V#{p3} h#{subbar_width} V#{p2} Z"
|
||||
})
|
||||
make_datapoint_text(
|
||||
p1 + subbar_width/2.0,
|
||||
p3 - 6,
|
||||
dataset[:data][i].to_s)
|
||||
dataset_count += 1
|
||||
end
|
||||
field_count += 1
|
||||
}
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
@@ -0,0 +1,140 @@
|
||||
require 'rexml/document'
|
||||
require 'SVG/Graph/Graph'
|
||||
|
||||
module SVG
|
||||
module Graph
|
||||
# = Synopsis
|
||||
#
|
||||
# A superclass for bar-style graphs. Do not attempt to instantiate
|
||||
# directly; use one of the subclasses instead.
|
||||
#
|
||||
# = Author
|
||||
#
|
||||
# Sean E. Russell <serATgermaneHYPHENsoftwareDOTcom>
|
||||
#
|
||||
# Copyright 2004 Sean E. Russell
|
||||
# This software is available under the Ruby license[LICENSE.txt]
|
||||
#
|
||||
class BarBase < SVG::Graph::Graph
|
||||
# Ensures that :fields are provided in the configuration.
|
||||
def initialize config
|
||||
raise "fields was not supplied or is empty" unless config[:fields] &&
|
||||
config[:fields].kind_of?(Array) &&
|
||||
config[:fields].length > 0
|
||||
super
|
||||
end
|
||||
|
||||
# In addition to the defaults set in Graph::initialize, sets
|
||||
# [bar_gap] true
|
||||
# [stack] :overlap
|
||||
def set_defaults
|
||||
init_with( :bar_gap => true, :stack => :overlap )
|
||||
end
|
||||
|
||||
# Whether to have a gap between the bars or not, default
|
||||
# is true, set to false if you don't want gaps.
|
||||
attr_accessor :bar_gap
|
||||
# How to stack data sets. :overlap overlaps bars with
|
||||
# transparent colors, :top stacks bars on top of one another,
|
||||
# :side stacks the bars side-by-side. Defaults to :overlap.
|
||||
attr_accessor :stack
|
||||
|
||||
|
||||
protected
|
||||
|
||||
def max_value
|
||||
return @data.collect{|x| x[:data].max}.max
|
||||
end
|
||||
|
||||
def min_value
|
||||
min = 0
|
||||
|
||||
if (min_scale_value.nil? == false) then
|
||||
min = min_scale_value
|
||||
else
|
||||
min = @data.collect{|x| x[:data].min}.min
|
||||
end
|
||||
|
||||
return min
|
||||
end
|
||||
|
||||
def get_css
|
||||
return <<EOL
|
||||
/* default fill styles for multiple datasets (probably only use a single dataset on this graph though) */
|
||||
.key1,.fill1{
|
||||
fill: #ff0000;
|
||||
fill-opacity: 0.5;
|
||||
stroke: none;
|
||||
stroke-width: 0.5px;
|
||||
}
|
||||
.key2,.fill2{
|
||||
fill: #0000ff;
|
||||
fill-opacity: 0.5;
|
||||
stroke: none;
|
||||
stroke-width: 1px;
|
||||
}
|
||||
.key3,.fill3{
|
||||
fill: #00ff00;
|
||||
fill-opacity: 0.5;
|
||||
stroke: none;
|
||||
stroke-width: 1px;
|
||||
}
|
||||
.key4,.fill4{
|
||||
fill: #ffcc00;
|
||||
fill-opacity: 0.5;
|
||||
stroke: none;
|
||||
stroke-width: 1px;
|
||||
}
|
||||
.key5,.fill5{
|
||||
fill: #00ccff;
|
||||
fill-opacity: 0.5;
|
||||
stroke: none;
|
||||
stroke-width: 1px;
|
||||
}
|
||||
.key6,.fill6{
|
||||
fill: #ff00ff;
|
||||
fill-opacity: 0.5;
|
||||
stroke: none;
|
||||
stroke-width: 1px;
|
||||
}
|
||||
.key7,.fill7{
|
||||
fill: #00ffff;
|
||||
fill-opacity: 0.5;
|
||||
stroke: none;
|
||||
stroke-width: 1px;
|
||||
}
|
||||
.key8,.fill8{
|
||||
fill: #ffff00;
|
||||
fill-opacity: 0.5;
|
||||
stroke: none;
|
||||
stroke-width: 1px;
|
||||
}
|
||||
.key9,.fill9{
|
||||
fill: #cc6666;
|
||||
fill-opacity: 0.5;
|
||||
stroke: none;
|
||||
stroke-width: 1px;
|
||||
}
|
||||
.key10,.fill10{
|
||||
fill: #663399;
|
||||
fill-opacity: 0.5;
|
||||
stroke: none;
|
||||
stroke-width: 1px;
|
||||
}
|
||||
.key11,.fill11{
|
||||
fill: #339900;
|
||||
fill-opacity: 0.5;
|
||||
stroke: none;
|
||||
stroke-width: 1px;
|
||||
}
|
||||
.key12,.fill12{
|
||||
fill: #9966FF;
|
||||
fill-opacity: 0.5;
|
||||
stroke: none;
|
||||
stroke-width: 1px;
|
||||
}
|
||||
EOL
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
@@ -0,0 +1,136 @@
|
||||
require 'rexml/document'
|
||||
require 'SVG/Graph/BarBase'
|
||||
|
||||
module SVG
|
||||
module Graph
|
||||
# === Create presentation quality SVG horitonzal bar graphs easily
|
||||
#
|
||||
# = Synopsis
|
||||
#
|
||||
# require 'SVG/Graph/BarHorizontal'
|
||||
#
|
||||
# fields = %w(Jan Feb Mar)
|
||||
# data_sales_02 = [12, 45, 21]
|
||||
#
|
||||
# graph = SVG::Graph::BarHorizontal.new({
|
||||
# :height => 500,
|
||||
# :width => 300,
|
||||
# :fields => fields,
|
||||
# })
|
||||
#
|
||||
# graph.add_data({
|
||||
# :data => data_sales_02,
|
||||
# :title => 'Sales 2002',
|
||||
# })
|
||||
#
|
||||
# print "Content-type: image/svg+xml\r\n\r\n"
|
||||
# print graph.burn
|
||||
#
|
||||
# = Description
|
||||
#
|
||||
# This object aims to allow you to easily create high quality
|
||||
# SVG horitonzal bar graphs. You can either use the default style sheet
|
||||
# or supply your own. Either way there are many options which can
|
||||
# be configured to give you control over how the graph is
|
||||
# generated - with or without a key, data elements at each point,
|
||||
# title, subtitle etc.
|
||||
#
|
||||
# = Examples
|
||||
#
|
||||
# * http://germane-software.com/repositories/public/SVG/test/test.rb
|
||||
#
|
||||
# = See also
|
||||
#
|
||||
# * SVG::Graph::Graph
|
||||
# * SVG::Graph::Bar
|
||||
# * SVG::Graph::Line
|
||||
# * SVG::Graph::Pie
|
||||
# * SVG::Graph::Plot
|
||||
# * SVG::Graph::TimeSeries
|
||||
#
|
||||
# == Author
|
||||
#
|
||||
# Sean E. Russell <serATgermaneHYPHENsoftwareDOTcom>
|
||||
#
|
||||
# Copyright 2004 Sean E. Russell
|
||||
# This software is available under the Ruby license[LICENSE.txt]
|
||||
#
|
||||
class BarHorizontal < BarBase
|
||||
# In addition to the defaults set in BarBase::set_defaults, sets
|
||||
# [rotate_y_labels] true
|
||||
# [show_x_guidelines] true
|
||||
# [show_y_guidelines] false
|
||||
def set_defaults
|
||||
super
|
||||
init_with(
|
||||
:rotate_y_labels => true,
|
||||
:show_x_guidelines => true,
|
||||
:show_y_guidelines => false
|
||||
)
|
||||
self.right_align = self.right_font = 1
|
||||
end
|
||||
|
||||
protected
|
||||
|
||||
def get_x_labels
|
||||
maxvalue = max_value
|
||||
minvalue = min_value
|
||||
range = maxvalue - minvalue
|
||||
top_pad = range == 0 ? 10 : range / 20.0
|
||||
scale_range = (maxvalue + top_pad) - minvalue
|
||||
|
||||
scale_division = scale_divisions || (scale_range / 10.0)
|
||||
|
||||
if scale_integers
|
||||
scale_division = scale_division < 1 ? 1 : scale_division.round
|
||||
end
|
||||
|
||||
rv = []
|
||||
maxvalue = maxvalue%scale_division == 0 ?
|
||||
maxvalue : maxvalue + scale_division
|
||||
minvalue.step( maxvalue, scale_division ) {|v| rv << v}
|
||||
return rv
|
||||
end
|
||||
|
||||
def get_y_labels
|
||||
@config[:fields]
|
||||
end
|
||||
|
||||
def y_label_offset( height )
|
||||
height / -2.0
|
||||
end
|
||||
|
||||
def draw_data
|
||||
minvalue = min_value
|
||||
fieldheight = field_height
|
||||
fieldwidth = (@graph_width.to_f - font_size*2*right_font ) /
|
||||
(get_x_labels.max - get_x_labels.min )
|
||||
bargap = bar_gap ? (fieldheight < 10 ? fieldheight / 2 : 10) : 0
|
||||
|
||||
subbar_height = fieldheight - bargap
|
||||
subbar_height /= @data.length if stack == :side
|
||||
|
||||
field_count = 1
|
||||
y_mod = (subbar_height / 2) + (font_size / 2)
|
||||
@config[:fields].each_index { |i|
|
||||
dataset_count = 0
|
||||
for dataset in @data
|
||||
y = @graph_height - (fieldheight * field_count)
|
||||
y += (subbar_height * dataset_count) if stack == :side
|
||||
x = (dataset[:data][i] - minvalue) * fieldwidth
|
||||
|
||||
@graph.add_element( "path", {
|
||||
"d" => "M0 #{y} H#{x} v#{subbar_height} H0 Z",
|
||||
"class" => "fill#{dataset_count+1}"
|
||||
})
|
||||
make_datapoint_text(
|
||||
x+5, y+y_mod, dataset[:data][i], "text-anchor: start; "
|
||||
)
|
||||
dataset_count += 1
|
||||
end
|
||||
field_count += 1
|
||||
}
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
@@ -0,0 +1,977 @@
|
||||
begin
|
||||
require 'zlib'
|
||||
@@__have_zlib = true
|
||||
rescue
|
||||
@@__have_zlib = false
|
||||
end
|
||||
|
||||
require 'rexml/document'
|
||||
|
||||
module SVG
|
||||
module Graph
|
||||
VERSION = '@ANT_VERSION@'
|
||||
|
||||
# === Base object for generating SVG Graphs
|
||||
#
|
||||
# == Synopsis
|
||||
#
|
||||
# This class is only used as a superclass of specialized charts. Do not
|
||||
# attempt to use this class directly, unless creating a new chart type.
|
||||
#
|
||||
# For examples of how to subclass this class, see the existing specific
|
||||
# subclasses, such as SVG::Graph::Pie.
|
||||
#
|
||||
# == Examples
|
||||
#
|
||||
# For examples of how to use this package, see either the test files, or
|
||||
# the documentation for the specific class you want to use.
|
||||
#
|
||||
# * file:test/plot.rb
|
||||
# * file:test/single.rb
|
||||
# * file:test/test.rb
|
||||
# * file:test/timeseries.rb
|
||||
#
|
||||
# == Description
|
||||
#
|
||||
# This package should be used as a base for creating SVG graphs.
|
||||
#
|
||||
# == Acknowledgements
|
||||
#
|
||||
# Leo Lapworth for creating the SVG::TT::Graph package which this Ruby
|
||||
# port is based on.
|
||||
#
|
||||
# Stephen Morgan for creating the TT template and SVG.
|
||||
#
|
||||
# == See
|
||||
#
|
||||
# * SVG::Graph::BarHorizontal
|
||||
# * SVG::Graph::Bar
|
||||
# * SVG::Graph::Line
|
||||
# * SVG::Graph::Pie
|
||||
# * SVG::Graph::Plot
|
||||
# * SVG::Graph::TimeSeries
|
||||
#
|
||||
# == Author
|
||||
#
|
||||
# Sean E. Russell <serATgermaneHYPHENsoftwareDOTcom>
|
||||
#
|
||||
# Copyright 2004 Sean E. Russell
|
||||
# This software is available under the Ruby license[LICENSE.txt]
|
||||
#
|
||||
class Graph
|
||||
include REXML
|
||||
|
||||
# Initialize the graph object with the graph settings. You won't
|
||||
# instantiate this class directly; see the subclass for options.
|
||||
# [width] 500
|
||||
# [height] 300
|
||||
# [show_x_guidelines] false
|
||||
# [show_y_guidelines] true
|
||||
# [show_data_values] true
|
||||
# [min_scale_value] 0
|
||||
# [show_x_labels] true
|
||||
# [stagger_x_labels] false
|
||||
# [rotate_x_labels] false
|
||||
# [step_x_labels] 1
|
||||
# [step_include_first_x_label] true
|
||||
# [show_y_labels] true
|
||||
# [rotate_y_labels] false
|
||||
# [scale_integers] false
|
||||
# [show_x_title] false
|
||||
# [x_title] 'X Field names'
|
||||
# [show_y_title] false
|
||||
# [y_title_text_direction] :bt
|
||||
# [y_title] 'Y Scale'
|
||||
# [show_graph_title] false
|
||||
# [graph_title] 'Graph Title'
|
||||
# [show_graph_subtitle] false
|
||||
# [graph_subtitle] 'Graph Sub Title'
|
||||
# [key] true,
|
||||
# [key_position] :right, # bottom or righ
|
||||
# [font_size] 12
|
||||
# [title_font_size] 16
|
||||
# [subtitle_font_size] 14
|
||||
# [x_label_font_size] 12
|
||||
# [x_title_font_size] 14
|
||||
# [y_label_font_size] 12
|
||||
# [y_title_font_size] 14
|
||||
# [key_font_size] 10
|
||||
# [no_css] false
|
||||
# [add_popups] false
|
||||
def initialize( config )
|
||||
@config = config
|
||||
|
||||
self.top_align = self.top_font = self.right_align = self.right_font = 0
|
||||
|
||||
init_with({
|
||||
:width => 500,
|
||||
:height => 300,
|
||||
:show_x_guidelines => false,
|
||||
:show_y_guidelines => true,
|
||||
:show_data_values => true,
|
||||
|
||||
:min_scale_value => 0,
|
||||
|
||||
:show_x_labels => true,
|
||||
:stagger_x_labels => false,
|
||||
:rotate_x_labels => false,
|
||||
:step_x_labels => 1,
|
||||
:step_include_first_x_label => true,
|
||||
|
||||
:show_y_labels => true,
|
||||
:rotate_y_labels => false,
|
||||
:stagger_y_labels => false,
|
||||
:scale_integers => false,
|
||||
|
||||
:show_x_title => false,
|
||||
:x_title => 'X Field names',
|
||||
|
||||
:show_y_title => false,
|
||||
:y_title_text_direction => :bt,
|
||||
:y_title => 'Y Scale',
|
||||
|
||||
:show_graph_title => false,
|
||||
:graph_title => 'Graph Title',
|
||||
:show_graph_subtitle => false,
|
||||
:graph_subtitle => 'Graph Sub Title',
|
||||
:key => true,
|
||||
:key_position => :right, # bottom or right
|
||||
|
||||
:font_size =>10,
|
||||
:title_font_size =>12,
|
||||
:subtitle_font_size =>14,
|
||||
:x_label_font_size =>11,
|
||||
:x_title_font_size =>14,
|
||||
:y_label_font_size =>11,
|
||||
:y_title_font_size =>14,
|
||||
:key_font_size => 9,
|
||||
|
||||
:no_css =>false,
|
||||
:add_popups =>false,
|
||||
})
|
||||
|
||||
set_defaults if methods.include? "set_defaults"
|
||||
|
||||
init_with config
|
||||
end
|
||||
|
||||
|
||||
# This method allows you do add data to the graph object.
|
||||
# It can be called several times to add more data sets in.
|
||||
#
|
||||
# data_sales_02 = [12, 45, 21];
|
||||
#
|
||||
# graph.add_data({
|
||||
# :data => data_sales_02,
|
||||
# :title => 'Sales 2002'
|
||||
# })
|
||||
def add_data conf
|
||||
@data = [] unless defined? @data
|
||||
|
||||
if conf[:data] and conf[:data].kind_of? Array
|
||||
@data << conf
|
||||
else
|
||||
raise "No data provided by #{conf.inspect}"
|
||||
end
|
||||
end
|
||||
|
||||
|
||||
# This method removes all data from the object so that you can
|
||||
# reuse it to create a new graph but with the same config options.
|
||||
#
|
||||
# graph.clear_data
|
||||
def clear_data
|
||||
@data = []
|
||||
end
|
||||
|
||||
|
||||
# This method processes the template with the data and
|
||||
# config which has been set and returns the resulting SVG.
|
||||
#
|
||||
# This method will croak unless at least one data set has
|
||||
# been added to the graph object.
|
||||
#
|
||||
# print graph.burn
|
||||
def burn
|
||||
raise "No data available" unless @data.size > 0
|
||||
|
||||
calculations if methods.include? 'calculations'
|
||||
|
||||
start_svg
|
||||
calculate_graph_dimensions
|
||||
@foreground = Element.new( "g" )
|
||||
draw_graph
|
||||
draw_titles
|
||||
draw_legend
|
||||
draw_data
|
||||
@graph.add_element( @foreground )
|
||||
style
|
||||
|
||||
data = ""
|
||||
@doc.write( data, 0 )
|
||||
|
||||
if @config[:compress]
|
||||
if @@__have_zlib
|
||||
inp, out = IO.pipe
|
||||
gz = Zlib::GzipWriter.new( out )
|
||||
gz.write data
|
||||
gz.close
|
||||
data = inp.read
|
||||
else
|
||||
data << "<!-- Ruby Zlib not available for SVGZ -->";
|
||||
end
|
||||
end
|
||||
|
||||
return data
|
||||
end
|
||||
|
||||
|
||||
# Set the height of the graph box, this is the total height
|
||||
# of the SVG box created - not the graph it self which auto
|
||||
# scales to fix the space.
|
||||
attr_accessor :height
|
||||
# Set the width of the graph box, this is the total width
|
||||
# of the SVG box created - not the graph it self which auto
|
||||
# scales to fix the space.
|
||||
attr_accessor :width
|
||||
# Set the path to an external stylesheet, set to '' if
|
||||
# you want to revert back to using the defaut internal version.
|
||||
#
|
||||
# To create an external stylesheet create a graph using the
|
||||
# default internal version and copy the stylesheet section to
|
||||
# an external file and edit from there.
|
||||
attr_accessor :style_sheet
|
||||
# (Bool) Show the value of each element of data on the graph
|
||||
attr_accessor :show_data_values
|
||||
# The point at which the Y axis starts, defaults to '0',
|
||||
# if set to nil it will default to the minimum data value.
|
||||
attr_accessor :min_scale_value
|
||||
# Whether to show labels on the X axis or not, defaults
|
||||
# to true, set to false if you want to turn them off.
|
||||
attr_accessor :show_x_labels
|
||||
# This puts the X labels at alternative levels so if they
|
||||
# are long field names they will not overlap so easily.
|
||||
# Default it false, to turn on set to true.
|
||||
attr_accessor :stagger_x_labels
|
||||
# This puts the Y labels at alternative levels so if they
|
||||
# are long field names they will not overlap so easily.
|
||||
# Default it false, to turn on set to true.
|
||||
attr_accessor :stagger_y_labels
|
||||
# This turns the X axis labels by 90 degrees.
|
||||
# Default it false, to turn on set to true.
|
||||
attr_accessor :rotate_x_labels
|
||||
# This turns the Y axis labels by 90 degrees.
|
||||
# Default it false, to turn on set to true.
|
||||
attr_accessor :rotate_y_labels
|
||||
# How many "steps" to use between displayed X axis labels,
|
||||
# a step of one means display every label, a step of two results
|
||||
# in every other label being displayed (label <gap> label <gap> label),
|
||||
# a step of three results in every third label being displayed
|
||||
# (label <gap> <gap> label <gap> <gap> label) and so on.
|
||||
attr_accessor :step_x_labels
|
||||
# Whether to (when taking "steps" between X axis labels) step from
|
||||
# the first label (i.e. always include the first label) or step from
|
||||
# the X axis origin (i.e. start with a gap if step_x_labels is greater
|
||||
# than one).
|
||||
attr_accessor :step_include_first_x_label
|
||||
# Whether to show labels on the Y axis or not, defaults
|
||||
# to true, set to false if you want to turn them off.
|
||||
attr_accessor :show_y_labels
|
||||
# Ensures only whole numbers are used as the scale divisions.
|
||||
# Default it false, to turn on set to true. This has no effect if
|
||||
# scale divisions are less than 1.
|
||||
attr_accessor :scale_integers
|
||||
# This defines the gap between markers on the Y axis,
|
||||
# default is a 10th of the max_value, e.g. you will have
|
||||
# 10 markers on the Y axis. NOTE: do not set this too
|
||||
# low - you are limited to 999 markers, after that the
|
||||
# graph won't generate.
|
||||
attr_accessor :scale_divisions
|
||||
# Whether to show the title under the X axis labels,
|
||||
# default is false, set to true to show.
|
||||
attr_accessor :show_x_title
|
||||
# What the title under X axis should be, e.g. 'Months'.
|
||||
attr_accessor :x_title
|
||||
# Whether to show the title under the Y axis labels,
|
||||
# default is false, set to true to show.
|
||||
attr_accessor :show_y_title
|
||||
# Aligns writing mode for Y axis label.
|
||||
# Defaults to :bt (Bottom to Top).
|
||||
# Change to :tb (Top to Bottom) to reverse.
|
||||
attr_accessor :y_title_text_direction
|
||||
# What the title under Y axis should be, e.g. 'Sales in thousands'.
|
||||
attr_accessor :y_title
|
||||
# Whether to show a title on the graph, defaults
|
||||
# to false, set to true to show.
|
||||
attr_accessor :show_graph_title
|
||||
# What the title on the graph should be.
|
||||
attr_accessor :graph_title
|
||||
# Whether to show a subtitle on the graph, defaults
|
||||
# to false, set to true to show.
|
||||
attr_accessor :show_graph_subtitle
|
||||
# What the subtitle on the graph should be.
|
||||
attr_accessor :graph_subtitle
|
||||
# Whether to show a key, defaults to false, set to
|
||||
# true if you want to show it.
|
||||
attr_accessor :key
|
||||
# Where the key should be positioned, defaults to
|
||||
# :right, set to :bottom if you want to move it.
|
||||
attr_accessor :key_position
|
||||
# Set the font size (in points) of the data point labels
|
||||
attr_accessor :font_size
|
||||
# Set the font size of the X axis labels
|
||||
attr_accessor :x_label_font_size
|
||||
# Set the font size of the X axis title
|
||||
attr_accessor :x_title_font_size
|
||||
# Set the font size of the Y axis labels
|
||||
attr_accessor :y_label_font_size
|
||||
# Set the font size of the Y axis title
|
||||
attr_accessor :y_title_font_size
|
||||
# Set the title font size
|
||||
attr_accessor :title_font_size
|
||||
# Set the subtitle font size
|
||||
attr_accessor :subtitle_font_size
|
||||
# Set the key font size
|
||||
attr_accessor :key_font_size
|
||||
# Show guidelines for the X axis
|
||||
attr_accessor :show_x_guidelines
|
||||
# Show guidelines for the Y axis
|
||||
attr_accessor :show_y_guidelines
|
||||
# Do not use CSS if set to true. Many SVG viewers do not support CSS, but
|
||||
# not using CSS can result in larger SVGs as well as making it impossible to
|
||||
# change colors after the chart is generated. Defaults to false.
|
||||
attr_accessor :no_css
|
||||
# Add popups for the data points on some graphs
|
||||
attr_accessor :add_popups
|
||||
|
||||
|
||||
protected
|
||||
|
||||
def sort( *arrys )
|
||||
sort_multiple( arrys )
|
||||
end
|
||||
|
||||
# Overwrite configuration options with supplied options. Used
|
||||
# by subclasses.
|
||||
def init_with config
|
||||
config.each { |key, value|
|
||||
self.send( key.to_s+"=", value ) if methods.include? key.to_s
|
||||
}
|
||||
end
|
||||
|
||||
attr_accessor :top_align, :top_font, :right_align, :right_font
|
||||
|
||||
KEY_BOX_SIZE = 12
|
||||
|
||||
# Override this (and call super) to change the margin to the left
|
||||
# of the plot area. Results in @border_left being set.
|
||||
def calculate_left_margin
|
||||
@border_left = 7
|
||||
# Check for Y labels
|
||||
max_y_label_height_px = rotate_y_labels ?
|
||||
y_label_font_size :
|
||||
get_y_labels.max{|a,b|
|
||||
a.to_s.length<=>b.to_s.length
|
||||
}.to_s.length * y_label_font_size * 0.6
|
||||
@border_left += max_y_label_height_px if show_y_labels
|
||||
@border_left += max_y_label_height_px + 10 if stagger_y_labels
|
||||
@border_left += y_title_font_size + 5 if show_y_title
|
||||
end
|
||||
|
||||
|
||||
# Calculates the width of the widest Y label. This will be the
|
||||
# character height if the Y labels are rotated
|
||||
def max_y_label_width_px
|
||||
return font_size if rotate_y_labels
|
||||
end
|
||||
|
||||
|
||||
# Override this (and call super) to change the margin to the right
|
||||
# of the plot area. Results in @border_right being set.
|
||||
def calculate_right_margin
|
||||
@border_right = 7
|
||||
if key and key_position == :right
|
||||
val = keys.max { |a,b| a.length <=> b.length }
|
||||
@border_right += val.length * key_font_size * 0.7
|
||||
@border_right += KEY_BOX_SIZE
|
||||
@border_right += 10 # Some padding around the box
|
||||
end
|
||||
end
|
||||
|
||||
|
||||
# Override this (and call super) to change the margin to the top
|
||||
# of the plot area. Results in @border_top being set.
|
||||
def calculate_top_margin
|
||||
@border_top = 5
|
||||
@border_top += title_font_size if show_graph_title
|
||||
@border_top += 5
|
||||
@border_top += subtitle_font_size if show_graph_subtitle
|
||||
end
|
||||
|
||||
|
||||
# Adds pop-up point information to a graph.
|
||||
def add_popup( x, y, label )
|
||||
txt_width = label.length * font_size * 0.6 + 10
|
||||
tx = (x+txt_width > width ? x-5 : x+5)
|
||||
t = @foreground.add_element( "text", {
|
||||
"x" => tx.to_s,
|
||||
"y" => (y - font_size).to_s,
|
||||
"visibility" => "hidden",
|
||||
})
|
||||
t.attributes["style"] = "fill: #000; "+
|
||||
(x+txt_width > width ? "text-anchor: end;" : "text-anchor: start;")
|
||||
t.text = label.to_s
|
||||
t.attributes["id"] = t.id.to_s
|
||||
|
||||
@foreground.add_element( "circle", {
|
||||
"cx" => x.to_s,
|
||||
"cy" => y.to_s,
|
||||
"r" => "10",
|
||||
"style" => "opacity: 0",
|
||||
"onmouseover" =>
|
||||
"document.getElementById(#{t.id}).setAttribute('visibility', 'visible' )",
|
||||
"onmouseout" =>
|
||||
"document.getElementById(#{t.id}).setAttribute('visibility', 'hidden' )",
|
||||
})
|
||||
|
||||
end
|
||||
|
||||
|
||||
# Override this (and call super) to change the margin to the bottom
|
||||
# of the plot area. Results in @border_bottom being set.
|
||||
def calculate_bottom_margin
|
||||
@border_bottom = 7
|
||||
if key and key_position == :bottom
|
||||
@border_bottom += @data.size * (font_size + 5)
|
||||
@border_bottom += 10
|
||||
end
|
||||
if show_x_labels
|
||||
max_x_label_height_px = rotate_x_labels ?
|
||||
get_x_labels.max{|a,b|
|
||||
a.length<=>b.length
|
||||
}.length * x_label_font_size * 0.6 :
|
||||
x_label_font_size
|
||||
@border_bottom += max_x_label_height_px
|
||||
@border_bottom += max_x_label_height_px + 10 if stagger_x_labels
|
||||
end
|
||||
@border_bottom += x_title_font_size + 5 if show_x_title
|
||||
end
|
||||
|
||||
|
||||
# Draws the background, axis, and labels.
|
||||
def draw_graph
|
||||
@graph = @root.add_element( "g", {
|
||||
"transform" => "translate( #@border_left #@border_top )"
|
||||
})
|
||||
|
||||
# Background
|
||||
@graph.add_element( "rect", {
|
||||
"x" => "0",
|
||||
"y" => "0",
|
||||
"width" => @graph_width.to_s,
|
||||
"height" => @graph_height.to_s,
|
||||
"class" => "graphBackground"
|
||||
})
|
||||
|
||||
# Axis
|
||||
@graph.add_element( "path", {
|
||||
"d" => "M 0 0 v#@graph_height",
|
||||
"class" => "axis",
|
||||
"id" => "xAxis"
|
||||
})
|
||||
@graph.add_element( "path", {
|
||||
"d" => "M 0 #@graph_height h#@graph_width",
|
||||
"class" => "axis",
|
||||
"id" => "yAxis"
|
||||
})
|
||||
|
||||
draw_x_labels
|
||||
draw_y_labels
|
||||
end
|
||||
|
||||
|
||||
# Where in the X area the label is drawn
|
||||
# Centered in the field, should be width/2. Start, 0.
|
||||
def x_label_offset( width )
|
||||
0
|
||||
end
|
||||
|
||||
def make_datapoint_text( x, y, value, style="" )
|
||||
if show_data_values
|
||||
@foreground.add_element( "text", {
|
||||
"x" => x.to_s,
|
||||
"y" => y.to_s,
|
||||
"class" => "dataPointLabel",
|
||||
"style" => "#{style} stroke: #fff; stroke-width: 2;"
|
||||
}).text = value.to_s
|
||||
text = @foreground.add_element( "text", {
|
||||
"x" => x.to_s,
|
||||
"y" => y.to_s,
|
||||
"class" => "dataPointLabel"
|
||||
})
|
||||
text.text = value.to_s
|
||||
text.attributes["style"] = style if style.length > 0
|
||||
end
|
||||
end
|
||||
|
||||
|
||||
# Draws the X axis labels
|
||||
def draw_x_labels
|
||||
stagger = x_label_font_size + 5
|
||||
if show_x_labels
|
||||
label_width = field_width
|
||||
|
||||
count = 0
|
||||
for label in get_x_labels
|
||||
if step_include_first_x_label == true then
|
||||
step = count % step_x_labels
|
||||
else
|
||||
step = (count + 1) % step_x_labels
|
||||
end
|
||||
|
||||
if step == 0 then
|
||||
text = @graph.add_element( "text" )
|
||||
text.attributes["class"] = "xAxisLabels"
|
||||
text.text = label.to_s
|
||||
|
||||
x = count * label_width + x_label_offset( label_width )
|
||||
y = @graph_height + x_label_font_size + 3
|
||||
t = 0 - (font_size / 2)
|
||||
|
||||
if stagger_x_labels and count % 2 == 1
|
||||
y += stagger
|
||||
@graph.add_element( "path", {
|
||||
"d" => "M#{x} #@graph_height v#{stagger}",
|
||||
"class" => "staggerGuideLine"
|
||||
})
|
||||
end
|
||||
|
||||
text.attributes["x"] = x.to_s
|
||||
text.attributes["y"] = y.to_s
|
||||
if rotate_x_labels
|
||||
text.attributes["transform"] =
|
||||
"rotate( 90 #{x} #{y-x_label_font_size} )"+
|
||||
" translate( 0 -#{x_label_font_size/4} )"
|
||||
text.attributes["style"] = "text-anchor: start"
|
||||
else
|
||||
text.attributes["style"] = "text-anchor: middle"
|
||||
end
|
||||
end
|
||||
|
||||
draw_x_guidelines( label_width, count ) if show_x_guidelines
|
||||
count += 1
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
|
||||
# Where in the Y area the label is drawn
|
||||
# Centered in the field, should be width/2. Start, 0.
|
||||
def y_label_offset( height )
|
||||
0
|
||||
end
|
||||
|
||||
|
||||
def field_width
|
||||
(@graph_width.to_f - font_size*2*right_font) /
|
||||
(get_x_labels.length - right_align)
|
||||
end
|
||||
|
||||
|
||||
def field_height
|
||||
(@graph_height.to_f - font_size*2*top_font) /
|
||||
(get_y_labels.length - top_align)
|
||||
end
|
||||
|
||||
|
||||
# Draws the Y axis labels
|
||||
def draw_y_labels
|
||||
stagger = y_label_font_size + 5
|
||||
if show_y_labels
|
||||
label_height = field_height
|
||||
|
||||
count = 0
|
||||
y_offset = @graph_height + y_label_offset( label_height )
|
||||
y_offset += font_size/1.2 unless rotate_y_labels
|
||||
for label in get_y_labels
|
||||
y = y_offset - (label_height * count)
|
||||
x = rotate_y_labels ? 0 : -3
|
||||
|
||||
if stagger_y_labels and count % 2 == 1
|
||||
x -= stagger
|
||||
@graph.add_element( "path", {
|
||||
"d" => "M#{x} #{y} h#{stagger}",
|
||||
"class" => "staggerGuideLine"
|
||||
})
|
||||
end
|
||||
|
||||
text = @graph.add_element( "text", {
|
||||
"x" => x.to_s,
|
||||
"y" => y.to_s,
|
||||
"class" => "yAxisLabels"
|
||||
})
|
||||
text.text = label.to_s
|
||||
if rotate_y_labels
|
||||
text.attributes["transform"] = "translate( -#{font_size} 0 ) "+
|
||||
"rotate( 90 #{x} #{y} ) "
|
||||
text.attributes["style"] = "text-anchor: middle"
|
||||
else
|
||||
text.attributes["y"] = (y - (y_label_font_size/2)).to_s
|
||||
text.attributes["style"] = "text-anchor: end"
|
||||
end
|
||||
draw_y_guidelines( label_height, count ) if show_y_guidelines
|
||||
count += 1
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
|
||||
# Draws the X axis guidelines
|
||||
def draw_x_guidelines( label_height, count )
|
||||
if count != 0
|
||||
@graph.add_element( "path", {
|
||||
"d" => "M#{label_height*count} 0 v#@graph_height",
|
||||
"class" => "guideLines"
|
||||
})
|
||||
end
|
||||
end
|
||||
|
||||
|
||||
# Draws the Y axis guidelines
|
||||
def draw_y_guidelines( label_height, count )
|
||||
if count != 0
|
||||
@graph.add_element( "path", {
|
||||
"d" => "M0 #{@graph_height-(label_height*count)} h#@graph_width",
|
||||
"class" => "guideLines"
|
||||
})
|
||||
end
|
||||
end
|
||||
|
||||
|
||||
# Draws the graph title and subtitle
|
||||
def draw_titles
|
||||
if show_graph_title
|
||||
@root.add_element( "text", {
|
||||
"x" => (width / 2).to_s,
|
||||
"y" => (title_font_size).to_s,
|
||||
"class" => "mainTitle"
|
||||
}).text = graph_title.to_s
|
||||
end
|
||||
|
||||
if show_graph_subtitle
|
||||
y_subtitle = show_graph_title ?
|
||||
title_font_size + 10 :
|
||||
subtitle_font_size
|
||||
@root.add_element("text", {
|
||||
"x" => (width / 2).to_s,
|
||||
"y" => (y_subtitle).to_s,
|
||||
"class" => "subTitle"
|
||||
}).text = graph_subtitle.to_s
|
||||
end
|
||||
|
||||
if show_x_title
|
||||
y = @graph_height + @border_top + x_title_font_size
|
||||
if show_x_labels
|
||||
y += x_label_font_size + 5 if stagger_x_labels
|
||||
y += x_label_font_size + 5
|
||||
end
|
||||
x = width / 2
|
||||
|
||||
@root.add_element("text", {
|
||||
"x" => x.to_s,
|
||||
"y" => y.to_s,
|
||||
"class" => "xAxisTitle",
|
||||
}).text = x_title.to_s
|
||||
end
|
||||
|
||||
if show_y_title
|
||||
x = y_title_font_size + (y_title_text_direction==:bt ? 3 : -3)
|
||||
y = height / 2
|
||||
|
||||
text = @root.add_element("text", {
|
||||
"x" => x.to_s,
|
||||
"y" => y.to_s,
|
||||
"class" => "yAxisTitle",
|
||||
})
|
||||
text.text = y_title.to_s
|
||||
if y_title_text_direction == :bt
|
||||
text.attributes["transform"] = "rotate( -90, #{x}, #{y} )"
|
||||
else
|
||||
text.attributes["transform"] = "rotate( 90, #{x}, #{y} )"
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
def keys
|
||||
return @data.collect{ |d| d[:title] }
|
||||
end
|
||||
|
||||
# Draws the legend on the graph
|
||||
def draw_legend
|
||||
if key
|
||||
group = @root.add_element( "g" )
|
||||
|
||||
key_count = 0
|
||||
for key_name in keys
|
||||
y_offset = (KEY_BOX_SIZE * key_count) + (key_count * 5)
|
||||
group.add_element( "rect", {
|
||||
"x" => 0.to_s,
|
||||
"y" => y_offset.to_s,
|
||||
"width" => KEY_BOX_SIZE.to_s,
|
||||
"height" => KEY_BOX_SIZE.to_s,
|
||||
"class" => "key#{key_count+1}"
|
||||
})
|
||||
group.add_element( "text", {
|
||||
"x" => (KEY_BOX_SIZE + 5).to_s,
|
||||
"y" => (y_offset + KEY_BOX_SIZE - 2).to_s,
|
||||
"class" => "keyText"
|
||||
}).text = key_name.to_s
|
||||
key_count += 1
|
||||
end
|
||||
|
||||
case key_position
|
||||
when :right
|
||||
x_offset = @graph_width + @border_left + 10
|
||||
y_offset = @border_top + 20
|
||||
when :bottom
|
||||
x_offset = @border_left + 20
|
||||
y_offset = @border_top + @graph_height + 5
|
||||
if show_x_labels
|
||||
max_x_label_height_px = rotate_x_labels ?
|
||||
get_x_labels.max{|a,b|
|
||||
a.length<=>b.length
|
||||
}.length * x_label_font_size :
|
||||
x_label_font_size
|
||||
y_offset += max_x_label_height_px
|
||||
y_offset += max_x_label_height_px + 5 if stagger_x_labels
|
||||
end
|
||||
y_offset += x_title_font_size + 5 if show_x_title
|
||||
end
|
||||
group.attributes["transform"] = "translate(#{x_offset} #{y_offset})"
|
||||
end
|
||||
end
|
||||
|
||||
|
||||
private
|
||||
|
||||
def sort_multiple( arrys, lo=0, hi=arrys[0].length-1 )
|
||||
if lo < hi
|
||||
p = partition(arrys,lo,hi)
|
||||
sort_multiple(arrys, lo, p-1)
|
||||
sort_multiple(arrys, p+1, hi)
|
||||
end
|
||||
arrys
|
||||
end
|
||||
|
||||
def partition( arrys, lo, hi )
|
||||
p = arrys[0][lo]
|
||||
l = lo
|
||||
z = lo+1
|
||||
while z <= hi
|
||||
if arrys[0][z] < p
|
||||
l += 1
|
||||
arrys.each { |arry| arry[z], arry[l] = arry[l], arry[z] }
|
||||
end
|
||||
z += 1
|
||||
end
|
||||
arrys.each { |arry| arry[lo], arry[l] = arry[l], arry[lo] }
|
||||
l
|
||||
end
|
||||
|
||||
def style
|
||||
if no_css
|
||||
styles = parse_css
|
||||
@root.elements.each("//*[@class]") { |el|
|
||||
cl = el.attributes["class"]
|
||||
style = styles[cl]
|
||||
style += el.attributes["style"] if el.attributes["style"]
|
||||
el.attributes["style"] = style
|
||||
}
|
||||
end
|
||||
end
|
||||
|
||||
def parse_css
|
||||
css = get_style
|
||||
rv = {}
|
||||
while css =~ /^(\.(\w+)(?:\s*,\s*\.\w+)*)\s*\{/m
|
||||
names_orig = names = $1
|
||||
css = $'
|
||||
css =~ /([^}]+)\}/m
|
||||
content = $1
|
||||
css = $'
|
||||
|
||||
nms = []
|
||||
while names =~ /^\s*,?\s*\.(\w+)/
|
||||
nms << $1
|
||||
names = $'
|
||||
end
|
||||
|
||||
content = content.tr( "\n\t", " ")
|
||||
for name in nms
|
||||
current = rv[name]
|
||||
current = current ? current+"; "+content : content
|
||||
rv[name] = current.strip.squeeze(" ")
|
||||
end
|
||||
end
|
||||
return rv
|
||||
end
|
||||
|
||||
|
||||
# Override and place code to add defs here
|
||||
def add_defs defs
|
||||
end
|
||||
|
||||
|
||||
def start_svg
|
||||
# Base document
|
||||
@doc = Document.new
|
||||
@doc << XMLDecl.new
|
||||
@doc << DocType.new( %q{svg PUBLIC "-//W3C//DTD SVG 1.0//EN" } +
|
||||
%q{"http://www.w3.org/TR/2001/REC-SVG-20010904/DTD/svg10.dtd"} )
|
||||
if style_sheet && style_sheet != ''
|
||||
@doc << Instruction.new( "xml-stylesheet",
|
||||
%Q{href="#{style_sheet}" type="text/css"} )
|
||||
end
|
||||
@root = @doc.add_element( "svg", {
|
||||
"width" => width.to_s,
|
||||
"height" => height.to_s,
|
||||
"viewBox" => "0 0 #{width} #{height}",
|
||||
"xmlns" => "http://www.w3.org/2000/svg",
|
||||
"xmlns:xlink" => "http://www.w3.org/1999/xlink",
|
||||
"xmlns:a3" => "http://ns.adobe.com/AdobeSVGViewerExtensions/3.0/",
|
||||
"a3:scriptImplementation" => "Adobe"
|
||||
})
|
||||
@root << Comment.new( " "+"\\"*66 )
|
||||
@root << Comment.new( " Created with SVG::Graph " )
|
||||
@root << Comment.new( " SVG::Graph by Sean E. Russell " )
|
||||
@root << Comment.new( " Losely based on SVG::TT::Graph for Perl by"+
|
||||
" Leo Lapworth & Stephan Morgan " )
|
||||
@root << Comment.new( " "+"/"*66 )
|
||||
|
||||
defs = @root.add_element( "defs" )
|
||||
add_defs defs
|
||||
if not(style_sheet && style_sheet != '') and !no_css
|
||||
@root << Comment.new(" include default stylesheet if none specified ")
|
||||
style = defs.add_element( "style", {"type"=>"text/css"} )
|
||||
style << CData.new( get_style )
|
||||
end
|
||||
|
||||
@root << Comment.new( "SVG Background" )
|
||||
@root.add_element( "rect", {
|
||||
"width" => width.to_s,
|
||||
"height" => height.to_s,
|
||||
"x" => "0",
|
||||
"y" => "0",
|
||||
"class" => "svgBackground"
|
||||
})
|
||||
end
|
||||
|
||||
|
||||
def calculate_graph_dimensions
|
||||
calculate_left_margin
|
||||
calculate_right_margin
|
||||
calculate_bottom_margin
|
||||
calculate_top_margin
|
||||
@graph_width = width - @border_left - @border_right
|
||||
@graph_height = height - @border_top - @border_bottom
|
||||
end
|
||||
|
||||
def get_style
|
||||
return <<EOL
|
||||
/* Copy from here for external style sheet */
|
||||
.svgBackground{
|
||||
fill:#ffffff;
|
||||
}
|
||||
.graphBackground{
|
||||
fill:#f5f5f5;
|
||||
}
|
||||
|
||||
/* graphs titles */
|
||||
.mainTitle{
|
||||
text-anchor: middle;
|
||||
fill: #555555;
|
||||
font-size: #{title_font_size}px;
|
||||
font-family: "Verdana", sans-serif;
|
||||
font-weight: bold;
|
||||
}
|
||||
.subTitle{
|
||||
text-anchor: middle;
|
||||
fill: #999999;
|
||||
font-size: #{subtitle_font_size}px;
|
||||
font-family: "Verdana", sans-serif;
|
||||
font-weight: normal;
|
||||
}
|
||||
|
||||
.axis{
|
||||
stroke: #666666;
|
||||
stroke-width: 1px;
|
||||
}
|
||||
|
||||
.guideLines{
|
||||
stroke: #666666;
|
||||
stroke-width: 1px;
|
||||
stroke-dasharray:2,2,2;
|
||||
}
|
||||
|
||||
.xAxisLabels{
|
||||
text-anchor: middle;
|
||||
fill: #000000;
|
||||
font-size: #{x_label_font_size}px;
|
||||
font-family: "Verdana", sans-serif;
|
||||
font-weight: normal;
|
||||
}
|
||||
|
||||
.yAxisLabels{
|
||||
text-anchor: end;
|
||||
fill: #000000;
|
||||
font-size: #{y_label_font_size}px;
|
||||
font-family: "Verdana", sans-serif;
|
||||
font-weight: normal;
|
||||
}
|
||||
|
||||
.xAxisTitle{
|
||||
text-anchor: middle;
|
||||
fill: #ff0000;
|
||||
font-size: #{x_title_font_size}px;
|
||||
font-family: "Verdana", sans-serif;
|
||||
font-weight: normal;
|
||||
}
|
||||
|
||||
.yAxisTitle{
|
||||
fill: #ff0000;
|
||||
text-anchor: middle;
|
||||
font-size: #{y_title_font_size}px;
|
||||
font-family: "Verdana", sans-serif;
|
||||
font-weight: normal;
|
||||
}
|
||||
|
||||
.dataPointLabel{
|
||||
fill: #000000;
|
||||
text-anchor:middle;
|
||||
font-size: 10px;
|
||||
font-family: "Verdana", sans-serif;
|
||||
font-weight: normal;
|
||||
}
|
||||
|
||||
.staggerGuideLine{
|
||||
fill: none;
|
||||
stroke: #000000;
|
||||
stroke-width: 0.5px;
|
||||
}
|
||||
|
||||
#{get_css}
|
||||
|
||||
.keyText{
|
||||
fill: #000000;
|
||||
text-anchor:start;
|
||||
font-size: #{key_font_size}px;
|
||||
font-family: "Verdana", sans-serif;
|
||||
font-weight: normal;
|
||||
}
|
||||
/* End copy for external style sheet */
|
||||
EOL
|
||||
end
|
||||
|
||||
end
|
||||
end
|
||||
end
|
||||
@@ -0,0 +1,444 @@
|
||||
require 'SVG/Graph/Graph'
|
||||
|
||||
module SVG
|
||||
module Graph
|
||||
# === Create presentation quality SVG line graphs easily
|
||||
#
|
||||
# = Synopsis
|
||||
#
|
||||
# require 'SVG/Graph/Line'
|
||||
#
|
||||
# fields = %w(Jan Feb Mar);
|
||||
# data_sales_02 = [12, 45, 21]
|
||||
# data_sales_03 = [15, 30, 40]
|
||||
#
|
||||
# graph = SVG::Graph::Line.new({
|
||||
# :height => 500,
|
||||
# :width => 300,
|
||||
# :fields => fields,
|
||||
# })
|
||||
#
|
||||
# graph.add_data({
|
||||
# :data => data_sales_02,
|
||||
# :title => 'Sales 2002',
|
||||
# })
|
||||
#
|
||||
# graph.add_data({
|
||||
# :data => data_sales_03,
|
||||
# :title => 'Sales 2003',
|
||||
# })
|
||||
#
|
||||
# print "Content-type: image/svg+xml\r\n\r\n";
|
||||
# print graph.burn();
|
||||
#
|
||||
# = Description
|
||||
#
|
||||
# This object aims to allow you to easily create high quality
|
||||
# SVG line graphs. You can either use the default style sheet
|
||||
# or supply your own. Either way there are many options which can
|
||||
# be configured to give you control over how the graph is
|
||||
# generated - with or without a key, data elements at each point,
|
||||
# title, subtitle etc.
|
||||
#
|
||||
# = Examples
|
||||
#
|
||||
# http://www.germane-software/repositories/public/SVG/test/single.rb
|
||||
#
|
||||
# = Notes
|
||||
#
|
||||
# The default stylesheet handles upto 10 data sets, if you
|
||||
# use more you must create your own stylesheet and add the
|
||||
# additional settings for the extra data sets. You will know
|
||||
# if you go over 10 data sets as they will have no style and
|
||||
# be in black.
|
||||
#
|
||||
# = See also
|
||||
#
|
||||
# * SVG::Graph::Graph
|
||||
# * SVG::Graph::BarHorizontal
|
||||
# * SVG::Graph::Bar
|
||||
# * SVG::Graph::Pie
|
||||
# * SVG::Graph::Plot
|
||||
# * SVG::Graph::TimeSeries
|
||||
#
|
||||
# == Author
|
||||
#
|
||||
# Sean E. Russell <serATgermaneHYPHENsoftwareDOTcom>
|
||||
#
|
||||
# Copyright 2004 Sean E. Russell
|
||||
# This software is available under the Ruby license[LICENSE.txt]
|
||||
#
|
||||
class Line < SVG::Graph::Graph
|
||||
# Show a small circle on the graph where the line
|
||||
# goes from one point to the next.
|
||||
attr_accessor :show_data_points
|
||||
# Accumulates each data set. (i.e. Each point increased by sum of
|
||||
# all previous series at same point). Default is 0, set to '1' to show.
|
||||
attr_accessor :stacked
|
||||
# Fill in the area under the plot if true
|
||||
attr_accessor :area_fill
|
||||
|
||||
# The constructor takes a hash reference, fields (the names for each
|
||||
# field on the X axis) MUST be set, all other values are defaulted to
|
||||
# those shown above - with the exception of style_sheet which defaults
|
||||
# to using the internal style sheet.
|
||||
def initialize config
|
||||
raise "fields was not supplied or is empty" unless config[:fields] &&
|
||||
config[:fields].kind_of?(Array) &&
|
||||
config[:fields].length > 0
|
||||
super
|
||||
end
|
||||
|
||||
# In addition to the defaults set in Graph::initialize, sets
|
||||
# [show_data_points] true
|
||||
# [show_data_values] true
|
||||
# [stacked] false
|
||||
# [area_fill] false
|
||||
def set_defaults
|
||||
init_with(
|
||||
:show_data_points => true,
|
||||
:show_data_values => true,
|
||||
:stacked => false,
|
||||
:area_fill => false
|
||||
)
|
||||
|
||||
self.top_align = self.top_font = self.right_align = self.right_font = 1
|
||||
end
|
||||
|
||||
protected
|
||||
|
||||
def max_value
|
||||
max = 0
|
||||
|
||||
if (stacked == true) then
|
||||
sums = Array.new(@config[:fields].length).fill(0)
|
||||
|
||||
@data.each do |data|
|
||||
sums.each_index do |i|
|
||||
sums[i] += data[:data][i].to_f
|
||||
end
|
||||
end
|
||||
|
||||
max = sums.max
|
||||
else
|
||||
max = @data.collect{|x| x[:data].max}.max
|
||||
end
|
||||
|
||||
return max
|
||||
end
|
||||
|
||||
def min_value
|
||||
min = 0
|
||||
|
||||
if (min_scale_value.nil? == false) then
|
||||
min = min_scale_value
|
||||
elsif (stacked == true) then
|
||||
min = @data[-1][:data].min
|
||||
else
|
||||
min = @data.collect{|x| x[:data].min}.min
|
||||
end
|
||||
|
||||
return min
|
||||
end
|
||||
|
||||
def get_x_labels
|
||||
@config[:fields]
|
||||
end
|
||||
|
||||
def calculate_left_margin
|
||||
super
|
||||
label_left = @config[:fields][0].length / 2 * font_size * 0.6
|
||||
@border_left = label_left if label_left > @border_left
|
||||
end
|
||||
|
||||
def get_y_labels
|
||||
maxvalue = max_value
|
||||
minvalue = min_value
|
||||
range = maxvalue - minvalue
|
||||
top_pad = range == 0 ? 10 : range / 20.0
|
||||
scale_range = (maxvalue + top_pad) - minvalue
|
||||
|
||||
scale_division = scale_divisions || (scale_range / 10.0)
|
||||
|
||||
if scale_integers
|
||||
scale_division = scale_division < 1 ? 1 : scale_division.round
|
||||
end
|
||||
|
||||
rv = []
|
||||
maxvalue = maxvalue%scale_division == 0 ?
|
||||
maxvalue : maxvalue + scale_division
|
||||
minvalue.step( maxvalue, scale_division ) {|v| rv << v}
|
||||
return rv
|
||||
end
|
||||
|
||||
def calc_coords(field, value, width = field_width, height = field_height)
|
||||
coords = {:x => 0, :y => 0}
|
||||
coords[:x] = width * field
|
||||
coords[:y] = @graph_height - value * height
|
||||
|
||||
return coords
|
||||
end
|
||||
|
||||
def draw_data
|
||||
minvalue = min_value
|
||||
fieldheight = (@graph_height.to_f - font_size*2*top_font) /
|
||||
(get_y_labels.max - get_y_labels.min)
|
||||
fieldwidth = field_width
|
||||
line = @data.length
|
||||
|
||||
prev_sum = Array.new(@config[:fields].length).fill(0)
|
||||
cum_sum = Array.new(@config[:fields].length).fill(-minvalue)
|
||||
|
||||
for data in @data.reverse
|
||||
lpath = ""
|
||||
apath = ""
|
||||
|
||||
if not stacked then cum_sum.fill(-minvalue) end
|
||||
|
||||
data[:data].each_index do |i|
|
||||
cum_sum[i] += data[:data][i]
|
||||
|
||||
c = calc_coords(i, cum_sum[i], fieldwidth, fieldheight)
|
||||
|
||||
lpath << "#{c[:x]} #{c[:y]} "
|
||||
end
|
||||
|
||||
if area_fill
|
||||
if stacked then
|
||||
(prev_sum.length - 1).downto 0 do |i|
|
||||
c = calc_coords(i, prev_sum[i], fieldwidth, fieldheight)
|
||||
|
||||
apath << "#{c[:x]} #{c[:y]} "
|
||||
end
|
||||
|
||||
c = calc_coords(0, prev_sum[0], fieldwidth, fieldheight)
|
||||
else
|
||||
apath = "V#@graph_height"
|
||||
c = calc_coords(0, 0, fieldwidth, fieldheight)
|
||||
end
|
||||
|
||||
@graph.add_element("path", {
|
||||
"d" => "M#{c[:x]} #{c[:y]} L" + lpath + apath + "Z",
|
||||
"class" => "fill#{line}"
|
||||
})
|
||||
end
|
||||
|
||||
@graph.add_element("path", {
|
||||
"d" => "M0 #@graph_height L" + lpath,
|
||||
"class" => "line#{line}"
|
||||
})
|
||||
|
||||
if show_data_points || show_data_values
|
||||
cum_sum.each_index do |i|
|
||||
if show_data_points
|
||||
@graph.add_element( "circle", {
|
||||
"cx" => (fieldwidth * i).to_s,
|
||||
"cy" => (@graph_height - cum_sum[i] * fieldheight).to_s,
|
||||
"r" => "2.5",
|
||||
"class" => "dataPoint#{line}"
|
||||
})
|
||||
end
|
||||
make_datapoint_text(
|
||||
fieldwidth * i,
|
||||
@graph_height - cum_sum[i] * fieldheight - 6,
|
||||
cum_sum[i] + minvalue
|
||||
)
|
||||
end
|
||||
end
|
||||
|
||||
prev_sum = cum_sum.dup
|
||||
line -= 1
|
||||
end
|
||||
end
|
||||
|
||||
|
||||
def get_css
|
||||
return <<EOL
|
||||
/* default line styles */
|
||||
.line1{
|
||||
fill: none;
|
||||
stroke: #ff0000;
|
||||
stroke-width: 1px;
|
||||
}
|
||||
.line2{
|
||||
fill: none;
|
||||
stroke: #0000ff;
|
||||
stroke-width: 1px;
|
||||
}
|
||||
.line3{
|
||||
fill: none;
|
||||
stroke: #00ff00;
|
||||
stroke-width: 1px;
|
||||
}
|
||||
.line4{
|
||||
fill: none;
|
||||
stroke: #ffcc00;
|
||||
stroke-width: 1px;
|
||||
}
|
||||
.line5{
|
||||
fill: none;
|
||||
stroke: #00ccff;
|
||||
stroke-width: 1px;
|
||||
}
|
||||
.line6{
|
||||
fill: none;
|
||||
stroke: #ff00ff;
|
||||
stroke-width: 1px;
|
||||
}
|
||||
.line7{
|
||||
fill: none;
|
||||
stroke: #00ffff;
|
||||
stroke-width: 1px;
|
||||
}
|
||||
.line8{
|
||||
fill: none;
|
||||
stroke: #ffff00;
|
||||
stroke-width: 1px;
|
||||
}
|
||||
.line9{
|
||||
fill: none;
|
||||
stroke: #ccc6666;
|
||||
stroke-width: 1px;
|
||||
}
|
||||
.line10{
|
||||
fill: none;
|
||||
stroke: #663399;
|
||||
stroke-width: 1px;
|
||||
}
|
||||
.line11{
|
||||
fill: none;
|
||||
stroke: #339900;
|
||||
stroke-width: 1px;
|
||||
}
|
||||
.line12{
|
||||
fill: none;
|
||||
stroke: #9966FF;
|
||||
stroke-width: 1px;
|
||||
}
|
||||
/* default fill styles */
|
||||
.fill1{
|
||||
fill: #cc0000;
|
||||
fill-opacity: 0.2;
|
||||
stroke: none;
|
||||
}
|
||||
.fill2{
|
||||
fill: #0000cc;
|
||||
fill-opacity: 0.2;
|
||||
stroke: none;
|
||||
}
|
||||
.fill3{
|
||||
fill: #00cc00;
|
||||
fill-opacity: 0.2;
|
||||
stroke: none;
|
||||
}
|
||||
.fill4{
|
||||
fill: #ffcc00;
|
||||
fill-opacity: 0.2;
|
||||
stroke: none;
|
||||
}
|
||||
.fill5{
|
||||
fill: #00ccff;
|
||||
fill-opacity: 0.2;
|
||||
stroke: none;
|
||||
}
|
||||
.fill6{
|
||||
fill: #ff00ff;
|
||||
fill-opacity: 0.2;
|
||||
stroke: none;
|
||||
}
|
||||
.fill7{
|
||||
fill: #00ffff;
|
||||
fill-opacity: 0.2;
|
||||
stroke: none;
|
||||
}
|
||||
.fill8{
|
||||
fill: #ffff00;
|
||||
fill-opacity: 0.2;
|
||||
stroke: none;
|
||||
}
|
||||
.fill9{
|
||||
fill: #cc6666;
|
||||
fill-opacity: 0.2;
|
||||
stroke: none;
|
||||
}
|
||||
.fill10{
|
||||
fill: #663399;
|
||||
fill-opacity: 0.2;
|
||||
stroke: none;
|
||||
}
|
||||
.fill11{
|
||||
fill: #339900;
|
||||
fill-opacity: 0.2;
|
||||
stroke: none;
|
||||
}
|
||||
.fill12{
|
||||
fill: #9966FF;
|
||||
fill-opacity: 0.2;
|
||||
stroke: none;
|
||||
}
|
||||
/* default line styles */
|
||||
.key1,.dataPoint1{
|
||||
fill: #ff0000;
|
||||
stroke: none;
|
||||
stroke-width: 1px;
|
||||
}
|
||||
.key2,.dataPoint2{
|
||||
fill: #0000ff;
|
||||
stroke: none;
|
||||
stroke-width: 1px;
|
||||
}
|
||||
.key3,.dataPoint3{
|
||||
fill: #00ff00;
|
||||
stroke: none;
|
||||
stroke-width: 1px;
|
||||
}
|
||||
.key4,.dataPoint4{
|
||||
fill: #ffcc00;
|
||||
stroke: none;
|
||||
stroke-width: 1px;
|
||||
}
|
||||
.key5,.dataPoint5{
|
||||
fill: #00ccff;
|
||||
stroke: none;
|
||||
stroke-width: 1px;
|
||||
}
|
||||
.key6,.dataPoint6{
|
||||
fill: #ff00ff;
|
||||
stroke: none;
|
||||
stroke-width: 1px;
|
||||
}
|
||||
.key7,.dataPoint7{
|
||||
fill: #00ffff;
|
||||
stroke: none;
|
||||
stroke-width: 1px;
|
||||
}
|
||||
.key8,.dataPoint8{
|
||||
fill: #ffff00;
|
||||
stroke: none;
|
||||
stroke-width: 1px;
|
||||
}
|
||||
.key9,.dataPoint9{
|
||||
fill: #cc6666;
|
||||
stroke: none;
|
||||
stroke-width: 1px;
|
||||
}
|
||||
.key10,.dataPoint10{
|
||||
fill: #663399;
|
||||
stroke: none;
|
||||
stroke-width: 1px;
|
||||
}
|
||||
.key11,.dataPoint11{
|
||||
fill: #339900;
|
||||
stroke: none;
|
||||
stroke-width: 1px;
|
||||
}
|
||||
.key12,.dataPoint12{
|
||||
fill: #9966FF;
|
||||
stroke: none;
|
||||
stroke-width: 1px;
|
||||
}
|
||||
EOL
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
@@ -0,0 +1,394 @@
|
||||
require 'SVG/Graph/Graph'
|
||||
|
||||
module SVG
|
||||
module Graph
|
||||
# === Create presentation quality SVG pie graphs easily
|
||||
#
|
||||
# == Synopsis
|
||||
#
|
||||
# require 'SVG/Graph/Pie'
|
||||
#
|
||||
# fields = %w(Jan Feb Mar)
|
||||
# data_sales_02 = [12, 45, 21]
|
||||
#
|
||||
# graph = SVG::Graph::Pie.new({
|
||||
# :height => 500,
|
||||
# :width => 300,
|
||||
# :fields => fields,
|
||||
# })
|
||||
#
|
||||
# graph.add_data({
|
||||
# :data => data_sales_02,
|
||||
# :title => 'Sales 2002',
|
||||
# })
|
||||
#
|
||||
# print "Content-type: image/svg+xml\r\n\r\n"
|
||||
# print graph.burn();
|
||||
#
|
||||
# == Description
|
||||
#
|
||||
# This object aims to allow you to easily create high quality
|
||||
# SVG pie graphs. You can either use the default style sheet
|
||||
# or supply your own. Either way there are many options which can
|
||||
# be configured to give you control over how the graph is
|
||||
# generated - with or without a key, display percent on pie chart,
|
||||
# title, subtitle etc.
|
||||
#
|
||||
# = Examples
|
||||
#
|
||||
# http://www.germane-software/repositories/public/SVG/test/single.rb
|
||||
#
|
||||
# == See also
|
||||
#
|
||||
# * SVG::Graph::Graph
|
||||
# * SVG::Graph::BarHorizontal
|
||||
# * SVG::Graph::Bar
|
||||
# * SVG::Graph::Line
|
||||
# * SVG::Graph::Plot
|
||||
# * SVG::Graph::TimeSeries
|
||||
#
|
||||
# == Author
|
||||
#
|
||||
# Sean E. Russell <serATgermaneHYPHENsoftwareDOTcom>
|
||||
#
|
||||
# Copyright 2004 Sean E. Russell
|
||||
# This software is available under the Ruby license[LICENSE.txt]
|
||||
#
|
||||
class Pie < Graph
|
||||
# Defaults are those set by Graph::initialize, and
|
||||
# [show_shadow] true
|
||||
# [shadow_offset] 10
|
||||
# [show_data_labels] false
|
||||
# [show_actual_values] false
|
||||
# [show_percent] true
|
||||
# [show_key_data_labels] true
|
||||
# [show_key_actual_values] true
|
||||
# [show_key_percent] false
|
||||
# [expanded] false
|
||||
# [expand_greatest] false
|
||||
# [expand_gap] 10
|
||||
# [show_x_labels] false
|
||||
# [show_y_labels] false
|
||||
# [datapoint_font_size] 12
|
||||
def set_defaults
|
||||
init_with(
|
||||
:show_shadow => true,
|
||||
:shadow_offset => 10,
|
||||
|
||||
:show_data_labels => false,
|
||||
:show_actual_values => false,
|
||||
:show_percent => true,
|
||||
|
||||
:show_key_data_labels => true,
|
||||
:show_key_actual_values => true,
|
||||
:show_key_percent => false,
|
||||
|
||||
:expanded => false,
|
||||
:expand_greatest => false,
|
||||
:expand_gap => 10,
|
||||
|
||||
:show_x_labels => false,
|
||||
:show_y_labels => false,
|
||||
:datapoint_font_size => 12
|
||||
)
|
||||
@data = []
|
||||
end
|
||||
|
||||
# Adds a data set to the graph.
|
||||
#
|
||||
# graph.add_data( { :data => [1,2,3,4] } )
|
||||
#
|
||||
# Note that the :title is not necessary. If multiple
|
||||
# data sets are added to the graph, the pie chart will
|
||||
# display the +sums+ of the data. EG:
|
||||
#
|
||||
# graph.add_data( { :data => [1,2,3,4] } )
|
||||
# graph.add_data( { :data => [2,3,5,9] } )
|
||||
#
|
||||
# is the same as:
|
||||
#
|
||||
# graph.add_data( { :data => [3,5,8,13] } )
|
||||
def add_data arg
|
||||
arg[:data].each_index {|idx|
|
||||
@data[idx] = 0 unless @data[idx]
|
||||
@data[idx] += arg[:data][idx]
|
||||
}
|
||||
end
|
||||
|
||||
# If true, displays a drop shadow for the chart
|
||||
attr_accessor :show_shadow
|
||||
# Sets the offset of the shadow from the pie chart
|
||||
attr_accessor :shadow_offset
|
||||
# If true, display the data labels on the chart
|
||||
attr_accessor :show_data_labels
|
||||
# If true, display the actual field values in the data labels
|
||||
attr_accessor :show_actual_values
|
||||
# If true, display the percentage value of each pie wedge in the data
|
||||
# labels
|
||||
attr_accessor :show_percent
|
||||
# If true, display the labels in the key
|
||||
attr_accessor :show_key_data_labels
|
||||
# If true, display the actual value of the field in the key
|
||||
attr_accessor :show_key_actual_values
|
||||
# If true, display the percentage value of the wedges in the key
|
||||
attr_accessor :show_key_percent
|
||||
# If true, "explode" the pie (put space between the wedges)
|
||||
attr_accessor :expanded
|
||||
# If true, expand the largest pie wedge
|
||||
attr_accessor :expand_greatest
|
||||
# The amount of space between expanded wedges
|
||||
attr_accessor :expand_gap
|
||||
# The font size of the data point labels
|
||||
attr_accessor :datapoint_font_size
|
||||
|
||||
|
||||
protected
|
||||
|
||||
def add_defs defs
|
||||
gradient = defs.add_element( "filter", {
|
||||
"id"=>"dropshadow",
|
||||
"width" => "1.2",
|
||||
"height" => "1.2",
|
||||
} )
|
||||
gradient.add_element( "feGaussianBlur", {
|
||||
"stdDeviation" => "4",
|
||||
"result" => "blur"
|
||||
})
|
||||
end
|
||||
|
||||
# We don't need the graph
|
||||
def draw_graph
|
||||
end
|
||||
|
||||
def get_y_labels
|
||||
[""]
|
||||
end
|
||||
|
||||
def get_x_labels
|
||||
[""]
|
||||
end
|
||||
|
||||
def keys
|
||||
total = 0
|
||||
max_value = 0
|
||||
@data.each {|x| total += x }
|
||||
percent_scale = 100.0 / total
|
||||
count = -1
|
||||
a = @config[:fields].collect{ |x|
|
||||
count += 1
|
||||
v = @data[count]
|
||||
perc = show_key_percent ? " "+(v * percent_scale).round.to_s+"%" : ""
|
||||
x + " [" + v.to_s + "]" + perc
|
||||
}
|
||||
end
|
||||
|
||||
RADIANS = Math::PI/180
|
||||
|
||||
def draw_data
|
||||
@graph = @root.add_element( "g" )
|
||||
background = @graph.add_element("g")
|
||||
midground = @graph.add_element("g")
|
||||
|
||||
diameter = @graph_height > @graph_width ? @graph_width : @graph_height
|
||||
diameter -= expand_gap if expanded or expand_greatest
|
||||
diameter -= datapoint_font_size if show_data_labels
|
||||
diameter -= 10 if show_shadow
|
||||
radius = diameter / 2.0
|
||||
|
||||
xoff = (width - diameter) / 2
|
||||
yoff = (height - @border_bottom - diameter)
|
||||
yoff -= 10 if show_shadow
|
||||
@graph.attributes['transform'] = "translate( #{xoff} #{yoff} )"
|
||||
|
||||
wedge_text_pad = 5
|
||||
wedge_text_pad = 20 if show_percent and show_data_labels
|
||||
|
||||
total = 0
|
||||
max_value = 0
|
||||
@data.each {|x|
|
||||
max_value = max_value < x ? x : max_value
|
||||
total += x
|
||||
}
|
||||
percent_scale = 100.0 / total
|
||||
|
||||
prev_percent = 0
|
||||
rad_mult = 3.6 * RADIANS
|
||||
@config[:fields].each_index { |count|
|
||||
value = @data[count]
|
||||
percent = percent_scale * value
|
||||
|
||||
radians = prev_percent * rad_mult
|
||||
x_start = radius+(Math.sin(radians) * radius)
|
||||
y_start = radius-(Math.cos(radians) * radius)
|
||||
radians = (prev_percent+percent) * rad_mult
|
||||
x_end = radius+(Math.sin(radians) * radius)
|
||||
y_end = radius-(Math.cos(radians) * radius)
|
||||
path = "M#{radius},#{radius} L#{x_start},#{y_start} "+
|
||||
"A#{radius},#{radius} "+
|
||||
"0, #{percent >= 50 ? '1' : '0'},1, "+
|
||||
"#{x_end} #{y_end} Z"
|
||||
|
||||
|
||||
wedge = @foreground.add_element( "path", {
|
||||
"d" => path,
|
||||
"class" => "fill#{count+1}"
|
||||
})
|
||||
|
||||
translate = nil
|
||||
tx = 0
|
||||
ty = 0
|
||||
half_percent = prev_percent + percent / 2
|
||||
radians = half_percent * rad_mult
|
||||
|
||||
if show_shadow
|
||||
shadow = background.add_element( "path", {
|
||||
"d" => path,
|
||||
"filter" => "url(#dropshadow)",
|
||||
"style" => "fill: #ccc; stroke: none;"
|
||||
})
|
||||
clear = midground.add_element( "path", {
|
||||
"d" => path,
|
||||
"style" => "fill: #fff; stroke: none;"
|
||||
})
|
||||
end
|
||||
|
||||
if expanded or (expand_greatest && value == max_value)
|
||||
tx = (Math.sin(radians) * expand_gap)
|
||||
ty = -(Math.cos(radians) * expand_gap)
|
||||
translate = "translate( #{tx} #{ty} )"
|
||||
wedge.attributes["transform"] = translate
|
||||
clear.attributes["transform"] = translate
|
||||
end
|
||||
|
||||
if show_shadow
|
||||
shadow.attributes["transform"] =
|
||||
"translate( #{tx+shadow_offset} #{ty+shadow_offset} )"
|
||||
end
|
||||
|
||||
if show_data_labels and value != 0
|
||||
label = ""
|
||||
label += @config[:fields][count] if show_key_data_labels
|
||||
label += " ["+value.to_s+"]" if show_actual_values
|
||||
label += " "+percent.round.to_s+"%" if show_percent
|
||||
|
||||
msr = Math.sin(radians)
|
||||
mcr = Math.cos(radians)
|
||||
tx = radius + (msr * radius)
|
||||
ty = radius -(mcr * radius)
|
||||
|
||||
if expanded or (expand_greatest && value == max_value)
|
||||
tx += (msr * expand_gap)
|
||||
ty -= (mcr * expand_gap)
|
||||
end
|
||||
@foreground.add_element( "text", {
|
||||
"x" => tx.to_s,
|
||||
"y" => ty.to_s,
|
||||
"class" => "dataPointLabel",
|
||||
"style" => "stroke: #fff; stroke-width: 2;"
|
||||
}).text = label.to_s
|
||||
@foreground.add_element( "text", {
|
||||
"x" => tx.to_s,
|
||||
"y" => ty.to_s,
|
||||
"class" => "dataPointLabel",
|
||||
}).text = label.to_s
|
||||
end
|
||||
|
||||
prev_percent += percent
|
||||
}
|
||||
end
|
||||
|
||||
|
||||
def round val, to
|
||||
up = 10**to.to_f
|
||||
(val * up).to_i / up
|
||||
end
|
||||
|
||||
|
||||
def get_css
|
||||
return <<EOL
|
||||
.dataPointLabel{
|
||||
fill: #000000;
|
||||
text-anchor:middle;
|
||||
font-size: #{datapoint_font_size}px;
|
||||
font-family: "Arial", sans-serif;
|
||||
font-weight: normal;
|
||||
}
|
||||
|
||||
/* key - MUST match fill styles */
|
||||
.key1,.fill1{
|
||||
fill: #ff0000;
|
||||
fill-opacity: 0.7;
|
||||
stroke: none;
|
||||
stroke-width: 1px;
|
||||
}
|
||||
.key2,.fill2{
|
||||
fill: #0000ff;
|
||||
fill-opacity: 0.7;
|
||||
stroke: none;
|
||||
stroke-width: 1px;
|
||||
}
|
||||
.key3,.fill3{
|
||||
fill-opacity: 0.7;
|
||||
fill: #00ff00;
|
||||
stroke: none;
|
||||
stroke-width: 1px;
|
||||
}
|
||||
.key4,.fill4{
|
||||
fill-opacity: 0.7;
|
||||
fill: #ffcc00;
|
||||
stroke: none;
|
||||
stroke-width: 1px;
|
||||
}
|
||||
.key5,.fill5{
|
||||
fill-opacity: 0.7;
|
||||
fill: #00ccff;
|
||||
stroke: none;
|
||||
stroke-width: 1px;
|
||||
}
|
||||
.key6,.fill6{
|
||||
fill-opacity: 0.7;
|
||||
fill: #ff00ff;
|
||||
stroke: none;
|
||||
stroke-width: 1px;
|
||||
}
|
||||
.key7,.fill7{
|
||||
fill-opacity: 0.7;
|
||||
fill: #00ff99;
|
||||
stroke: none;
|
||||
stroke-width: 1px;
|
||||
}
|
||||
.key8,.fill8{
|
||||
fill-opacity: 0.7;
|
||||
fill: #ffff00;
|
||||
stroke: none;
|
||||
stroke-width: 1px;
|
||||
}
|
||||
.key9,.fill9{
|
||||
fill-opacity: 0.7;
|
||||
fill: #cc6666;
|
||||
stroke: none;
|
||||
stroke-width: 1px;
|
||||
}
|
||||
.key10,.fill10{
|
||||
fill-opacity: 0.7;
|
||||
fill: #663399;
|
||||
stroke: none;
|
||||
stroke-width: 1px;
|
||||
}
|
||||
.key11,.fill11{
|
||||
fill-opacity: 0.7;
|
||||
fill: #339900;
|
||||
stroke: none;
|
||||
stroke-width: 1px;
|
||||
}
|
||||
.key12,.fill12{
|
||||
fill-opacity: 0.7;
|
||||
fill: #9966FF;
|
||||
stroke: none;
|
||||
stroke-width: 1px;
|
||||
}
|
||||
EOL
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
@@ -0,0 +1,494 @@
|
||||
require 'SVG/Graph/Graph'
|
||||
|
||||
module SVG
|
||||
module Graph
|
||||
# === For creating SVG plots of scalar data
|
||||
#
|
||||
# = Synopsis
|
||||
#
|
||||
# require 'SVG/Graph/Plot'
|
||||
#
|
||||
# # Data sets are x,y pairs
|
||||
# # Note that multiple data sets can differ in length, and that the
|
||||
# # data in the datasets needn't be in order; they will be ordered
|
||||
# # by the plot along the X-axis.
|
||||
# projection = [
|
||||
# 6, 11, 0, 5, 18, 7, 1, 11, 13, 9, 1, 2, 19, 0, 3, 13,
|
||||
# 7, 9
|
||||
# ]
|
||||
# actual = [
|
||||
# 0, 18, 8, 15, 9, 4, 18, 14, 10, 2, 11, 6, 14, 12,
|
||||
# 15, 6, 4, 17, 2, 12
|
||||
# ]
|
||||
#
|
||||
# graph = SVG::Graph::Plot.new({
|
||||
# :height => 500,
|
||||
# :width => 300,
|
||||
# :key => true,
|
||||
# :scale_x_integers => true,
|
||||
# :scale_y_integerrs => true,
|
||||
# })
|
||||
#
|
||||
# graph.add_data({
|
||||
# :data => projection
|
||||
# :title => 'Projected',
|
||||
# })
|
||||
#
|
||||
# graph.add_data({
|
||||
# :data => actual,
|
||||
# :title => 'Actual',
|
||||
# })
|
||||
#
|
||||
# print graph.burn()
|
||||
#
|
||||
# = Description
|
||||
#
|
||||
# Produces a graph of scalar data.
|
||||
#
|
||||
# This object aims to allow you to easily create high quality
|
||||
# SVG[http://www.w3c.org/tr/svg] scalar plots. You can either use the
|
||||
# default style sheet or supply your own. Either way there are many options
|
||||
# which can be configured to give you control over how the graph is
|
||||
# generated - with or without a key, data elements at each point, title,
|
||||
# subtitle etc.
|
||||
#
|
||||
# = Examples
|
||||
#
|
||||
# http://www.germane-software/repositories/public/SVG/test/plot.rb
|
||||
#
|
||||
# = Notes
|
||||
#
|
||||
# The default stylesheet handles upto 10 data sets, if you
|
||||
# use more you must create your own stylesheet and add the
|
||||
# additional settings for the extra data sets. You will know
|
||||
# if you go over 10 data sets as they will have no style and
|
||||
# be in black.
|
||||
#
|
||||
# Unlike the other types of charts, data sets must contain x,y pairs:
|
||||
#
|
||||
# [ 1, 2 ] # A data set with 1 point: (1,2)
|
||||
# [ 1,2, 5,6] # A data set with 2 points: (1,2) and (5,6)
|
||||
#
|
||||
# = See also
|
||||
#
|
||||
# * SVG::Graph::Graph
|
||||
# * SVG::Graph::BarHorizontal
|
||||
# * SVG::Graph::Bar
|
||||
# * SVG::Graph::Line
|
||||
# * SVG::Graph::Pie
|
||||
# * SVG::Graph::TimeSeries
|
||||
#
|
||||
# == Author
|
||||
#
|
||||
# Sean E. Russell <serATgermaneHYPHENsoftwareDOTcom>
|
||||
#
|
||||
# Copyright 2004 Sean E. Russell
|
||||
# This software is available under the Ruby license[LICENSE.txt]
|
||||
#
|
||||
class Plot < Graph
|
||||
|
||||
# In addition to the defaults set by Graph::initialize, sets
|
||||
# [show_data_points] true
|
||||
# [area_fill] false
|
||||
# [stacked] false
|
||||
def set_defaults
|
||||
init_with(
|
||||
:show_data_points => true,
|
||||
:area_fill => false,
|
||||
:stacked => false
|
||||
)
|
||||
self.top_align = self.right_align = self.top_font = self.right_font = 1
|
||||
end
|
||||
|
||||
# Determines the scaling for the X axis divisions.
|
||||
#
|
||||
# graph.scale_x_divisions = 2
|
||||
#
|
||||
# would cause the graph to attempt to generate labels stepped by 2; EG:
|
||||
# 0,2,4,6,8...
|
||||
attr_accessor :scale_x_divisions
|
||||
# Determines the scaling for the Y axis divisions.
|
||||
#
|
||||
# graph.scale_y_divisions = 0.5
|
||||
#
|
||||
# would cause the graph to attempt to generate labels stepped by 0.5; EG:
|
||||
# 0, 0.5, 1, 1.5, 2, ...
|
||||
attr_accessor :scale_y_divisions
|
||||
# Make the X axis labels integers
|
||||
attr_accessor :scale_x_integers
|
||||
# Make the Y axis labels integers
|
||||
attr_accessor :scale_y_integers
|
||||
# Fill the area under the line
|
||||
attr_accessor :area_fill
|
||||
# Show a small circle on the graph where the line
|
||||
# goes from one point to the next.
|
||||
attr_accessor :show_data_points
|
||||
# Set the minimum value of the X axis
|
||||
attr_accessor :min_x_value
|
||||
# Set the minimum value of the Y axis
|
||||
attr_accessor :min_y_value
|
||||
|
||||
|
||||
# Adds data to the plot. The data must be in X,Y pairs; EG
|
||||
# [ 1, 2 ] # A data set with 1 point: (1,2)
|
||||
# [ 1,2, 5,6] # A data set with 2 points: (1,2) and (5,6)
|
||||
def add_data data
|
||||
@data = [] unless @data
|
||||
|
||||
raise "No data provided by #{conf.inspect}" unless data[:data] and
|
||||
data[:data].kind_of? Array
|
||||
raise "Data supplied must be x,y pairs! "+
|
||||
"The data provided contained an odd set of "+
|
||||
"data points" unless data[:data].length % 2 == 0
|
||||
return if data[:data].length == 0
|
||||
|
||||
x = []
|
||||
y = []
|
||||
data[:data].each_index {|i|
|
||||
(i%2 == 0 ? x : y) << data[:data][i]
|
||||
}
|
||||
sort( x, y )
|
||||
data[:data] = [x,y]
|
||||
@data << data
|
||||
end
|
||||
|
||||
|
||||
protected
|
||||
|
||||
def keys
|
||||
@data.collect{ |x| x[:title] }
|
||||
end
|
||||
|
||||
def calculate_left_margin
|
||||
super
|
||||
label_left = get_x_labels[0].to_s.length / 2 * font_size * 0.6
|
||||
@border_left = label_left if label_left > @border_left
|
||||
end
|
||||
|
||||
def calculate_right_margin
|
||||
super
|
||||
label_right = get_x_labels[-1].to_s.length / 2 * font_size * 0.6
|
||||
@border_right = label_right if label_right > @border_right
|
||||
end
|
||||
|
||||
|
||||
X = 0
|
||||
Y = 1
|
||||
def x_range
|
||||
max_value = @data.collect{|x| x[:data][X][-1] }.max
|
||||
min_value = @data.collect{|x| x[:data][X][0] }.min
|
||||
min_value = min_value<min_x_value ? min_value : min_x_value if min_x_value
|
||||
|
||||
range = max_value - min_value
|
||||
right_pad = range == 0 ? 10 : range / 20.0
|
||||
scale_range = (max_value + right_pad) - min_value
|
||||
|
||||
scale_division = scale_x_divisions || (scale_range / 10.0)
|
||||
|
||||
if scale_x_integers
|
||||
scale_division = scale_division < 1 ? 1 : scale_division.round
|
||||
end
|
||||
|
||||
[min_value, max_value, scale_division]
|
||||
end
|
||||
|
||||
def get_x_values
|
||||
min_value, max_value, scale_division = x_range
|
||||
rv = []
|
||||
min_value.step( max_value, scale_division ) {|v| rv << v}
|
||||
return rv
|
||||
end
|
||||
alias :get_x_labels :get_x_values
|
||||
|
||||
def field_width
|
||||
values = get_x_values
|
||||
max = @data.collect{|x| x[:data][X][-1]}.max
|
||||
dx = (max - values[-1]).to_f / (values[-1] - values[-2])
|
||||
(@graph_width.to_f - font_size*2*right_font) /
|
||||
(values.length + dx - right_align)
|
||||
end
|
||||
|
||||
|
||||
def y_range
|
||||
max_value = @data.collect{|x| x[:data][Y].max }.max
|
||||
min_value = @data.collect{|x| x[:data][Y].min }.min
|
||||
min_value = min_value<min_y_value ? min_value : min_y_value if min_y_value
|
||||
|
||||
range = max_value - min_value
|
||||
top_pad = range == 0 ? 10 : range / 20.0
|
||||
scale_range = (max_value + top_pad) - min_value
|
||||
|
||||
scale_division = scale_y_divisions || (scale_range / 10.0)
|
||||
|
||||
if scale_y_integers
|
||||
scale_division = scale_division < 1 ? 1 : scale_division.round
|
||||
end
|
||||
|
||||
return [min_value, max_value, scale_division]
|
||||
end
|
||||
|
||||
def get_y_values
|
||||
min_value, max_value, scale_division = y_range
|
||||
rv = []
|
||||
min_value.step( max_value, scale_division ) {|v| rv << v}
|
||||
return rv
|
||||
end
|
||||
alias :get_y_labels :get_y_values
|
||||
|
||||
def field_height
|
||||
values = get_y_values
|
||||
max = @data.collect{|x| x[:data][Y].max }.max
|
||||
dx = (max - values[-1]).to_f / (values[-1] - values[-2])
|
||||
(@graph_height.to_f - font_size*2*top_font) /
|
||||
(values.length + dx - top_align)
|
||||
end
|
||||
|
||||
def draw_data
|
||||
line = 1
|
||||
|
||||
x_min, x_max, x_div = x_range
|
||||
y_min, y_max, y_div = y_range
|
||||
x_step = (@graph_width.to_f - font_size*2) / (x_max-x_min)
|
||||
y_step = (@graph_height.to_f - font_size*2) / (y_max-y_min)
|
||||
|
||||
for data in @data
|
||||
x_points = data[:data][X]
|
||||
y_points = data[:data][Y]
|
||||
|
||||
lpath = "L"
|
||||
x_start = 0
|
||||
y_start = 0
|
||||
x_points.each_index { |idx|
|
||||
x = (x_points[idx] - x_min) * x_step
|
||||
y = @graph_height - (y_points[idx] - y_min) * y_step
|
||||
x_start, y_start = x,y if idx == 0
|
||||
lpath << "#{x} #{y} "
|
||||
}
|
||||
|
||||
if area_fill
|
||||
@graph.add_element( "path", {
|
||||
"d" => "M#{x_start} #@graph_height #{lpath} V#@graph_height Z",
|
||||
"class" => "fill#{line}"
|
||||
})
|
||||
end
|
||||
|
||||
@graph.add_element( "path", {
|
||||
"d" => "M#{x_start} #{y_start} #{lpath}",
|
||||
"class" => "line#{line}"
|
||||
})
|
||||
|
||||
if show_data_points || show_data_values
|
||||
x_points.each_index { |idx|
|
||||
x = (x_points[idx] - x_min) * x_step
|
||||
y = @graph_height - (y_points[idx] - y_min) * y_step
|
||||
if show_data_points
|
||||
@graph.add_element( "circle", {
|
||||
"cx" => x.to_s,
|
||||
"cy" => y.to_s,
|
||||
"r" => "2.5",
|
||||
"class" => "dataPoint#{line}"
|
||||
})
|
||||
add_popup(x, y, format( x_points[idx], y_points[idx] )) if add_popups
|
||||
end
|
||||
make_datapoint_text( x, y-6, y_points[idx] )
|
||||
}
|
||||
end
|
||||
line += 1
|
||||
end
|
||||
end
|
||||
|
||||
def format x, y
|
||||
"(#{(x * 100).to_i / 100}, #{(y * 100).to_i / 100})"
|
||||
end
|
||||
|
||||
def get_css
|
||||
return <<EOL
|
||||
/* default line styles */
|
||||
.line1{
|
||||
fill: none;
|
||||
stroke: #ff0000;
|
||||
stroke-width: 1px;
|
||||
}
|
||||
.line2{
|
||||
fill: none;
|
||||
stroke: #0000ff;
|
||||
stroke-width: 1px;
|
||||
}
|
||||
.line3{
|
||||
fill: none;
|
||||
stroke: #00ff00;
|
||||
stroke-width: 1px;
|
||||
}
|
||||
.line4{
|
||||
fill: none;
|
||||
stroke: #ffcc00;
|
||||
stroke-width: 1px;
|
||||
}
|
||||
.line5{
|
||||
fill: none;
|
||||
stroke: #00ccff;
|
||||
stroke-width: 1px;
|
||||
}
|
||||
.line6{
|
||||
fill: none;
|
||||
stroke: #ff00ff;
|
||||
stroke-width: 1px;
|
||||
}
|
||||
.line7{
|
||||
fill: none;
|
||||
stroke: #00ffff;
|
||||
stroke-width: 1px;
|
||||
}
|
||||
.line8{
|
||||
fill: none;
|
||||
stroke: #ffff00;
|
||||
stroke-width: 1px;
|
||||
}
|
||||
.line9{
|
||||
fill: none;
|
||||
stroke: #ccc6666;
|
||||
stroke-width: 1px;
|
||||
}
|
||||
.line10{
|
||||
fill: none;
|
||||
stroke: #663399;
|
||||
stroke-width: 1px;
|
||||
}
|
||||
.line11{
|
||||
fill: none;
|
||||
stroke: #339900;
|
||||
stroke-width: 1px;
|
||||
}
|
||||
.line12{
|
||||
fill: none;
|
||||
stroke: #9966FF;
|
||||
stroke-width: 1px;
|
||||
}
|
||||
/* default fill styles */
|
||||
.fill1{
|
||||
fill: #cc0000;
|
||||
fill-opacity: 0.2;
|
||||
stroke: none;
|
||||
}
|
||||
.fill2{
|
||||
fill: #0000cc;
|
||||
fill-opacity: 0.2;
|
||||
stroke: none;
|
||||
}
|
||||
.fill3{
|
||||
fill: #00cc00;
|
||||
fill-opacity: 0.2;
|
||||
stroke: none;
|
||||
}
|
||||
.fill4{
|
||||
fill: #ffcc00;
|
||||
fill-opacity: 0.2;
|
||||
stroke: none;
|
||||
}
|
||||
.fill5{
|
||||
fill: #00ccff;
|
||||
fill-opacity: 0.2;
|
||||
stroke: none;
|
||||
}
|
||||
.fill6{
|
||||
fill: #ff00ff;
|
||||
fill-opacity: 0.2;
|
||||
stroke: none;
|
||||
}
|
||||
.fill7{
|
||||
fill: #00ffff;
|
||||
fill-opacity: 0.2;
|
||||
stroke: none;
|
||||
}
|
||||
.fill8{
|
||||
fill: #ffff00;
|
||||
fill-opacity: 0.2;
|
||||
stroke: none;
|
||||
}
|
||||
.fill9{
|
||||
fill: #cc6666;
|
||||
fill-opacity: 0.2;
|
||||
stroke: none;
|
||||
}
|
||||
.fill10{
|
||||
fill: #663399;
|
||||
fill-opacity: 0.2;
|
||||
stroke: none;
|
||||
}
|
||||
.fill11{
|
||||
fill: #339900;
|
||||
fill-opacity: 0.2;
|
||||
stroke: none;
|
||||
}
|
||||
.fill12{
|
||||
fill: #9966FF;
|
||||
fill-opacity: 0.2;
|
||||
stroke: none;
|
||||
}
|
||||
/* default line styles */
|
||||
.key1,.dataPoint1{
|
||||
fill: #ff0000;
|
||||
stroke: none;
|
||||
stroke-width: 1px;
|
||||
}
|
||||
.key2,.dataPoint2{
|
||||
fill: #0000ff;
|
||||
stroke: none;
|
||||
stroke-width: 1px;
|
||||
}
|
||||
.key3,.dataPoint3{
|
||||
fill: #00ff00;
|
||||
stroke: none;
|
||||
stroke-width: 1px;
|
||||
}
|
||||
.key4,.dataPoint4{
|
||||
fill: #ffcc00;
|
||||
stroke: none;
|
||||
stroke-width: 1px;
|
||||
}
|
||||
.key5,.dataPoint5{
|
||||
fill: #00ccff;
|
||||
stroke: none;
|
||||
stroke-width: 1px;
|
||||
}
|
||||
.key6,.dataPoint6{
|
||||
fill: #ff00ff;
|
||||
stroke: none;
|
||||
stroke-width: 1px;
|
||||
}
|
||||
.key7,.dataPoint7{
|
||||
fill: #00ffff;
|
||||
stroke: none;
|
||||
stroke-width: 1px;
|
||||
}
|
||||
.key8,.dataPoint8{
|
||||
fill: #ffff00;
|
||||
stroke: none;
|
||||
stroke-width: 1px;
|
||||
}
|
||||
.key9,.dataPoint9{
|
||||
fill: #cc6666;
|
||||
stroke: none;
|
||||
stroke-width: 1px;
|
||||
}
|
||||
.key10,.dataPoint10{
|
||||
fill: #663399;
|
||||
stroke: none;
|
||||
stroke-width: 1px;
|
||||
}
|
||||
.key11,.dataPoint11{
|
||||
fill: #339900;
|
||||
stroke: none;
|
||||
stroke-width: 1px;
|
||||
}
|
||||
.key12,.dataPoint12{
|
||||
fill: #9966FF;
|
||||
stroke: none;
|
||||
stroke-width: 1px;
|
||||
}
|
||||
EOL
|
||||
end
|
||||
|
||||
end
|
||||
end
|
||||
end
|
||||
@@ -0,0 +1,373 @@
|
||||
require 'SVG/Graph/Plot'
|
||||
require 'parsedate'
|
||||
|
||||
module SVG
|
||||
module Graph
|
||||
# === For creating SVG plots of scalar temporal data
|
||||
#
|
||||
# = Synopsis
|
||||
#
|
||||
# require 'SVG/Graph/Schedule'
|
||||
#
|
||||
# # Data sets are label, start, end tripples.
|
||||
# data1 = [
|
||||
# "Housesitting", "6/17/04", "6/19/04",
|
||||
# "Summer Session", "6/15/04", "8/15/04",
|
||||
# ]
|
||||
#
|
||||
# graph = SVG::Graph::Schedule.new( {
|
||||
# :width => 640,
|
||||
# :height => 480,
|
||||
# :graph_title => title,
|
||||
# :show_graph_title => true,
|
||||
# :no_css => true,
|
||||
# :scale_x_integers => true,
|
||||
# :scale_y_integers => true,
|
||||
# :min_x_value => 0,
|
||||
# :min_y_value => 0,
|
||||
# :show_data_labels => true,
|
||||
# :show_x_guidelines => true,
|
||||
# :show_x_title => true,
|
||||
# :x_title => "Time",
|
||||
# :stagger_x_labels => true,
|
||||
# :stagger_y_labels => true,
|
||||
# :x_label_format => "%m/%d/%y",
|
||||
# })
|
||||
#
|
||||
# graph.add_data({
|
||||
# :data => data1,
|
||||
# :title => 'Data',
|
||||
# })
|
||||
#
|
||||
# print graph.burn()
|
||||
#
|
||||
# = Description
|
||||
#
|
||||
# Produces a graph of temporal scalar data.
|
||||
#
|
||||
# = Examples
|
||||
#
|
||||
# http://www.germane-software/repositories/public/SVG/test/schedule.rb
|
||||
#
|
||||
# = Notes
|
||||
#
|
||||
# The default stylesheet handles upto 10 data sets, if you
|
||||
# use more you must create your own stylesheet and add the
|
||||
# additional settings for the extra data sets. You will know
|
||||
# if you go over 10 data sets as they will have no style and
|
||||
# be in black.
|
||||
#
|
||||
# Note that multiple data sets within the same chart can differ in
|
||||
# length, and that the data in the datasets needn't be in order;
|
||||
# they will be ordered by the plot along the X-axis.
|
||||
#
|
||||
# The dates must be parseable by ParseDate, but otherwise can be
|
||||
# any order of magnitude (seconds within the hour, or years)
|
||||
#
|
||||
# = See also
|
||||
#
|
||||
# * SVG::Graph::Graph
|
||||
# * SVG::Graph::BarHorizontal
|
||||
# * SVG::Graph::Bar
|
||||
# * SVG::Graph::Line
|
||||
# * SVG::Graph::Pie
|
||||
# * SVG::Graph::Plot
|
||||
# * SVG::Graph::TimeSeries
|
||||
#
|
||||
# == Author
|
||||
#
|
||||
# Sean E. Russell <serATgermaneHYPHENsoftwareDOTcom>
|
||||
#
|
||||
# Copyright 2004 Sean E. Russell
|
||||
# This software is available under the Ruby license[LICENSE.txt]
|
||||
#
|
||||
class Schedule < Graph
|
||||
# In addition to the defaults set by Graph::initialize and
|
||||
# Plot::set_defaults, sets:
|
||||
# [x_label_format] '%Y-%m-%d %H:%M:%S'
|
||||
# [popup_format] '%Y-%m-%d %H:%M:%S'
|
||||
def set_defaults
|
||||
init_with(
|
||||
:x_label_format => '%Y-%m-%d %H:%M:%S',
|
||||
:popup_format => '%Y-%m-%d %H:%M:%S',
|
||||
:scale_x_divisions => false,
|
||||
:scale_x_integers => false,
|
||||
:bar_gap => true
|
||||
)
|
||||
end
|
||||
|
||||
# The format string use do format the X axis labels.
|
||||
# See Time::strformat
|
||||
attr_accessor :x_label_format
|
||||
# Use this to set the spacing between dates on the axis. The value
|
||||
# must be of the form
|
||||
# "\d+ ?(days|weeks|months|years|hours|minutes|seconds)?"
|
||||
#
|
||||
# EG:
|
||||
#
|
||||
# graph.timescale_divisions = "2 weeks"
|
||||
#
|
||||
# will cause the chart to try to divide the X axis up into segments of
|
||||
# two week periods.
|
||||
attr_accessor :timescale_divisions
|
||||
# The formatting used for the popups. See x_label_format
|
||||
attr_accessor :popup_format
|
||||
attr_accessor :min_x_value
|
||||
attr_accessor :scale_x_divisions
|
||||
attr_accessor :scale_x_integers
|
||||
attr_accessor :bar_gap
|
||||
|
||||
# Add data to the plot.
|
||||
#
|
||||
# # A data set with 1 point: Lunch from 12:30 to 14:00
|
||||
# d1 = [ "Lunch", "12:30", "14:00" ]
|
||||
# # A data set with 2 points: "Cats" runs from 5/11/03 to 7/15/04, and
|
||||
# # "Henry V" runs from 6/12/03 to 8/20/03
|
||||
# d2 = [ "Cats", "5/11/03", "7/15/04",
|
||||
# "Henry V", "6/12/03", "8/20/03" ]
|
||||
#
|
||||
# graph.add_data(
|
||||
# :data => d1,
|
||||
# :title => 'Meetings'
|
||||
# )
|
||||
# graph.add_data(
|
||||
# :data => d2,
|
||||
# :title => 'Plays'
|
||||
# )
|
||||
#
|
||||
# Note that the data must be in time,value pairs, and that the date format
|
||||
# may be any date that is parseable by ParseDate.
|
||||
# Also note that, in this example, we're mixing scales; the data from d1
|
||||
# will probably not be discernable if both data sets are plotted on the same
|
||||
# graph, since d1 is too granular.
|
||||
def add_data data
|
||||
@data = [] unless @data
|
||||
|
||||
raise "No data provided by #{conf.inspect}" unless data[:data] and
|
||||
data[:data].kind_of? Array
|
||||
raise "Data supplied must be title,from,to tripples! "+
|
||||
"The data provided contained an odd set of "+
|
||||
"data points" unless data[:data].length % 3 == 0
|
||||
return if data[:data].length == 0
|
||||
|
||||
|
||||
y = []
|
||||
x_start = []
|
||||
x_end = []
|
||||
data[:data].each_index {|i|
|
||||
im3 = i%3
|
||||
if im3 == 0
|
||||
y << data[:data][i]
|
||||
else
|
||||
arr = ParseDate.parsedate( data[:data][i] )
|
||||
t = Time.local( *arr[0,6].compact )
|
||||
(im3 == 1 ? x_start : x_end) << t.to_i
|
||||
end
|
||||
}
|
||||
sort( x_start, x_end, y )
|
||||
@data = [x_start, x_end, y ]
|
||||
end
|
||||
|
||||
|
||||
protected
|
||||
|
||||
def min_x_value=(value)
|
||||
arr = ParseDate.parsedate( value )
|
||||
@min_x_value = Time.local( *arr[0,6].compact ).to_i
|
||||
end
|
||||
|
||||
|
||||
def format x, y
|
||||
Time.at( x ).strftime( popup_format )
|
||||
end
|
||||
|
||||
def get_x_labels
|
||||
rv = get_x_values.collect { |v| Time.at(v).strftime( x_label_format ) }
|
||||
end
|
||||
|
||||
def y_label_offset( height )
|
||||
height / -2.0
|
||||
end
|
||||
|
||||
def get_y_labels
|
||||
@data[2]
|
||||
end
|
||||
|
||||
def draw_data
|
||||
fieldheight = field_height
|
||||
fieldwidth = field_width
|
||||
|
||||
bargap = bar_gap ? (fieldheight < 10 ? fieldheight / 2 : 10) : 0
|
||||
subbar_height = fieldheight - bargap
|
||||
|
||||
field_count = 1
|
||||
y_mod = (subbar_height / 2) + (font_size / 2)
|
||||
min,max,div = x_range
|
||||
scale = (@graph_width.to_f - font_size*2) / (max-min)
|
||||
@data[0].each_index { |i|
|
||||
x_start = @data[0][i]
|
||||
x_end = @data[1][i]
|
||||
y = @graph_height - (fieldheight * field_count)
|
||||
bar_width = (x_end-x_start) * scale
|
||||
bar_start = x_start * scale - (min * scale)
|
||||
|
||||
@graph.add_element( "rect", {
|
||||
"x" => bar_start.to_s,
|
||||
"y" => y.to_s,
|
||||
"width" => bar_width.to_s,
|
||||
"height" => subbar_height.to_s,
|
||||
"class" => "fill#{field_count+1}"
|
||||
})
|
||||
field_count += 1
|
||||
}
|
||||
end
|
||||
|
||||
def get_css
|
||||
return <<EOL
|
||||
/* default fill styles for multiple datasets (probably only use a single dataset on this graph though) */
|
||||
.key1,.fill1{
|
||||
fill: #ff0000;
|
||||
fill-opacity: 0.5;
|
||||
stroke: none;
|
||||
stroke-width: 0.5px;
|
||||
}
|
||||
.key2,.fill2{
|
||||
fill: #0000ff;
|
||||
fill-opacity: 0.5;
|
||||
stroke: none;
|
||||
stroke-width: 1px;
|
||||
}
|
||||
.key3,.fill3{
|
||||
fill: #00ff00;
|
||||
fill-opacity: 0.5;
|
||||
stroke: none;
|
||||
stroke-width: 1px;
|
||||
}
|
||||
.key4,.fill4{
|
||||
fill: #ffcc00;
|
||||
fill-opacity: 0.5;
|
||||
stroke: none;
|
||||
stroke-width: 1px;
|
||||
}
|
||||
.key5,.fill5{
|
||||
fill: #00ccff;
|
||||
fill-opacity: 0.5;
|
||||
stroke: none;
|
||||
stroke-width: 1px;
|
||||
}
|
||||
.key6,.fill6{
|
||||
fill: #ff00ff;
|
||||
fill-opacity: 0.5;
|
||||
stroke: none;
|
||||
stroke-width: 1px;
|
||||
}
|
||||
.key7,.fill7{
|
||||
fill: #00ffff;
|
||||
fill-opacity: 0.5;
|
||||
stroke: none;
|
||||
stroke-width: 1px;
|
||||
}
|
||||
.key8,.fill8{
|
||||
fill: #ffff00;
|
||||
fill-opacity: 0.5;
|
||||
stroke: none;
|
||||
stroke-width: 1px;
|
||||
}
|
||||
.key9,.fill9{
|
||||
fill: #cc6666;
|
||||
fill-opacity: 0.5;
|
||||
stroke: none;
|
||||
stroke-width: 1px;
|
||||
}
|
||||
.key10,.fill10{
|
||||
fill: #663399;
|
||||
fill-opacity: 0.5;
|
||||
stroke: none;
|
||||
stroke-width: 1px;
|
||||
}
|
||||
.key11,.fill11{
|
||||
fill: #339900;
|
||||
fill-opacity: 0.5;
|
||||
stroke: none;
|
||||
stroke-width: 1px;
|
||||
}
|
||||
.key12,.fill12{
|
||||
fill: #9966FF;
|
||||
fill-opacity: 0.5;
|
||||
stroke: none;
|
||||
stroke-width: 1px;
|
||||
}
|
||||
EOL
|
||||
end
|
||||
|
||||
private
|
||||
def x_range
|
||||
max_value = [ @data[0][-1], @data[1].max ].max
|
||||
min_value = [ @data[0][0], @data[1].min ].min
|
||||
min_value = min_value<min_x_value ? min_value : min_x_value if min_x_value
|
||||
|
||||
range = max_value - min_value
|
||||
right_pad = range == 0 ? 10 : range / 20.0
|
||||
scale_range = (max_value + right_pad) - min_value
|
||||
|
||||
scale_division = scale_x_divisions || (scale_range / 10.0)
|
||||
|
||||
if scale_x_integers
|
||||
scale_division = scale_division < 1 ? 1 : scale_division.round
|
||||
end
|
||||
|
||||
[min_value, max_value, scale_division]
|
||||
end
|
||||
|
||||
def get_x_values
|
||||
rv = []
|
||||
min, max, scale_division = x_range
|
||||
if timescale_divisions
|
||||
timescale_divisions =~ /(\d+) ?(days|weeks|months|years|hours|minutes|seconds)?/
|
||||
division_units = $2 ? $2 : "days"
|
||||
amount = $1.to_i
|
||||
if amount
|
||||
step = nil
|
||||
case division_units
|
||||
when "months"
|
||||
cur = min
|
||||
while cur < max
|
||||
rv << cur
|
||||
arr = Time.at( cur ).to_a
|
||||
arr[4] += amount
|
||||
if arr[4] > 12
|
||||
arr[5] += (arr[4] / 12).to_i
|
||||
arr[4] = (arr[4] % 12)
|
||||
end
|
||||
cur = Time.local(*arr).to_i
|
||||
end
|
||||
when "years"
|
||||
cur = min
|
||||
while cur < max
|
||||
rv << cur
|
||||
arr = Time.at( cur ).to_a
|
||||
arr[5] += amount
|
||||
cur = Time.local(*arr).to_i
|
||||
end
|
||||
when "weeks"
|
||||
step = 7 * 24 * 60 * 60 * amount
|
||||
when "days"
|
||||
step = 24 * 60 * 60 * amount
|
||||
when "hours"
|
||||
step = 60 * 60 * amount
|
||||
when "minutes"
|
||||
step = 60 * amount
|
||||
when "seconds"
|
||||
step = amount
|
||||
end
|
||||
min.step( max, step ) {|v| rv << v} if step
|
||||
|
||||
return rv
|
||||
end
|
||||
end
|
||||
min.step( max, scale_division ) {|v| rv << v}
|
||||
return rv
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
@@ -0,0 +1,241 @@
|
||||
require 'SVG/Graph/Plot'
|
||||
require 'parsedate'
|
||||
|
||||
module SVG
|
||||
module Graph
|
||||
# === For creating SVG plots of scalar temporal data
|
||||
#
|
||||
# = Synopsis
|
||||
#
|
||||
# require 'SVG/Graph/TimeSeriess'
|
||||
#
|
||||
# # Data sets are x,y pairs
|
||||
# data1 = ["6/17/72", 11, "1/11/72", 7, "4/13/04 17:31", 11,
|
||||
# "9/11/01", 9, "9/1/85", 2, "9/1/88", 1, "1/15/95", 13]
|
||||
# data2 = ["8/1/73", 18, "3/1/77", 15, "10/1/98", 4,
|
||||
# "5/1/02", 14, "3/1/95", 6, "8/1/91", 12, "12/1/87", 6,
|
||||
# "5/1/84", 17, "10/1/80", 12]
|
||||
#
|
||||
# graph = SVG::Graph::TimeSeries.new( {
|
||||
# :width => 640,
|
||||
# :height => 480,
|
||||
# :graph_title => title,
|
||||
# :show_graph_title => true,
|
||||
# :no_css => true,
|
||||
# :key => true,
|
||||
# :scale_x_integers => true,
|
||||
# :scale_y_integers => true,
|
||||
# :min_x_value => 0,
|
||||
# :min_y_value => 0,
|
||||
# :show_data_labels => true,
|
||||
# :show_x_guidelines => true,
|
||||
# :show_x_title => true,
|
||||
# :x_title => "Time",
|
||||
# :show_y_title => true,
|
||||
# :y_title => "Ice Cream Cones",
|
||||
# :y_title_text_direction => :bt,
|
||||
# :stagger_x_labels => true,
|
||||
# :x_label_format => "%m/%d/%y",
|
||||
# })
|
||||
#
|
||||
# graph.add_data({
|
||||
# :data => projection
|
||||
# :title => 'Projected',
|
||||
# })
|
||||
#
|
||||
# graph.add_data({
|
||||
# :data => actual,
|
||||
# :title => 'Actual',
|
||||
# })
|
||||
#
|
||||
# print graph.burn()
|
||||
#
|
||||
# = Description
|
||||
#
|
||||
# Produces a graph of temporal scalar data.
|
||||
#
|
||||
# = Examples
|
||||
#
|
||||
# http://www.germane-software/repositories/public/SVG/test/timeseries.rb
|
||||
#
|
||||
# = Notes
|
||||
#
|
||||
# The default stylesheet handles upto 10 data sets, if you
|
||||
# use more you must create your own stylesheet and add the
|
||||
# additional settings for the extra data sets. You will know
|
||||
# if you go over 10 data sets as they will have no style and
|
||||
# be in black.
|
||||
#
|
||||
# Unlike the other types of charts, data sets must contain x,y pairs:
|
||||
#
|
||||
# [ "12:30", 2 ] # A data set with 1 point: ("12:30",2)
|
||||
# [ "01:00",2, "14:20",6] # A data set with 2 points: ("01:00",2) and
|
||||
# # ("14:20",6)
|
||||
#
|
||||
# Note that multiple data sets within the same chart can differ in length,
|
||||
# and that the data in the datasets needn't be in order; they will be ordered
|
||||
# by the plot along the X-axis.
|
||||
#
|
||||
# The dates must be parseable by ParseDate, but otherwise can be
|
||||
# any order of magnitude (seconds within the hour, or years)
|
||||
#
|
||||
# = See also
|
||||
#
|
||||
# * SVG::Graph::Graph
|
||||
# * SVG::Graph::BarHorizontal
|
||||
# * SVG::Graph::Bar
|
||||
# * SVG::Graph::Line
|
||||
# * SVG::Graph::Pie
|
||||
# * SVG::Graph::Plot
|
||||
#
|
||||
# == Author
|
||||
#
|
||||
# Sean E. Russell <serATgermaneHYPHENsoftwareDOTcom>
|
||||
#
|
||||
# Copyright 2004 Sean E. Russell
|
||||
# This software is available under the Ruby license[LICENSE.txt]
|
||||
#
|
||||
class TimeSeries < Plot
|
||||
# In addition to the defaults set by Graph::initialize and
|
||||
# Plot::set_defaults, sets:
|
||||
# [x_label_format] '%Y-%m-%d %H:%M:%S'
|
||||
# [popup_format] '%Y-%m-%d %H:%M:%S'
|
||||
def set_defaults
|
||||
super
|
||||
init_with(
|
||||
#:max_time_span => '',
|
||||
:x_label_format => '%Y-%m-%d %H:%M:%S',
|
||||
:popup_format => '%Y-%m-%d %H:%M:%S'
|
||||
)
|
||||
end
|
||||
|
||||
# The format string use do format the X axis labels.
|
||||
# See Time::strformat
|
||||
attr_accessor :x_label_format
|
||||
# Use this to set the spacing between dates on the axis. The value
|
||||
# must be of the form
|
||||
# "\d+ ?(days|weeks|months|years|hours|minutes|seconds)?"
|
||||
#
|
||||
# EG:
|
||||
#
|
||||
# graph.timescale_divisions = "2 weeks"
|
||||
#
|
||||
# will cause the chart to try to divide the X axis up into segments of
|
||||
# two week periods.
|
||||
attr_accessor :timescale_divisions
|
||||
# The formatting used for the popups. See x_label_format
|
||||
attr_accessor :popup_format
|
||||
|
||||
# Add data to the plot.
|
||||
#
|
||||
# d1 = [ "12:30", 2 ] # A data set with 1 point: ("12:30",2)
|
||||
# d2 = [ "01:00",2, "14:20",6] # A data set with 2 points: ("01:00",2) and
|
||||
# # ("14:20",6)
|
||||
# graph.add_data(
|
||||
# :data => d1,
|
||||
# :title => 'One'
|
||||
# )
|
||||
# graph.add_data(
|
||||
# :data => d2,
|
||||
# :title => 'Two'
|
||||
# )
|
||||
#
|
||||
# Note that the data must be in time,value pairs, and that the date format
|
||||
# may be any date that is parseable by ParseDate.
|
||||
def add_data data
|
||||
@data = [] unless @data
|
||||
|
||||
raise "No data provided by #{conf.inspect}" unless data[:data] and
|
||||
data[:data].kind_of? Array
|
||||
raise "Data supplied must be x,y pairs! "+
|
||||
"The data provided contained an odd set of "+
|
||||
"data points" unless data[:data].length % 2 == 0
|
||||
return if data[:data].length == 0
|
||||
|
||||
|
||||
x = []
|
||||
y = []
|
||||
data[:data].each_index {|i|
|
||||
if i%2 == 0
|
||||
arr = ParseDate.parsedate( data[:data][i] )
|
||||
t = Time.local( *arr[0,6].compact )
|
||||
x << t.to_i
|
||||
else
|
||||
y << data[:data][i]
|
||||
end
|
||||
}
|
||||
sort( x, y )
|
||||
data[:data] = [x,y]
|
||||
@data << data
|
||||
end
|
||||
|
||||
|
||||
protected
|
||||
|
||||
def min_x_value=(value)
|
||||
arr = ParseDate.parsedate( value )
|
||||
@min_x_value = Time.local( *arr[0,6].compact ).to_i
|
||||
end
|
||||
|
||||
|
||||
def format x, y
|
||||
Time.at( x ).strftime( popup_format )
|
||||
end
|
||||
|
||||
def get_x_labels
|
||||
get_x_values.collect { |v| Time.at(v).strftime( x_label_format ) }
|
||||
end
|
||||
|
||||
private
|
||||
def get_x_values
|
||||
rv = []
|
||||
min, max, scale_division = x_range
|
||||
if timescale_divisions
|
||||
timescale_divisions =~ /(\d+) ?(days|weeks|months|years|hours|minutes|seconds)?/
|
||||
division_units = $2 ? $2 : "days"
|
||||
amount = $1.to_i
|
||||
if amount
|
||||
step = nil
|
||||
case division_units
|
||||
when "months"
|
||||
cur = min
|
||||
while cur < max
|
||||
rv << cur
|
||||
arr = Time.at( cur ).to_a
|
||||
arr[4] += amount
|
||||
if arr[4] > 12
|
||||
arr[5] += (arr[4] / 12).to_i
|
||||
arr[4] = (arr[4] % 12)
|
||||
end
|
||||
cur = Time.local(*arr).to_i
|
||||
end
|
||||
when "years"
|
||||
cur = min
|
||||
while cur < max
|
||||
rv << cur
|
||||
arr = Time.at( cur ).to_a
|
||||
arr[5] += amount
|
||||
cur = Time.local(*arr).to_i
|
||||
end
|
||||
when "weeks"
|
||||
step = 7 * 24 * 60 * 60 * amount
|
||||
when "days"
|
||||
step = 24 * 60 * 60 * amount
|
||||
when "hours"
|
||||
step = 60 * 60 * amount
|
||||
when "minutes"
|
||||
step = 60 * amount
|
||||
when "seconds"
|
||||
step = amount
|
||||
end
|
||||
min.step( max, step ) {|v| rv << v} if step
|
||||
|
||||
return rv
|
||||
end
|
||||
end
|
||||
min.step( max, scale_division ) {|v| rv << v}
|
||||
return rv
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
@@ -0,0 +1,57 @@
|
||||
SVG::Graph is copyrighted free software by Sean Russell <ser@germane-software.com>.
|
||||
You can redistribute it and/or modify it under either the terms of the GPL
|
||||
(see GPL.txt file), or the conditions below:
|
||||
|
||||
1. You may make and give away verbatim copies of the source form of the
|
||||
software without restriction, provided that you duplicate all of the
|
||||
original copyright notices and associated disclaimers.
|
||||
|
||||
2. You may modify your copy of the software in any way, provided that
|
||||
you do at least ONE of the following:
|
||||
|
||||
a) place your modifications in the Public Domain or otherwise
|
||||
make them Freely Available, such as by posting said
|
||||
modifications to Usenet or an equivalent medium, or by allowing
|
||||
the author to include your modifications in the software.
|
||||
|
||||
b) use the modified software only within your corporation or
|
||||
organization.
|
||||
|
||||
c) rename any non-standard executables so the names do not conflict
|
||||
with standard executables, which must also be provided.
|
||||
|
||||
d) make other distribution arrangements with the author.
|
||||
|
||||
3. You may distribute the software in object code or executable
|
||||
form, provided that you do at least ONE of the following:
|
||||
|
||||
a) distribute the executables and library files of the software,
|
||||
together with instructions (in the manual page or equivalent)
|
||||
on where to get the original distribution.
|
||||
|
||||
b) accompany the distribution with the machine-readable source of
|
||||
the software.
|
||||
|
||||
c) give non-standard executables non-standard names, with
|
||||
instructions on where to get the original software distribution.
|
||||
|
||||
d) make other distribution arrangements with the author.
|
||||
|
||||
4. You may modify and include the part of the software into any other
|
||||
software (possibly commercial). But some files in the distribution
|
||||
are not written by the author, so that they are not under this terms.
|
||||
|
||||
All files of this sort are located under the contrib/ directory.
|
||||
See each file for the copying condition.
|
||||
|
||||
5. The scripts and library files supplied as input to or produced as
|
||||
output from the software do not automatically fall under the
|
||||
copyright of the software, but belong to whomever generated them,
|
||||
and may be sold commercially, and may be aggregated with this
|
||||
software.
|
||||
|
||||
6. THIS SOFTWARE IS PROVIDED "AS IS" AND WITHOUT ANY EXPRESS OR
|
||||
IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED
|
||||
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
|
||||
PURPOSE.
|
||||
|
||||
@@ -0,0 +1,41 @@
|
||||
# redMine - project management software
|
||||
# Copyright (C) 2006-2008 Jean-Philippe Lang
|
||||
#
|
||||
# This program is free software; you can redistribute it and/or
|
||||
# modify it under the terms of the GNU General Public License
|
||||
# as published by the Free Software Foundation; either version 2
|
||||
# of the License, or (at your option) any later version.
|
||||
#
|
||||
# This program is distributed in the hope that it will be useful,
|
||||
# but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
# GNU General Public License for more details.
|
||||
#
|
||||
# You should have received a copy of the GNU General Public License
|
||||
# along with this program; if not, write to the Free Software
|
||||
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
|
||||
|
||||
class ARCondition
|
||||
attr_reader :conditions
|
||||
|
||||
def initialize(condition=nil)
|
||||
@conditions = ['1=1']
|
||||
add(condition) if condition
|
||||
end
|
||||
|
||||
def add(condition)
|
||||
if condition.is_a?(Array)
|
||||
@conditions.first << " AND (#{condition.first})"
|
||||
@conditions += condition[1..-1]
|
||||
elsif condition.is_a?(String)
|
||||
@conditions.first << " AND (#{condition})"
|
||||
else
|
||||
raise "Unsupported #{condition.class} condition: #{condition}"
|
||||
end
|
||||
self
|
||||
end
|
||||
|
||||
def <<(condition)
|
||||
add(condition)
|
||||
end
|
||||
end
|
||||
@@ -0,0 +1,280 @@
|
||||
class Diff
|
||||
|
||||
VERSION = 0.3
|
||||
|
||||
def Diff.lcs(a, b)
|
||||
astart = 0
|
||||
bstart = 0
|
||||
afinish = a.length-1
|
||||
bfinish = b.length-1
|
||||
mvector = []
|
||||
|
||||
# First we prune off any common elements at the beginning
|
||||
while (astart <= afinish && bstart <= afinish && a[astart] == b[bstart])
|
||||
mvector[astart] = bstart
|
||||
astart += 1
|
||||
bstart += 1
|
||||
end
|
||||
|
||||
# now the end
|
||||
while (astart <= afinish && bstart <= bfinish && a[afinish] == b[bfinish])
|
||||
mvector[afinish] = bfinish
|
||||
afinish -= 1
|
||||
bfinish -= 1
|
||||
end
|
||||
|
||||
bmatches = b.reverse_hash(bstart..bfinish)
|
||||
thresh = []
|
||||
links = []
|
||||
|
||||
(astart..afinish).each { |aindex|
|
||||
aelem = a[aindex]
|
||||
next unless bmatches.has_key? aelem
|
||||
k = nil
|
||||
bmatches[aelem].reverse.each { |bindex|
|
||||
if k && (thresh[k] > bindex) && (thresh[k-1] < bindex)
|
||||
thresh[k] = bindex
|
||||
else
|
||||
k = thresh.replacenextlarger(bindex, k)
|
||||
end
|
||||
links[k] = [ (k==0) ? nil : links[k-1], aindex, bindex ] if k
|
||||
}
|
||||
}
|
||||
|
||||
if !thresh.empty?
|
||||
link = links[thresh.length-1]
|
||||
while link
|
||||
mvector[link[1]] = link[2]
|
||||
link = link[0]
|
||||
end
|
||||
end
|
||||
|
||||
return mvector
|
||||
end
|
||||
|
||||
def makediff(a, b)
|
||||
mvector = Diff.lcs(a, b)
|
||||
ai = bi = 0
|
||||
while ai < mvector.length
|
||||
bline = mvector[ai]
|
||||
if bline
|
||||
while bi < bline
|
||||
discardb(bi, b[bi])
|
||||
bi += 1
|
||||
end
|
||||
match(ai, bi)
|
||||
bi += 1
|
||||
else
|
||||
discarda(ai, a[ai])
|
||||
end
|
||||
ai += 1
|
||||
end
|
||||
while ai < a.length
|
||||
discarda(ai, a[ai])
|
||||
ai += 1
|
||||
end
|
||||
while bi < b.length
|
||||
discardb(bi, b[bi])
|
||||
bi += 1
|
||||
end
|
||||
match(ai, bi)
|
||||
1
|
||||
end
|
||||
|
||||
def compactdiffs
|
||||
diffs = []
|
||||
@diffs.each { |df|
|
||||
i = 0
|
||||
curdiff = []
|
||||
while i < df.length
|
||||
whot = df[i][0]
|
||||
s = @isstring ? df[i][2].chr : [df[i][2]]
|
||||
p = df[i][1]
|
||||
last = df[i][1]
|
||||
i += 1
|
||||
while df[i] && df[i][0] == whot && df[i][1] == last+1
|
||||
s << df[i][2]
|
||||
last = df[i][1]
|
||||
i += 1
|
||||
end
|
||||
curdiff.push [whot, p, s]
|
||||
end
|
||||
diffs.push curdiff
|
||||
}
|
||||
return diffs
|
||||
end
|
||||
|
||||
attr_reader :diffs, :difftype
|
||||
|
||||
def initialize(diffs_or_a, b = nil, isstring = nil)
|
||||
if b.nil?
|
||||
@diffs = diffs_or_a
|
||||
@isstring = isstring
|
||||
else
|
||||
@diffs = []
|
||||
@curdiffs = []
|
||||
makediff(diffs_or_a, b)
|
||||
@difftype = diffs_or_a.class
|
||||
end
|
||||
end
|
||||
|
||||
def match(ai, bi)
|
||||
@diffs.push @curdiffs unless @curdiffs.empty?
|
||||
@curdiffs = []
|
||||
end
|
||||
|
||||
def discarda(i, elem)
|
||||
@curdiffs.push ['-', i, elem]
|
||||
end
|
||||
|
||||
def discardb(i, elem)
|
||||
@curdiffs.push ['+', i, elem]
|
||||
end
|
||||
|
||||
def compact
|
||||
return Diff.new(compactdiffs)
|
||||
end
|
||||
|
||||
def compact!
|
||||
@diffs = compactdiffs
|
||||
end
|
||||
|
||||
def inspect
|
||||
@diffs.inspect
|
||||
end
|
||||
|
||||
end
|
||||
|
||||
module Diffable
|
||||
def diff(b)
|
||||
Diff.new(self, b)
|
||||
end
|
||||
|
||||
# Create a hash that maps elements of the array to arrays of indices
|
||||
# where the elements are found.
|
||||
|
||||
def reverse_hash(range = (0...self.length))
|
||||
revmap = {}
|
||||
range.each { |i|
|
||||
elem = self[i]
|
||||
if revmap.has_key? elem
|
||||
revmap[elem].push i
|
||||
else
|
||||
revmap[elem] = [i]
|
||||
end
|
||||
}
|
||||
return revmap
|
||||
end
|
||||
|
||||
def replacenextlarger(value, high = nil)
|
||||
high ||= self.length
|
||||
if self.empty? || value > self[-1]
|
||||
push value
|
||||
return high
|
||||
end
|
||||
# binary search for replacement point
|
||||
low = 0
|
||||
while low < high
|
||||
index = (high+low)/2
|
||||
found = self[index]
|
||||
return nil if value == found
|
||||
if value > found
|
||||
low = index + 1
|
||||
else
|
||||
high = index
|
||||
end
|
||||
end
|
||||
|
||||
self[low] = value
|
||||
# $stderr << "replace #{value} : 0/#{low}/#{init_high} (#{steps} steps) (#{init_high-low} off )\n"
|
||||
# $stderr.puts self.inspect
|
||||
#gets
|
||||
#p length - low
|
||||
return low
|
||||
end
|
||||
|
||||
def patch(diff)
|
||||
newary = nil
|
||||
if diff.difftype == String
|
||||
newary = diff.difftype.new('')
|
||||
else
|
||||
newary = diff.difftype.new
|
||||
end
|
||||
ai = 0
|
||||
bi = 0
|
||||
diff.diffs.each { |d|
|
||||
d.each { |mod|
|
||||
case mod[0]
|
||||
when '-'
|
||||
while ai < mod[1]
|
||||
newary << self[ai]
|
||||
ai += 1
|
||||
bi += 1
|
||||
end
|
||||
ai += 1
|
||||
when '+'
|
||||
while bi < mod[1]
|
||||
newary << self[ai]
|
||||
ai += 1
|
||||
bi += 1
|
||||
end
|
||||
newary << mod[2]
|
||||
bi += 1
|
||||
else
|
||||
raise "Unknown diff action"
|
||||
end
|
||||
}
|
||||
}
|
||||
while ai < self.length
|
||||
newary << self[ai]
|
||||
ai += 1
|
||||
bi += 1
|
||||
end
|
||||
return newary
|
||||
end
|
||||
end
|
||||
|
||||
class Array
|
||||
include Diffable
|
||||
end
|
||||
|
||||
class String
|
||||
include Diffable
|
||||
end
|
||||
|
||||
=begin
|
||||
= Diff
|
||||
(({diff.rb})) - computes the differences between two arrays or
|
||||
strings. Copyright (C) 2001 Lars Christensen
|
||||
|
||||
== Synopsis
|
||||
|
||||
diff = Diff.new(a, b)
|
||||
b = a.patch(diff)
|
||||
|
||||
== Class Diff
|
||||
=== Class Methods
|
||||
--- Diff.new(a, b)
|
||||
--- a.diff(b)
|
||||
Creates a Diff object which represent the differences between
|
||||
((|a|)) and ((|b|)). ((|a|)) and ((|b|)) can be either be arrays
|
||||
of any objects, strings, or object of any class that include
|
||||
module ((|Diffable|))
|
||||
|
||||
== Module Diffable
|
||||
The module ((|Diffable|)) is intended to be included in any class for
|
||||
which differences are to be computed. Diffable is included into String
|
||||
and Array when (({diff.rb})) is (({require}))'d.
|
||||
|
||||
Classes including Diffable should implement (({[]})) to get element at
|
||||
integer indices, (({<<})) to append elements to the object and
|
||||
(({ClassName#new})) should accept 0 arguments to create a new empty
|
||||
object.
|
||||
|
||||
=== Instance Methods
|
||||
--- Diffable#patch(diff)
|
||||
Applies the differences from ((|diff|)) to the object ((|obj|))
|
||||
and return the result. ((|obj|)) is not changed. ((|obj|)) and
|
||||
can be either an array or a string, but must match the object
|
||||
from which the ((|diff|)) was created.
|
||||
=end
|
||||
@@ -0,0 +1,18 @@
|
||||
Description:
|
||||
The plugin generator creates stubs for a new Redmine plugin.
|
||||
|
||||
Example:
|
||||
./script/generate redmine_plugin meetings
|
||||
create vendor/plugins/redmine_meetings/app/controllers
|
||||
create vendor/plugins/redmine_meetings/app/helpers
|
||||
create vendor/plugins/redmine_meetings/app/models
|
||||
create vendor/plugins/redmine_meetings/app/views
|
||||
create vendor/plugins/redmine_meetings/db/migrate
|
||||
create vendor/plugins/redmine_meetings/lib/tasks
|
||||
create vendor/plugins/redmine_meetings/assets/images
|
||||
create vendor/plugins/redmine_meetings/assets/javascripts
|
||||
create vendor/plugins/redmine_meetings/assets/stylesheets
|
||||
create vendor/plugins/redmine_meetings/lang
|
||||
create vendor/plugins/redmine_meetings/README
|
||||
create vendor/plugins/redmine_meetings/init.rb
|
||||
create vendor/plugins/redmine_meetings/lang/en.yml
|
||||
@@ -0,0 +1,31 @@
|
||||
class RedminePluginGenerator < Rails::Generator::NamedBase
|
||||
attr_reader :plugin_path, :plugin_name, :plugin_pretty_name
|
||||
|
||||
def initialize(runtime_args, runtime_options = {})
|
||||
super
|
||||
@plugin_name = "redmine_#{file_name.underscore}"
|
||||
@plugin_pretty_name = plugin_name.titleize
|
||||
@plugin_path = "vendor/plugins/#{plugin_name}"
|
||||
end
|
||||
|
||||
def manifest
|
||||
record do |m|
|
||||
m.directory "#{plugin_path}/app/controllers"
|
||||
m.directory "#{plugin_path}/app/helpers"
|
||||
m.directory "#{plugin_path}/app/models"
|
||||
m.directory "#{plugin_path}/app/views"
|
||||
m.directory "#{plugin_path}/db/migrate"
|
||||
m.directory "#{plugin_path}/lib/tasks"
|
||||
m.directory "#{plugin_path}/assets/images"
|
||||
m.directory "#{plugin_path}/assets/javascripts"
|
||||
m.directory "#{plugin_path}/assets/stylesheets"
|
||||
m.directory "#{plugin_path}/lang"
|
||||
m.directory "#{plugin_path}/test"
|
||||
|
||||
m.template 'README.rdoc', "#{plugin_path}/README.rdoc"
|
||||
m.template 'init.rb.erb', "#{plugin_path}/init.rb"
|
||||
m.template 'en.yml', "#{plugin_path}/lang/en.yml"
|
||||
m.template 'test_helper.rb.erb', "#{plugin_path}/test/test_helper.rb"
|
||||
end
|
||||
end
|
||||
end
|
||||
@@ -0,0 +1,3 @@
|
||||
= <%= file_name %>
|
||||
|
||||
Description goes here
|
||||
@@ -0,0 +1,2 @@
|
||||
# English strings go here
|
||||
my_label: "My label"
|
||||
@@ -0,0 +1,8 @@
|
||||
require 'redmine'
|
||||
|
||||
Redmine::Plugin.register :<%= plugin_name %> do
|
||||
name '<%= plugin_pretty_name %> plugin'
|
||||
author 'Author name'
|
||||
description 'This is a plugin for Redmine'
|
||||
version '0.0.1'
|
||||
end
|
||||
@@ -0,0 +1,5 @@
|
||||
# Load the normal Rails helper
|
||||
require File.expand_path(File.dirname(__FILE__) + '/../../../../test/test_helper')
|
||||
|
||||
# Ensure that we are using the temporary fixture path
|
||||
Engines::Testing.set_fixture_path
|
||||
@@ -0,0 +1,5 @@
|
||||
Description:
|
||||
Generates a plugin controller.
|
||||
|
||||
Example:
|
||||
./script/generate redmine_plugin_controller MyPlugin Pools index show vote
|
||||
+54
@@ -0,0 +1,54 @@
|
||||
require 'rails_generator/base'
|
||||
require 'rails_generator/generators/components/controller/controller_generator'
|
||||
|
||||
class RedminePluginControllerGenerator < ControllerGenerator
|
||||
attr_reader :plugin_path, :plugin_name, :plugin_pretty_name
|
||||
|
||||
def initialize(runtime_args, runtime_options = {})
|
||||
runtime_args = runtime_args.dup
|
||||
@plugin_name = "redmine_" + runtime_args.shift.underscore
|
||||
@plugin_pretty_name = plugin_name.titleize
|
||||
@plugin_path = "vendor/plugins/#{plugin_name}"
|
||||
super(runtime_args, runtime_options)
|
||||
end
|
||||
|
||||
def destination_root
|
||||
File.join(RAILS_ROOT, plugin_path)
|
||||
end
|
||||
|
||||
def manifest
|
||||
record do |m|
|
||||
# Check for class naming collisions.
|
||||
m.class_collisions class_path, "#{class_name}Controller", "#{class_name}ControllerTest", "#{class_name}Helper"
|
||||
|
||||
# Controller, helper, views, and test directories.
|
||||
m.directory File.join('app/controllers', class_path)
|
||||
m.directory File.join('app/helpers', class_path)
|
||||
m.directory File.join('app/views', class_path, file_name)
|
||||
m.directory File.join('test/functional', class_path)
|
||||
|
||||
# Controller class, functional test, and helper class.
|
||||
m.template 'controller.rb.erb',
|
||||
File.join('app/controllers',
|
||||
class_path,
|
||||
"#{file_name}_controller.rb")
|
||||
|
||||
m.template 'functional_test.rb.erb',
|
||||
File.join('test/functional',
|
||||
class_path,
|
||||
"#{file_name}_controller_test.rb")
|
||||
|
||||
m.template 'helper.rb.erb',
|
||||
File.join('app/helpers',
|
||||
class_path,
|
||||
"#{file_name}_helper.rb")
|
||||
|
||||
# View template for each action.
|
||||
actions.each do |action|
|
||||
path = File.join('app/views', class_path, file_name, "#{action}.html.erb")
|
||||
m.template 'view.html.erb', path,
|
||||
:assigns => { :action => action, :path => path }
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
@@ -0,0 +1,7 @@
|
||||
class <%= class_name %>Controller < ApplicationController
|
||||
<% actions.each do |action| -%>
|
||||
|
||||
def <%= action %>
|
||||
end
|
||||
<% end -%>
|
||||
end
|
||||
+8
@@ -0,0 +1,8 @@
|
||||
require File.dirname(__FILE__) + '/../test_helper'
|
||||
|
||||
class <%= class_name %>ControllerTest < ActionController::TestCase
|
||||
# Replace this with your real tests.
|
||||
def test_truth
|
||||
assert true
|
||||
end
|
||||
end
|
||||
@@ -0,0 +1,2 @@
|
||||
module <%= class_name %>Helper
|
||||
end
|
||||
@@ -0,0 +1 @@
|
||||
<h2><%= class_name %>#<%= action %></h2>
|
||||
@@ -0,0 +1,5 @@
|
||||
Description:
|
||||
Generates a plugin model.
|
||||
|
||||
Examples:
|
||||
./script/generate redmine_plugin_model MyPlugin pool title:string question:text
|
||||
@@ -0,0 +1,44 @@
|
||||
require 'rails_generator/base'
|
||||
require 'rails_generator/generators/components/model/model_generator'
|
||||
|
||||
class RedminePluginModelGenerator < ModelGenerator
|
||||
attr_accessor :plugin_path, :plugin_name, :plugin_pretty_name
|
||||
|
||||
def initialize(runtime_args, runtime_options = {})
|
||||
runtime_args = runtime_args.dup
|
||||
@plugin_name = "redmine_" + runtime_args.shift.underscore
|
||||
@plugin_pretty_name = plugin_name.titleize
|
||||
@plugin_path = "vendor/plugins/#{plugin_name}"
|
||||
super(runtime_args, runtime_options)
|
||||
end
|
||||
|
||||
def destination_root
|
||||
File.join(RAILS_ROOT, plugin_path)
|
||||
end
|
||||
|
||||
def manifest
|
||||
record do |m|
|
||||
# Check for class naming collisions.
|
||||
m.class_collisions class_path, class_name, "#{class_name}Test"
|
||||
|
||||
# Model, test, and fixture directories.
|
||||
m.directory File.join('app/models', class_path)
|
||||
m.directory File.join('test/unit', class_path)
|
||||
m.directory File.join('test/fixtures', class_path)
|
||||
|
||||
# Model class, unit test, and fixtures.
|
||||
m.template 'model.rb.erb', File.join('app/models', class_path, "#{file_name}.rb")
|
||||
m.template 'unit_test.rb.erb', File.join('test/unit', class_path, "#{file_name}_test.rb")
|
||||
|
||||
unless options[:skip_fixture]
|
||||
m.template 'fixtures.yml', File.join('test/fixtures', "#{table_name}.yml")
|
||||
end
|
||||
|
||||
unless options[:skip_migration]
|
||||
m.migration_template 'migration.rb.erb', 'db/migrate', :assigns => {
|
||||
:migration_name => "Create#{class_name.pluralize.gsub(/::/, '')}"
|
||||
}, :migration_file_name => "create_#{file_path.gsub(/\//, '_').pluralize}"
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
@@ -0,0 +1,11 @@
|
||||
# Read about fixtures at http://ar.rubyonrails.org/classes/Fixtures.html
|
||||
one:
|
||||
id: 1
|
||||
<% for attribute in attributes -%>
|
||||
<%= attribute.name %>: <%= attribute.default %>
|
||||
<% end -%>
|
||||
two:
|
||||
id: 2
|
||||
<% for attribute in attributes -%>
|
||||
<%= attribute.name %>: <%= attribute.default %>
|
||||
<% end -%>
|
||||
@@ -0,0 +1,13 @@
|
||||
class <%= migration_name %> < ActiveRecord::Migration
|
||||
def self.up
|
||||
create_table :<%= table_name %> do |t|
|
||||
<% for attribute in attributes -%>
|
||||
t.column :<%= attribute.name %>, :<%= attribute.type %>
|
||||
<% end -%>
|
||||
end
|
||||
end
|
||||
|
||||
def self.down
|
||||
drop_table :<%= table_name %>
|
||||
end
|
||||
end
|
||||
@@ -0,0 +1,2 @@
|
||||
class <%= class_name %> < ActiveRecord::Base
|
||||
end
|
||||
@@ -0,0 +1,10 @@
|
||||
require File.dirname(__FILE__) + '/../test_helper'
|
||||
|
||||
class <%= class_name %>Test < Test::Unit::TestCase
|
||||
fixtures :<%= table_name %>
|
||||
|
||||
# Replace this with your real tests.
|
||||
def test_truth
|
||||
assert true
|
||||
end
|
||||
end
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,163 @@
|
||||
require 'redmine/access_control'
|
||||
require 'redmine/menu_manager'
|
||||
require 'redmine/activity'
|
||||
require 'redmine/mime_type'
|
||||
require 'redmine/core_ext'
|
||||
require 'redmine/themes'
|
||||
require 'redmine/hook'
|
||||
require 'redmine/plugin'
|
||||
require 'redmine/wiki_formatting'
|
||||
|
||||
begin
|
||||
require_library_or_gem 'RMagick' unless Object.const_defined?(:Magick)
|
||||
rescue LoadError
|
||||
# RMagick is not available
|
||||
end
|
||||
|
||||
REDMINE_SUPPORTED_SCM = %w( Subversion Darcs Mercurial Cvs Bazaar Git Filesystem )
|
||||
|
||||
# Permissions
|
||||
Redmine::AccessControl.map do |map|
|
||||
map.permission :view_project, {:projects => [:show, :activity]}, :public => true
|
||||
map.permission :search_project, {:search => :index}, :public => true
|
||||
map.permission :edit_project, {:projects => [:settings, :edit]}, :require => :member
|
||||
map.permission :select_project_modules, {:projects => :modules}, :require => :member
|
||||
map.permission :manage_members, {:projects => :settings, :members => [:new, :edit, :destroy]}, :require => :member
|
||||
map.permission :manage_versions, {:projects => [:settings, :add_version], :versions => [:edit, :destroy]}, :require => :member
|
||||
|
||||
map.project_module :issue_tracking do |map|
|
||||
# Issue categories
|
||||
map.permission :manage_categories, {:projects => [:settings, :add_issue_category], :issue_categories => [:edit, :destroy]}, :require => :member
|
||||
# Issues
|
||||
map.permission :view_issues, {:projects => [:changelog, :roadmap],
|
||||
:issues => [:index, :changes, :show, :context_menu],
|
||||
:versions => [:show, :status_by],
|
||||
:queries => :index,
|
||||
:reports => :issue_report}, :public => true
|
||||
map.permission :add_issues, {:issues => :new}
|
||||
map.permission :edit_issues, {:issues => [:edit, :reply, :bulk_edit]}
|
||||
map.permission :manage_issue_relations, {:issue_relations => [:new, :destroy]}
|
||||
map.permission :add_issue_notes, {:issues => [:edit, :reply]}
|
||||
map.permission :edit_issue_notes, {:journals => :edit}, :require => :loggedin
|
||||
map.permission :edit_own_issue_notes, {:journals => :edit}, :require => :loggedin
|
||||
map.permission :move_issues, {:issues => :move}, :require => :loggedin
|
||||
map.permission :delete_issues, {:issues => :destroy}, :require => :member
|
||||
# Queries
|
||||
map.permission :manage_public_queries, {:queries => [:new, :edit, :destroy]}, :require => :member
|
||||
map.permission :save_queries, {:queries => [:new, :edit, :destroy]}, :require => :loggedin
|
||||
# Gantt & calendar
|
||||
map.permission :view_gantt, :issues => :gantt
|
||||
map.permission :view_calendar, :issues => :calendar
|
||||
# Watchers
|
||||
map.permission :view_issue_watchers, {}
|
||||
map.permission :add_issue_watchers, {:watchers => :new}
|
||||
end
|
||||
|
||||
map.project_module :time_tracking do |map|
|
||||
map.permission :log_time, {:timelog => :edit}, :require => :loggedin
|
||||
map.permission :view_time_entries, :timelog => [:details, :report]
|
||||
map.permission :edit_time_entries, {:timelog => [:edit, :destroy]}, :require => :member
|
||||
map.permission :edit_own_time_entries, {:timelog => [:edit, :destroy]}, :require => :loggedin
|
||||
end
|
||||
|
||||
map.project_module :news do |map|
|
||||
map.permission :manage_news, {:news => [:new, :edit, :destroy, :destroy_comment]}, :require => :member
|
||||
map.permission :view_news, {:news => [:index, :show]}, :public => true
|
||||
map.permission :comment_news, {:news => :add_comment}
|
||||
end
|
||||
|
||||
map.project_module :documents do |map|
|
||||
map.permission :manage_documents, {:documents => [:new, :edit, :destroy, :add_attachment]}, :require => :loggedin
|
||||
map.permission :view_documents, :documents => [:index, :show, :download]
|
||||
end
|
||||
|
||||
map.project_module :files do |map|
|
||||
map.permission :manage_files, {:projects => :add_file}, :require => :loggedin
|
||||
map.permission :view_files, :projects => :list_files, :versions => :download
|
||||
end
|
||||
|
||||
map.project_module :wiki do |map|
|
||||
map.permission :manage_wiki, {:wikis => [:edit, :destroy]}, :require => :member
|
||||
map.permission :rename_wiki_pages, {:wiki => :rename}, :require => :member
|
||||
map.permission :delete_wiki_pages, {:wiki => :destroy}, :require => :member
|
||||
map.permission :view_wiki_pages, :wiki => [:index, :special]
|
||||
map.permission :view_wiki_edits, :wiki => [:history, :diff, :annotate]
|
||||
map.permission :edit_wiki_pages, :wiki => [:edit, :preview, :add_attachment]
|
||||
map.permission :delete_wiki_pages_attachments, {}
|
||||
map.permission :protect_wiki_pages, {:wiki => :protect}, :require => :member
|
||||
end
|
||||
|
||||
map.project_module :repository do |map|
|
||||
map.permission :manage_repository, {:repositories => [:edit, :committers, :destroy]}, :require => :member
|
||||
map.permission :browse_repository, :repositories => [:show, :browse, :entry, :annotate, :changes, :diff, :stats, :graph]
|
||||
map.permission :view_changesets, :repositories => [:show, :revisions, :revision]
|
||||
map.permission :commit_access, {}
|
||||
end
|
||||
|
||||
map.project_module :boards do |map|
|
||||
map.permission :manage_boards, {:boards => [:new, :edit, :destroy]}, :require => :member
|
||||
map.permission :view_messages, {:boards => [:index, :show], :messages => [:show]}, :public => true
|
||||
map.permission :add_messages, {:messages => [:new, :reply, :quote]}
|
||||
map.permission :edit_messages, {:messages => :edit}, :require => :member
|
||||
map.permission :edit_own_messages, {:messages => :edit}, :require => :loggedin
|
||||
map.permission :delete_messages, {:messages => :destroy}, :require => :member
|
||||
map.permission :delete_own_messages, {:messages => :destroy}, :require => :loggedin
|
||||
end
|
||||
end
|
||||
|
||||
Redmine::MenuManager.map :top_menu do |menu|
|
||||
menu.push :home, :home_path
|
||||
menu.push :my_page, { :controller => 'my', :action => 'page' }, :if => Proc.new { User.current.logged? }
|
||||
menu.push :projects, { :controller => 'projects', :action => 'index' }, :caption => :label_project_plural
|
||||
menu.push :administration, { :controller => 'admin', :action => 'index' }, :if => Proc.new { User.current.admin? }, :last => true
|
||||
menu.push :help, Redmine::Info.help_url, :last => true
|
||||
end
|
||||
|
||||
Redmine::MenuManager.map :account_menu do |menu|
|
||||
menu.push :login, :signin_path, :if => Proc.new { !User.current.logged? }
|
||||
menu.push :register, { :controller => 'account', :action => 'register' }, :if => Proc.new { !User.current.logged? && Setting.self_registration? }
|
||||
menu.push :my_account, { :controller => 'my', :action => 'account' }, :if => Proc.new { User.current.logged? }
|
||||
menu.push :logout, :signout_path, :if => Proc.new { User.current.logged? }
|
||||
end
|
||||
|
||||
Redmine::MenuManager.map :application_menu do |menu|
|
||||
# Empty
|
||||
end
|
||||
|
||||
Redmine::MenuManager.map :admin_menu do |menu|
|
||||
# Empty
|
||||
end
|
||||
|
||||
Redmine::MenuManager.map :project_menu do |menu|
|
||||
menu.push :overview, { :controller => 'projects', :action => 'show' }
|
||||
menu.push :activity, { :controller => 'projects', :action => 'activity' }
|
||||
menu.push :roadmap, { :controller => 'projects', :action => 'roadmap' },
|
||||
:if => Proc.new { |p| p.versions.any? }
|
||||
menu.push :issues, { :controller => 'issues', :action => 'index' }, :param => :project_id, :caption => :label_issue_plural
|
||||
menu.push :new_issue, { :controller => 'issues', :action => 'new' }, :param => :project_id, :caption => :label_issue_new,
|
||||
:html => { :accesskey => Redmine::AccessKeys.key_for(:new_issue) }
|
||||
menu.push :news, { :controller => 'news', :action => 'index' }, :param => :project_id, :caption => :label_news_plural
|
||||
menu.push :documents, { :controller => 'documents', :action => 'index' }, :param => :project_id, :caption => :label_document_plural
|
||||
menu.push :wiki, { :controller => 'wiki', :action => 'index', :page => nil },
|
||||
:if => Proc.new { |p| p.wiki && !p.wiki.new_record? }
|
||||
menu.push :boards, { :controller => 'boards', :action => 'index', :id => nil }, :param => :project_id,
|
||||
:if => Proc.new { |p| p.boards.any? }, :caption => :label_board_plural
|
||||
menu.push :files, { :controller => 'projects', :action => 'list_files' }, :caption => :label_attachment_plural
|
||||
menu.push :repository, { :controller => 'repositories', :action => 'show' },
|
||||
:if => Proc.new { |p| p.repository && !p.repository.new_record? }
|
||||
menu.push :settings, { :controller => 'projects', :action => 'settings' }, :last => true
|
||||
end
|
||||
|
||||
Redmine::Activity.map do |activity|
|
||||
activity.register :issues, :class_name => %w(Issue Journal)
|
||||
activity.register :changesets
|
||||
activity.register :news
|
||||
activity.register :documents, :class_name => %w(Document Attachment)
|
||||
activity.register :files, :class_name => 'Attachment'
|
||||
activity.register :wiki_edits, :class_name => 'WikiContent::Version', :default => false
|
||||
activity.register :messages, :default => false
|
||||
end
|
||||
|
||||
Redmine::WikiFormatting.map do |format|
|
||||
format.register :textile, Redmine::WikiFormatting::Textile::Formatter, Redmine::WikiFormatting::Textile::Helper
|
||||
end
|
||||
@@ -0,0 +1,120 @@
|
||||
# redMine - project management software
|
||||
# Copyright (C) 2006-2007 Jean-Philippe Lang
|
||||
#
|
||||
# This program is free software; you can redistribute it and/or
|
||||
# modify it under the terms of the GNU General Public License
|
||||
# as published by the Free Software Foundation; either version 2
|
||||
# of the License, or (at your option) any later version.
|
||||
#
|
||||
# This program is distributed in the hope that it will be useful,
|
||||
# but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
# GNU General Public License for more details.
|
||||
#
|
||||
# You should have received a copy of the GNU General Public License
|
||||
# along with this program; if not, write to the Free Software
|
||||
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
|
||||
|
||||
module Redmine
|
||||
module AccessControl
|
||||
|
||||
class << self
|
||||
def map
|
||||
mapper = Mapper.new
|
||||
yield mapper
|
||||
@permissions ||= []
|
||||
@permissions += mapper.mapped_permissions
|
||||
end
|
||||
|
||||
def permissions
|
||||
@permissions
|
||||
end
|
||||
|
||||
# Returns the permission of given name or nil if it wasn't found
|
||||
# Argument should be a symbol
|
||||
def permission(name)
|
||||
permissions.detect {|p| p.name == name}
|
||||
end
|
||||
|
||||
# Returns the actions that are allowed by the permission of given name
|
||||
def allowed_actions(permission_name)
|
||||
perm = permission(permission_name)
|
||||
perm ? perm.actions : []
|
||||
end
|
||||
|
||||
def public_permissions
|
||||
@public_permissions ||= @permissions.select {|p| p.public?}
|
||||
end
|
||||
|
||||
def members_only_permissions
|
||||
@members_only_permissions ||= @permissions.select {|p| p.require_member?}
|
||||
end
|
||||
|
||||
def loggedin_only_permissions
|
||||
@loggedin_only_permissions ||= @permissions.select {|p| p.require_loggedin?}
|
||||
end
|
||||
|
||||
def available_project_modules
|
||||
@available_project_modules ||= @permissions.collect(&:project_module).uniq.compact
|
||||
end
|
||||
|
||||
def modules_permissions(modules)
|
||||
@permissions.select {|p| p.project_module.nil? || modules.include?(p.project_module.to_s)}
|
||||
end
|
||||
end
|
||||
|
||||
class Mapper
|
||||
def initialize
|
||||
@project_module = nil
|
||||
end
|
||||
|
||||
def permission(name, hash, options={})
|
||||
@permissions ||= []
|
||||
options.merge!(:project_module => @project_module)
|
||||
@permissions << Permission.new(name, hash, options)
|
||||
end
|
||||
|
||||
def project_module(name, options={})
|
||||
@project_module = name
|
||||
yield self
|
||||
@project_module = nil
|
||||
end
|
||||
|
||||
def mapped_permissions
|
||||
@permissions
|
||||
end
|
||||
end
|
||||
|
||||
class Permission
|
||||
attr_reader :name, :actions, :project_module
|
||||
|
||||
def initialize(name, hash, options)
|
||||
@name = name
|
||||
@actions = []
|
||||
@public = options[:public] || false
|
||||
@require = options[:require]
|
||||
@project_module = options[:project_module]
|
||||
hash.each do |controller, actions|
|
||||
if actions.is_a? Array
|
||||
@actions << actions.collect {|action| "#{controller}/#{action}"}
|
||||
else
|
||||
@actions << "#{controller}/#{actions}"
|
||||
end
|
||||
end
|
||||
@actions.flatten!
|
||||
end
|
||||
|
||||
def public?
|
||||
@public
|
||||
end
|
||||
|
||||
def require_member?
|
||||
@require && @require == :member
|
||||
end
|
||||
|
||||
def require_loggedin?
|
||||
@require && (@require == :member || @require == :loggedin)
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
@@ -0,0 +1,31 @@
|
||||
# redMine - project management software
|
||||
# Copyright (C) 2006-2008 Jean-Philippe Lang
|
||||
#
|
||||
# This program is free software; you can redistribute it and/or
|
||||
# modify it under the terms of the GNU General Public License
|
||||
# as published by the Free Software Foundation; either version 2
|
||||
# of the License, or (at your option) any later version.
|
||||
#
|
||||
# This program is distributed in the hope that it will be useful,
|
||||
# but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
# GNU General Public License for more details.
|
||||
#
|
||||
# You should have received a copy of the GNU General Public License
|
||||
# along with this program; if not, write to the Free Software
|
||||
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
|
||||
|
||||
module Redmine
|
||||
module AccessKeys
|
||||
ACCESSKEYS = {:edit => 'e',
|
||||
:preview => 'r',
|
||||
:quick_search => 'f',
|
||||
:search => '4',
|
||||
:new_issue => '7'
|
||||
}.freeze unless const_defined?(:ACCESSKEYS)
|
||||
|
||||
def self.key_for(action)
|
||||
ACCESSKEYS[action]
|
||||
end
|
||||
end
|
||||
end
|
||||
@@ -0,0 +1,46 @@
|
||||
# Redmine - project management software
|
||||
# Copyright (C) 2006-2008 Jean-Philippe Lang
|
||||
#
|
||||
# This program is free software; you can redistribute it and/or
|
||||
# modify it under the terms of the GNU General Public License
|
||||
# as published by the Free Software Foundation; either version 2
|
||||
# of the License, or (at your option) any later version.
|
||||
#
|
||||
# This program is distributed in the hope that it will be useful,
|
||||
# but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
# GNU General Public License for more details.
|
||||
#
|
||||
# You should have received a copy of the GNU General Public License
|
||||
# along with this program; if not, write to the Free Software
|
||||
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
|
||||
|
||||
module Redmine
|
||||
module Activity
|
||||
|
||||
mattr_accessor :available_event_types, :default_event_types, :providers
|
||||
|
||||
@@available_event_types = []
|
||||
@@default_event_types = []
|
||||
@@providers = Hash.new {|h,k| h[k]=[] }
|
||||
|
||||
class << self
|
||||
def map(&block)
|
||||
yield self
|
||||
end
|
||||
|
||||
# Registers an activity provider
|
||||
def register(event_type, options={})
|
||||
options.assert_valid_keys(:class_name, :default)
|
||||
|
||||
event_type = event_type.to_s
|
||||
providers = options[:class_name] || event_type.classify
|
||||
providers = ([] << providers) unless providers.is_a?(Array)
|
||||
|
||||
@@available_event_types << event_type unless @@available_event_types.include?(event_type)
|
||||
@@default_event_types << event_type unless options[:default] == false
|
||||
@@providers[event_type] += providers
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
@@ -0,0 +1,93 @@
|
||||
# Redmine - project management software
|
||||
# Copyright (C) 2006-2008 Jean-Philippe Lang
|
||||
#
|
||||
# This program is free software; you can redistribute it and/or
|
||||
# modify it under the terms of the GNU General Public License
|
||||
# as published by the Free Software Foundation; either version 2
|
||||
# of the License, or (at your option) any later version.
|
||||
#
|
||||
# This program is distributed in the hope that it will be useful,
|
||||
# but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
# GNU General Public License for more details.
|
||||
#
|
||||
# You should have received a copy of the GNU General Public License
|
||||
# along with this program; if not, write to the Free Software
|
||||
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
|
||||
|
||||
module Redmine
|
||||
module Activity
|
||||
# Class used to retrieve activity events
|
||||
class Fetcher
|
||||
attr_reader :user, :project, :scope
|
||||
|
||||
# Needs to be unloaded in development mode
|
||||
@@constantized_providers = Hash.new {|h,k| h[k] = Redmine::Activity.providers[k].collect {|t| t.constantize } }
|
||||
|
||||
def initialize(user, options={})
|
||||
options.assert_valid_keys(:project, :with_subprojects, :author)
|
||||
@user = user
|
||||
@project = options[:project]
|
||||
@options = options
|
||||
|
||||
@scope = event_types
|
||||
end
|
||||
|
||||
# Returns an array of available event types
|
||||
def event_types
|
||||
return @event_types unless @event_types.nil?
|
||||
|
||||
@event_types = Redmine::Activity.available_event_types
|
||||
@event_types = @event_types.select {|o| @user.allowed_to?("view_#{o}".to_sym, @project)} if @project
|
||||
@event_types
|
||||
end
|
||||
|
||||
# Yields to filter the activity scope
|
||||
def scope_select(&block)
|
||||
@scope = @scope.select {|t| yield t }
|
||||
end
|
||||
|
||||
# Sets the scope
|
||||
# Argument can be :all, :default or an array of event types
|
||||
def scope=(s)
|
||||
case s
|
||||
when :all
|
||||
@scope = event_types
|
||||
when :default
|
||||
default_scope!
|
||||
else
|
||||
@scope = s & event_types
|
||||
end
|
||||
end
|
||||
|
||||
# Resets the scope to the default scope
|
||||
def default_scope!
|
||||
@scope = Redmine::Activity.default_event_types
|
||||
end
|
||||
|
||||
# Returns an array of events for the given date range
|
||||
def events(from = nil, to = nil, options={})
|
||||
e = []
|
||||
@options[:limit] = options[:limit]
|
||||
|
||||
@scope.each do |event_type|
|
||||
constantized_providers(event_type).each do |provider|
|
||||
e += provider.find_events(event_type, @user, from, to, @options)
|
||||
end
|
||||
end
|
||||
|
||||
if options[:limit]
|
||||
e.sort! {|a,b| b.event_date <=> a.event_date}
|
||||
e = e.slice(0, options[:limit])
|
||||
end
|
||||
e
|
||||
end
|
||||
|
||||
private
|
||||
|
||||
def constantized_providers(event_type)
|
||||
@@constantized_providers[event_type]
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
@@ -0,0 +1 @@
|
||||
Dir[File.dirname(__FILE__) + "/core_ext/*.rb"].each { |file| require(file) }
|
||||
@@ -0,0 +1,5 @@
|
||||
require File.dirname(__FILE__) + '/string/conversions'
|
||||
|
||||
class String #:nodoc:
|
||||
include Redmine::CoreExtensions::String::Conversions
|
||||
end
|
||||
@@ -0,0 +1,40 @@
|
||||
# redMine - project management software
|
||||
# Copyright (C) 2008 Jean-Philippe Lang
|
||||
#
|
||||
# This program is free software; you can redistribute it and/or
|
||||
# modify it under the terms of the GNU General Public License
|
||||
# as published by the Free Software Foundation; either version 2
|
||||
# of the License, or (at your option) any later version.
|
||||
#
|
||||
# This program is distributed in the hope that it will be useful,
|
||||
# but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
# GNU General Public License for more details.
|
||||
#
|
||||
# You should have received a copy of the GNU General Public License
|
||||
# along with this program; if not, write to the Free Software
|
||||
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
|
||||
|
||||
module Redmine #:nodoc:
|
||||
module CoreExtensions #:nodoc:
|
||||
module String #:nodoc:
|
||||
# Custom string conversions
|
||||
module Conversions
|
||||
# Parses hours format and returns a float
|
||||
def to_hours
|
||||
s = self.dup
|
||||
s.strip!
|
||||
unless s =~ %r{^[\d\.,]+$}
|
||||
# 2:30 => 2.5
|
||||
s.gsub!(%r{^(\d+):(\d+)$}) { $1.to_i + $2.to_i / 60.0 }
|
||||
# 2h30, 2h, 30m => 2.5, 2, 0.5
|
||||
s.gsub!(%r{^((\d+)\s*(h|hours?))?\s*((\d+)\s*(m|min)?)?$}) { |m| ($1 || $4) ? ($2.to_i + $5.to_i / 60.0) : m[0] }
|
||||
end
|
||||
# 2,5 => 2.5
|
||||
s.gsub!(',', '.')
|
||||
begin; Kernel.Float(s); rescue; nil; end
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
@@ -0,0 +1,176 @@
|
||||
# redMine - project management software
|
||||
# Copyright (C) 2006-2007 Jean-Philippe Lang
|
||||
#
|
||||
# This program is free software; you can redistribute it and/or
|
||||
# modify it under the terms of the GNU General Public License
|
||||
# as published by the Free Software Foundation; either version 2
|
||||
# of the License, or (at your option) any later version.
|
||||
#
|
||||
# This program is distributed in the hope that it will be useful,
|
||||
# but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
# GNU General Public License for more details.
|
||||
#
|
||||
# You should have received a copy of the GNU General Public License
|
||||
# along with this program; if not, write to the Free Software
|
||||
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
|
||||
|
||||
module Redmine
|
||||
module DefaultData
|
||||
class DataAlreadyLoaded < Exception; end
|
||||
|
||||
module Loader
|
||||
include GLoc
|
||||
|
||||
class << self
|
||||
# Returns true if no data is already loaded in the database
|
||||
# otherwise false
|
||||
def no_data?
|
||||
!Role.find(:first, :conditions => {:builtin => 0}) &&
|
||||
!Tracker.find(:first) &&
|
||||
!IssueStatus.find(:first) &&
|
||||
!Enumeration.find(:first)
|
||||
end
|
||||
|
||||
# Loads the default data
|
||||
# Raises a RecordNotSaved exception if something goes wrong
|
||||
def load(lang=nil)
|
||||
raise DataAlreadyLoaded.new("Some configuration data is already loaded.") unless no_data?
|
||||
set_language_if_valid(lang)
|
||||
|
||||
Role.transaction do
|
||||
# Roles
|
||||
manager = Role.create! :name => l(:default_role_manager),
|
||||
:position => 1
|
||||
manager.permissions = manager.setable_permissions.collect {|p| p.name}
|
||||
manager.save!
|
||||
|
||||
developper = Role.create! :name => l(:default_role_developper),
|
||||
:position => 2,
|
||||
:permissions => [:manage_versions,
|
||||
:manage_categories,
|
||||
:add_issues,
|
||||
:edit_issues,
|
||||
:manage_issue_relations,
|
||||
:add_issue_notes,
|
||||
:save_queries,
|
||||
:view_gantt,
|
||||
:view_calendar,
|
||||
:log_time,
|
||||
:view_time_entries,
|
||||
:comment_news,
|
||||
:view_documents,
|
||||
:view_wiki_pages,
|
||||
:view_wiki_edits,
|
||||
:edit_wiki_pages,
|
||||
:delete_wiki_pages,
|
||||
:add_messages,
|
||||
:edit_own_messages,
|
||||
:view_files,
|
||||
:manage_files,
|
||||
:browse_repository,
|
||||
:view_changesets,
|
||||
:commit_access]
|
||||
|
||||
reporter = Role.create! :name => l(:default_role_reporter),
|
||||
:position => 3,
|
||||
:permissions => [:add_issues,
|
||||
:add_issue_notes,
|
||||
:save_queries,
|
||||
:view_gantt,
|
||||
:view_calendar,
|
||||
:log_time,
|
||||
:view_time_entries,
|
||||
:comment_news,
|
||||
:view_documents,
|
||||
:view_wiki_pages,
|
||||
:view_wiki_edits,
|
||||
:add_messages,
|
||||
:edit_own_messages,
|
||||
:view_files,
|
||||
:browse_repository,
|
||||
:view_changesets]
|
||||
|
||||
Role.non_member.update_attribute :permissions, [:add_issues,
|
||||
:add_issue_notes,
|
||||
:save_queries,
|
||||
:view_gantt,
|
||||
:view_calendar,
|
||||
:view_time_entries,
|
||||
:comment_news,
|
||||
:view_documents,
|
||||
:view_wiki_pages,
|
||||
:view_wiki_edits,
|
||||
:add_messages,
|
||||
:view_files,
|
||||
:browse_repository,
|
||||
:view_changesets]
|
||||
|
||||
Role.anonymous.update_attribute :permissions, [:view_gantt,
|
||||
:view_calendar,
|
||||
:view_time_entries,
|
||||
:view_documents,
|
||||
:view_wiki_pages,
|
||||
:view_wiki_edits,
|
||||
:view_files,
|
||||
:browse_repository,
|
||||
:view_changesets]
|
||||
|
||||
# Trackers
|
||||
Tracker.create!(:name => l(:default_tracker_bug), :is_in_chlog => true, :is_in_roadmap => false, :position => 1)
|
||||
Tracker.create!(:name => l(:default_tracker_feature), :is_in_chlog => true, :is_in_roadmap => true, :position => 2)
|
||||
Tracker.create!(:name => l(:default_tracker_support), :is_in_chlog => false, :is_in_roadmap => false, :position => 3)
|
||||
|
||||
# Issue statuses
|
||||
new = IssueStatus.create!(:name => l(:default_issue_status_new), :is_closed => false, :is_default => true, :position => 1)
|
||||
assigned = IssueStatus.create!(:name => l(:default_issue_status_assigned), :is_closed => false, :is_default => false, :position => 2)
|
||||
resolved = IssueStatus.create!(:name => l(:default_issue_status_resolved), :is_closed => false, :is_default => false, :position => 3)
|
||||
feedback = IssueStatus.create!(:name => l(:default_issue_status_feedback), :is_closed => false, :is_default => false, :position => 4)
|
||||
closed = IssueStatus.create!(:name => l(:default_issue_status_closed), :is_closed => true, :is_default => false, :position => 5)
|
||||
rejected = IssueStatus.create!(:name => l(:default_issue_status_rejected), :is_closed => true, :is_default => false, :position => 6)
|
||||
|
||||
# Workflow
|
||||
Tracker.find(:all).each { |t|
|
||||
IssueStatus.find(:all).each { |os|
|
||||
IssueStatus.find(:all).each { |ns|
|
||||
Workflow.create!(:tracker_id => t.id, :role_id => manager.id, :old_status_id => os.id, :new_status_id => ns.id) unless os == ns
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Tracker.find(:all).each { |t|
|
||||
[new, assigned, resolved, feedback].each { |os|
|
||||
[assigned, resolved, feedback, closed].each { |ns|
|
||||
Workflow.create!(:tracker_id => t.id, :role_id => developper.id, :old_status_id => os.id, :new_status_id => ns.id) unless os == ns
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Tracker.find(:all).each { |t|
|
||||
[new, assigned, resolved, feedback].each { |os|
|
||||
[closed].each { |ns|
|
||||
Workflow.create!(:tracker_id => t.id, :role_id => reporter.id, :old_status_id => os.id, :new_status_id => ns.id) unless os == ns
|
||||
}
|
||||
}
|
||||
Workflow.create!(:tracker_id => t.id, :role_id => reporter.id, :old_status_id => resolved.id, :new_status_id => feedback.id)
|
||||
}
|
||||
|
||||
# Enumerations
|
||||
Enumeration.create!(:opt => "DCAT", :name => l(:default_doc_category_user), :position => 1)
|
||||
Enumeration.create!(:opt => "DCAT", :name => l(:default_doc_category_tech), :position => 2)
|
||||
|
||||
Enumeration.create!(:opt => "IPRI", :name => l(:default_priority_low), :position => 1)
|
||||
Enumeration.create!(:opt => "IPRI", :name => l(:default_priority_normal), :position => 2, :is_default => true)
|
||||
Enumeration.create!(:opt => "IPRI", :name => l(:default_priority_high), :position => 3)
|
||||
Enumeration.create!(:opt => "IPRI", :name => l(:default_priority_urgent), :position => 4)
|
||||
Enumeration.create!(:opt => "IPRI", :name => l(:default_priority_immediate), :position => 5)
|
||||
|
||||
Enumeration.create!(:opt => "ACTI", :name => l(:default_activity_design), :position => 1)
|
||||
Enumeration.create!(:opt => "ACTI", :name => l(:default_activity_development), :position => 2)
|
||||
end
|
||||
true
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
@@ -0,0 +1,76 @@
|
||||
# redMine - project management software
|
||||
# Copyright (C) 2006-2007 Jean-Philippe Lang
|
||||
#
|
||||
# This program is free software; you can redistribute it and/or
|
||||
# modify it under the terms of the GNU General Public License
|
||||
# as published by the Free Software Foundation; either version 2
|
||||
# of the License, or (at your option) any later version.
|
||||
#
|
||||
# This program is distributed in the hope that it will be useful,
|
||||
# but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
# GNU General Public License for more details.
|
||||
#
|
||||
# You should have received a copy of the GNU General Public License
|
||||
# along with this program; if not, write to the Free Software
|
||||
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
|
||||
|
||||
module Redmine
|
||||
module Helpers
|
||||
|
||||
# Simple class to compute the start and end dates of a calendar
|
||||
class Calendar
|
||||
include GLoc
|
||||
attr_reader :startdt, :enddt
|
||||
|
||||
def initialize(date, lang = current_language, period = :month)
|
||||
@date = date
|
||||
@events = []
|
||||
@ending_events_by_days = {}
|
||||
@starting_events_by_days = {}
|
||||
set_language lang
|
||||
case period
|
||||
when :month
|
||||
@startdt = Date.civil(date.year, date.month, 1)
|
||||
@enddt = (@startdt >> 1)-1
|
||||
# starts from the first day of the week
|
||||
@startdt = @startdt - (@startdt.cwday - first_wday)%7
|
||||
# ends on the last day of the week
|
||||
@enddt = @enddt + (last_wday - @enddt.cwday)%7
|
||||
when :week
|
||||
@startdt = date - (date.cwday - first_wday)%7
|
||||
@enddt = date + (last_wday - date.cwday)%7
|
||||
else
|
||||
raise 'Invalid period'
|
||||
end
|
||||
end
|
||||
|
||||
# Sets calendar events
|
||||
def events=(events)
|
||||
@events = events
|
||||
@ending_events_by_days = @events.group_by {|event| event.due_date}
|
||||
@starting_events_by_days = @events.group_by {|event| event.start_date}
|
||||
end
|
||||
|
||||
# Returns events for the given day
|
||||
def events_on(day)
|
||||
((@ending_events_by_days[day] || []) + (@starting_events_by_days[day] || [])).uniq
|
||||
end
|
||||
|
||||
# Calendar current month
|
||||
def month
|
||||
@date.month
|
||||
end
|
||||
|
||||
# Return the first day of week
|
||||
# 1 = Monday ... 7 = Sunday
|
||||
def first_wday
|
||||
@first_dow ||= (l(:general_first_day_of_week).to_i - 1)%7 + 1
|
||||
end
|
||||
|
||||
def last_wday
|
||||
@last_dow ||= (first_wday + 5)%7 + 1
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
@@ -0,0 +1,223 @@
|
||||
# Redmine - project management software
|
||||
# Copyright (C) 2006-2008 Jean-Philippe Lang
|
||||
#
|
||||
# This program is free software; you can redistribute it and/or
|
||||
# modify it under the terms of the GNU General Public License
|
||||
# as published by the Free Software Foundation; either version 2
|
||||
# of the License, or (at your option) any later version.
|
||||
#
|
||||
# This program is distributed in the hope that it will be useful,
|
||||
# but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
# GNU General Public License for more details.
|
||||
#
|
||||
# You should have received a copy of the GNU General Public License
|
||||
# along with this program; if not, write to the Free Software
|
||||
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
|
||||
|
||||
module Redmine
|
||||
module Helpers
|
||||
# Simple class to handle gantt chart data
|
||||
class Gantt
|
||||
attr_reader :year_from, :month_from, :date_from, :date_to, :zoom, :months, :events
|
||||
|
||||
def initialize(options={})
|
||||
options = options.dup
|
||||
@events = []
|
||||
|
||||
if options[:year] && options[:year].to_i >0
|
||||
@year_from = options[:year].to_i
|
||||
if options[:month] && options[:month].to_i >=1 && options[:month].to_i <= 12
|
||||
@month_from = options[:month].to_i
|
||||
else
|
||||
@month_from = 1
|
||||
end
|
||||
else
|
||||
@month_from ||= Date.today.month
|
||||
@year_from ||= Date.today.year
|
||||
end
|
||||
|
||||
zoom = (options[:zoom] || User.current.pref[:gantt_zoom]).to_i
|
||||
@zoom = (zoom > 0 && zoom < 5) ? zoom : 2
|
||||
months = (options[:months] || User.current.pref[:gantt_months]).to_i
|
||||
@months = (months > 0 && months < 25) ? months : 6
|
||||
|
||||
# Save gantt parameters as user preference (zoom and months count)
|
||||
if (User.current.logged? && (@zoom != User.current.pref[:gantt_zoom] || @months != User.current.pref[:gantt_months]))
|
||||
User.current.pref[:gantt_zoom], User.current.pref[:gantt_months] = @zoom, @months
|
||||
User.current.preference.save
|
||||
end
|
||||
|
||||
@date_from = Date.civil(@year_from, @month_from, 1)
|
||||
@date_to = (@date_from >> @months) - 1
|
||||
end
|
||||
|
||||
def events=(e)
|
||||
@events = e.sort {|x,y| x.start_date <=> y.start_date }
|
||||
end
|
||||
|
||||
def params
|
||||
{ :zoom => zoom, :year => year_from, :month => month_from, :months => months }
|
||||
end
|
||||
|
||||
def params_previous
|
||||
{ :year => (date_from << months).year, :month => (date_from << months).month, :zoom => zoom, :months => months }
|
||||
end
|
||||
|
||||
def params_next
|
||||
{ :year => (date_from >> months).year, :month => (date_from >> months).month, :zoom => zoom, :months => months }
|
||||
end
|
||||
|
||||
# Generates a gantt image
|
||||
# Only defined if RMagick is avalaible
|
||||
def to_image(format='PNG')
|
||||
date_to = (@date_from >> @months)-1
|
||||
show_weeks = @zoom > 1
|
||||
show_days = @zoom > 2
|
||||
|
||||
subject_width = 320
|
||||
header_heigth = 18
|
||||
# width of one day in pixels
|
||||
zoom = @zoom*2
|
||||
g_width = (@date_to - @date_from + 1)*zoom
|
||||
g_height = 20 * events.length + 20
|
||||
headers_heigth = (show_weeks ? 2*header_heigth : header_heigth)
|
||||
height = g_height + headers_heigth
|
||||
|
||||
imgl = Magick::ImageList.new
|
||||
imgl.new_image(subject_width+g_width+1, height)
|
||||
gc = Magick::Draw.new
|
||||
|
||||
# Subjects
|
||||
top = headers_heigth + 20
|
||||
gc.fill('black')
|
||||
gc.stroke('transparent')
|
||||
gc.stroke_width(1)
|
||||
events.each do |i|
|
||||
gc.text(4, top + 2, (i.is_a?(Issue) ? i.subject : i.name))
|
||||
top = top + 20
|
||||
end
|
||||
|
||||
# Months headers
|
||||
month_f = @date_from
|
||||
left = subject_width
|
||||
@months.times do
|
||||
width = ((month_f >> 1) - month_f) * zoom
|
||||
gc.fill('white')
|
||||
gc.stroke('grey')
|
||||
gc.stroke_width(1)
|
||||
gc.rectangle(left, 0, left + width, height)
|
||||
gc.fill('black')
|
||||
gc.stroke('transparent')
|
||||
gc.stroke_width(1)
|
||||
gc.text(left.round + 8, 14, "#{month_f.year}-#{month_f.month}")
|
||||
left = left + width
|
||||
month_f = month_f >> 1
|
||||
end
|
||||
|
||||
# Weeks headers
|
||||
if show_weeks
|
||||
left = subject_width
|
||||
height = header_heigth
|
||||
if @date_from.cwday == 1
|
||||
# date_from is monday
|
||||
week_f = date_from
|
||||
else
|
||||
# find next monday after date_from
|
||||
week_f = @date_from + (7 - @date_from.cwday + 1)
|
||||
width = (7 - @date_from.cwday + 1) * zoom
|
||||
gc.fill('white')
|
||||
gc.stroke('grey')
|
||||
gc.stroke_width(1)
|
||||
gc.rectangle(left, header_heigth, left + width, 2*header_heigth + g_height-1)
|
||||
left = left + width
|
||||
end
|
||||
while week_f <= date_to
|
||||
width = (week_f + 6 <= date_to) ? 7 * zoom : (date_to - week_f + 1) * zoom
|
||||
gc.fill('white')
|
||||
gc.stroke('grey')
|
||||
gc.stroke_width(1)
|
||||
gc.rectangle(left.round, header_heigth, left.round + width, 2*header_heigth + g_height-1)
|
||||
gc.fill('black')
|
||||
gc.stroke('transparent')
|
||||
gc.stroke_width(1)
|
||||
gc.text(left.round + 2, header_heigth + 14, week_f.cweek.to_s)
|
||||
left = left + width
|
||||
week_f = week_f+7
|
||||
end
|
||||
end
|
||||
|
||||
# Days details (week-end in grey)
|
||||
if show_days
|
||||
left = subject_width
|
||||
height = g_height + header_heigth - 1
|
||||
wday = @date_from.cwday
|
||||
(date_to - @date_from + 1).to_i.times do
|
||||
width = zoom
|
||||
gc.fill(wday == 6 || wday == 7 ? '#eee' : 'white')
|
||||
gc.stroke('grey')
|
||||
gc.stroke_width(1)
|
||||
gc.rectangle(left, 2*header_heigth, left + width, 2*header_heigth + g_height-1)
|
||||
left = left + width
|
||||
wday = wday + 1
|
||||
wday = 1 if wday > 7
|
||||
end
|
||||
end
|
||||
|
||||
# border
|
||||
gc.fill('transparent')
|
||||
gc.stroke('grey')
|
||||
gc.stroke_width(1)
|
||||
gc.rectangle(0, 0, subject_width+g_width, headers_heigth)
|
||||
gc.stroke('black')
|
||||
gc.rectangle(0, 0, subject_width+g_width, g_height+ headers_heigth-1)
|
||||
|
||||
# content
|
||||
top = headers_heigth + 20
|
||||
gc.stroke('transparent')
|
||||
events.each do |i|
|
||||
if i.is_a?(Issue)
|
||||
i_start_date = (i.start_date >= @date_from ? i.start_date : @date_from )
|
||||
i_end_date = (i.due_before <= date_to ? i.due_before : date_to )
|
||||
i_done_date = i.start_date + ((i.due_before - i.start_date+1)*i.done_ratio/100).floor
|
||||
i_done_date = (i_done_date <= @date_from ? @date_from : i_done_date )
|
||||
i_done_date = (i_done_date >= date_to ? date_to : i_done_date )
|
||||
i_late_date = [i_end_date, Date.today].min if i_start_date < Date.today
|
||||
|
||||
i_left = subject_width + ((i_start_date - @date_from)*zoom).floor
|
||||
i_width = ((i_end_date - i_start_date + 1)*zoom).floor # total width of the issue
|
||||
d_width = ((i_done_date - i_start_date)*zoom).floor # done width
|
||||
l_width = i_late_date ? ((i_late_date - i_start_date+1)*zoom).floor : 0 # delay width
|
||||
|
||||
gc.fill('grey')
|
||||
gc.rectangle(i_left, top, i_left + i_width, top - 6)
|
||||
gc.fill('red')
|
||||
gc.rectangle(i_left, top, i_left + l_width, top - 6) if l_width > 0
|
||||
gc.fill('blue')
|
||||
gc.rectangle(i_left, top, i_left + d_width, top - 6) if d_width > 0
|
||||
gc.fill('black')
|
||||
gc.text(i_left + i_width + 5,top + 1, "#{i.status.name} #{i.done_ratio}%")
|
||||
else
|
||||
i_left = subject_width + ((i.start_date - @date_from)*zoom).floor
|
||||
gc.fill('green')
|
||||
gc.rectangle(i_left, top, i_left + 6, top - 6)
|
||||
gc.fill('black')
|
||||
gc.text(i_left + 11, top + 1, i.name)
|
||||
end
|
||||
top = top + 20
|
||||
end
|
||||
|
||||
# today red line
|
||||
if Date.today >= @date_from and Date.today <= date_to
|
||||
gc.stroke('red')
|
||||
x = (Date.today-@date_from+1)*zoom + subject_width
|
||||
gc.line(x, headers_heigth, x, headers_heigth + g_height-1)
|
||||
end
|
||||
|
||||
gc.draw(imgl)
|
||||
imgl.format = format
|
||||
imgl.to_blob
|
||||
end if Object.const_defined?(:Magick)
|
||||
end
|
||||
end
|
||||
end
|
||||
@@ -0,0 +1,111 @@
|
||||
# Redmine - project management software
|
||||
# Copyright (C) 2006-2008 Jean-Philippe Lang
|
||||
#
|
||||
# This program is free software; you can redistribute it and/or
|
||||
# modify it under the terms of the GNU General Public License
|
||||
# as published by the Free Software Foundation; either version 2
|
||||
# of the License, or (at your option) any later version.
|
||||
#
|
||||
# This program is distributed in the hope that it will be useful,
|
||||
# but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
# GNU General Public License for more details.
|
||||
#
|
||||
# You should have received a copy of the GNU General Public License
|
||||
# along with this program; if not, write to the Free Software
|
||||
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
|
||||
|
||||
module Redmine
|
||||
module Hook
|
||||
@@listener_classes = []
|
||||
@@listeners = nil
|
||||
@@hook_listeners = {}
|
||||
|
||||
class << self
|
||||
# Adds a listener class.
|
||||
# Automatically called when a class inherits from Redmine::Hook::Listener.
|
||||
def add_listener(klass)
|
||||
raise "Hooks must include Singleton module." unless klass.included_modules.include?(Singleton)
|
||||
@@listener_classes << klass
|
||||
clear_listeners_instances
|
||||
end
|
||||
|
||||
# Returns all the listerners instances.
|
||||
def listeners
|
||||
@@listeners ||= @@listener_classes.collect {|listener| listener.instance}
|
||||
end
|
||||
|
||||
# Returns the listeners instances for the given hook.
|
||||
def hook_listeners(hook)
|
||||
@@hook_listeners[hook] ||= listeners.select {|listener| listener.respond_to?(hook)}
|
||||
end
|
||||
|
||||
# Clears all the listeners.
|
||||
def clear_listeners
|
||||
@@listener_classes = []
|
||||
clear_listeners_instances
|
||||
end
|
||||
|
||||
# Clears all the listeners instances.
|
||||
def clear_listeners_instances
|
||||
@@listeners = nil
|
||||
@@hook_listeners = {}
|
||||
end
|
||||
|
||||
# Calls a hook.
|
||||
# Returns the listeners response.
|
||||
def call_hook(hook, context={})
|
||||
response = ''
|
||||
hook_listeners(hook).each do |listener|
|
||||
response << listener.send(hook, context).to_s
|
||||
end
|
||||
response
|
||||
end
|
||||
end
|
||||
|
||||
# Base class for hook listeners.
|
||||
class Listener
|
||||
include Singleton
|
||||
include GLoc
|
||||
|
||||
# Registers the listener
|
||||
def self.inherited(child)
|
||||
Redmine::Hook.add_listener(child)
|
||||
super
|
||||
end
|
||||
end
|
||||
|
||||
# Listener class used for views hooks.
|
||||
# Listeners that inherit this class will include various helpers by default.
|
||||
class ViewListener < Listener
|
||||
include ERB::Util
|
||||
include ActionView::Helpers::TagHelper
|
||||
include ActionView::Helpers::FormHelper
|
||||
include ActionView::Helpers::FormTagHelper
|
||||
include ActionView::Helpers::FormOptionsHelper
|
||||
include ActionView::Helpers::JavaScriptHelper
|
||||
include ActionView::Helpers::PrototypeHelper
|
||||
include ActionView::Helpers::NumberHelper
|
||||
include ActionView::Helpers::UrlHelper
|
||||
include ActionView::Helpers::AssetTagHelper
|
||||
include ActionView::Helpers::TextHelper
|
||||
include ActionController::UrlWriter
|
||||
include ApplicationHelper
|
||||
end
|
||||
|
||||
# Helper module included in ApplicationHelper so that hooks can be called
|
||||
# in views like this:
|
||||
# <%= call_hook(:some_hook) %>
|
||||
# <%= call_hook(:another_hook, :foo => 'bar' %>
|
||||
#
|
||||
# Current project is automatically added to the call context.
|
||||
module Helper
|
||||
def call_hook(hook, context={})
|
||||
Redmine::Hook.call_hook(hook, {:project => @project}.merge(context))
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
ApplicationHelper.send(:include, Redmine::Hook::Helper)
|
||||
ActionController::Base.send(:include, Redmine::Hook::Helper)
|
||||
@@ -0,0 +1,51 @@
|
||||
# redMine - project management software
|
||||
# Copyright (C) 2006-2008 Jean-Philippe Lang
|
||||
#
|
||||
# This program is free software; you can redistribute it and/or
|
||||
# modify it under the terms of the GNU General Public License
|
||||
# as published by the Free Software Foundation; either version 2
|
||||
# of the License, or (at your option) any later version.
|
||||
#
|
||||
# This program is distributed in the hope that it will be useful,
|
||||
# but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
# GNU General Public License for more details.
|
||||
#
|
||||
# You should have received a copy of the GNU General Public License
|
||||
# along with this program; if not, write to the Free Software
|
||||
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
|
||||
|
||||
require 'net/imap'
|
||||
|
||||
module Redmine
|
||||
module IMAP
|
||||
class << self
|
||||
def check(imap_options={}, options={})
|
||||
host = imap_options[:host] || '127.0.0.1'
|
||||
port = imap_options[:port] || '143'
|
||||
ssl = !imap_options[:ssl].nil?
|
||||
folder = imap_options[:folder] || 'INBOX'
|
||||
|
||||
imap = Net::IMAP.new(host, port, ssl)
|
||||
imap.login(imap_options[:username], imap_options[:password]) unless imap_options[:username].nil?
|
||||
imap.select(folder)
|
||||
imap.search(['NOT', 'SEEN']).each do |message_id|
|
||||
msg = imap.fetch(message_id,'RFC822')[0].attr['RFC822']
|
||||
logger.debug "Receiving message #{message_id}" if logger && logger.debug?
|
||||
if MailHandler.receive(msg, options)
|
||||
imap.store(message_id, "+FLAGS", [:Seen, :Deleted])
|
||||
else
|
||||
imap.store(message_id, "+FLAGS", [:Seen])
|
||||
end
|
||||
end
|
||||
imap.expunge
|
||||
end
|
||||
|
||||
private
|
||||
|
||||
def logger
|
||||
RAILS_DEFAULT_LOGGER
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
@@ -0,0 +1,10 @@
|
||||
module Redmine
|
||||
module Info
|
||||
class << self
|
||||
def app_name; 'Redmine' end
|
||||
def url; 'http://www.redmine.org/' end
|
||||
def help_url; 'http://www.redmine.org/guide' end
|
||||
def versioned_name; "#{app_name} #{Redmine::VERSION}" end
|
||||
end
|
||||
end
|
||||
end
|
||||
@@ -0,0 +1,208 @@
|
||||
# redMine - project management software
|
||||
# Copyright (C) 2006-2007 Jean-Philippe Lang
|
||||
#
|
||||
# This program is free software; you can redistribute it and/or
|
||||
# modify it under the terms of the GNU General Public License
|
||||
# as published by the Free Software Foundation; either version 2
|
||||
# of the License, or (at your option) any later version.
|
||||
#
|
||||
# This program is distributed in the hope that it will be useful,
|
||||
# but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
# GNU General Public License for more details.
|
||||
#
|
||||
# You should have received a copy of the GNU General Public License
|
||||
# along with this program; if not, write to the Free Software
|
||||
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
|
||||
|
||||
require 'gloc'
|
||||
|
||||
module Redmine
|
||||
module MenuManager
|
||||
module MenuController
|
||||
def self.included(base)
|
||||
base.extend(ClassMethods)
|
||||
end
|
||||
|
||||
module ClassMethods
|
||||
@@menu_items = Hash.new {|hash, key| hash[key] = {:default => key, :actions => {}}}
|
||||
mattr_accessor :menu_items
|
||||
|
||||
# Set the menu item name for a controller or specific actions
|
||||
# Examples:
|
||||
# * menu_item :tickets # => sets the menu name to :tickets for the whole controller
|
||||
# * menu_item :tickets, :only => :list # => sets the menu name to :tickets for the 'list' action only
|
||||
# * menu_item :tickets, :only => [:list, :show] # => sets the menu name to :tickets for 2 actions only
|
||||
#
|
||||
# The default menu item name for a controller is controller_name by default
|
||||
# Eg. the default menu item name for ProjectsController is :projects
|
||||
def menu_item(id, options = {})
|
||||
if actions = options[:only]
|
||||
actions = [] << actions unless actions.is_a?(Array)
|
||||
actions.each {|a| menu_items[controller_name.to_sym][:actions][a.to_sym] = id}
|
||||
else
|
||||
menu_items[controller_name.to_sym][:default] = id
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
def menu_items
|
||||
self.class.menu_items
|
||||
end
|
||||
|
||||
# Returns the menu item name according to the current action
|
||||
def current_menu_item
|
||||
menu_items[controller_name.to_sym][:actions][action_name.to_sym] ||
|
||||
menu_items[controller_name.to_sym][:default]
|
||||
end
|
||||
end
|
||||
|
||||
module MenuHelper
|
||||
# Returns the current menu item name
|
||||
def current_menu_item
|
||||
@controller.current_menu_item
|
||||
end
|
||||
|
||||
# Renders the application main menu
|
||||
def render_main_menu(project)
|
||||
render_menu((project && !project.new_record?) ? :project_menu : :application_menu, project)
|
||||
end
|
||||
|
||||
def render_menu(menu, project=nil)
|
||||
links = []
|
||||
menu_items_for(menu, project) do |item, caption, url, selected|
|
||||
links << content_tag('li',
|
||||
link_to(h(caption), url, item.html_options(:selected => selected)))
|
||||
end
|
||||
links.empty? ? nil : content_tag('ul', links.join("\n"))
|
||||
end
|
||||
|
||||
def menu_items_for(menu, project=nil)
|
||||
items = []
|
||||
Redmine::MenuManager.allowed_items(menu, User.current, project).each do |item|
|
||||
unless item.condition && !item.condition.call(project)
|
||||
url = case item.url
|
||||
when Hash
|
||||
project.nil? ? item.url : {item.param => project}.merge(item.url)
|
||||
when Symbol
|
||||
send(item.url)
|
||||
else
|
||||
item.url
|
||||
end
|
||||
caption = item.caption(project)
|
||||
caption = l(caption) if caption.is_a?(Symbol)
|
||||
if block_given?
|
||||
yield item, caption, url, (current_menu_item == item.name)
|
||||
else
|
||||
items << [item, caption, url, (current_menu_item == item.name)]
|
||||
end
|
||||
end
|
||||
end
|
||||
return block_given? ? nil : items
|
||||
end
|
||||
end
|
||||
|
||||
class << self
|
||||
def map(menu_name)
|
||||
@items ||= {}
|
||||
mapper = Mapper.new(menu_name.to_sym, @items)
|
||||
if block_given?
|
||||
yield mapper
|
||||
else
|
||||
mapper
|
||||
end
|
||||
end
|
||||
|
||||
def items(menu_name)
|
||||
@items[menu_name.to_sym] || []
|
||||
end
|
||||
|
||||
def allowed_items(menu_name, user, project)
|
||||
project ? items(menu_name).select {|item| user && user.allowed_to?(item.url, project)} : items(menu_name)
|
||||
end
|
||||
end
|
||||
|
||||
class Mapper
|
||||
def initialize(menu, items)
|
||||
items[menu] ||= []
|
||||
@menu = menu
|
||||
@menu_items = items[menu]
|
||||
end
|
||||
|
||||
@@last_items_count = Hash.new {|h,k| h[k] = 0}
|
||||
|
||||
# Adds an item at the end of the menu. Available options:
|
||||
# * param: the parameter name that is used for the project id (default is :id)
|
||||
# * if: a Proc that is called before rendering the item, the item is displayed only if it returns true
|
||||
# * caption that can be:
|
||||
# * a localized string Symbol
|
||||
# * a String
|
||||
# * a Proc that can take the project as argument
|
||||
# * before, after: specify where the menu item should be inserted (eg. :after => :activity)
|
||||
# * last: menu item will stay at the end (eg. :last => true)
|
||||
# * html_options: a hash of html options that are passed to link_to
|
||||
def push(name, url, options={})
|
||||
options = options.dup
|
||||
|
||||
# menu item position
|
||||
if before = options.delete(:before)
|
||||
position = @menu_items.collect(&:name).index(before)
|
||||
elsif after = options.delete(:after)
|
||||
position = @menu_items.collect(&:name).index(after)
|
||||
position += 1 unless position.nil?
|
||||
elsif options.delete(:last)
|
||||
position = @menu_items.size
|
||||
@@last_items_count[@menu] += 1
|
||||
end
|
||||
# default position
|
||||
position ||= @menu_items.size - @@last_items_count[@menu]
|
||||
|
||||
@menu_items.insert(position, MenuItem.new(name, url, options))
|
||||
end
|
||||
|
||||
# Removes a menu item
|
||||
def delete(name)
|
||||
@menu_items.delete_if {|i| i.name == name}
|
||||
end
|
||||
end
|
||||
|
||||
class MenuItem
|
||||
include GLoc
|
||||
attr_reader :name, :url, :param, :condition
|
||||
|
||||
def initialize(name, url, options)
|
||||
raise "Invalid option :if for menu item '#{name}'" if options[:if] && !options[:if].respond_to?(:call)
|
||||
raise "Invalid option :html for menu item '#{name}'" if options[:html] && !options[:html].is_a?(Hash)
|
||||
@name = name
|
||||
@url = url
|
||||
@condition = options[:if]
|
||||
@param = options[:param] || :id
|
||||
@caption = options[:caption]
|
||||
@html_options = options[:html] || {}
|
||||
# Adds a unique class to each menu item based on its name
|
||||
@html_options[:class] = [@html_options[:class], @name.to_s.dasherize].compact.join(' ')
|
||||
end
|
||||
|
||||
def caption(project=nil)
|
||||
if @caption.is_a?(Proc)
|
||||
c = @caption.call(project).to_s
|
||||
c = @name.to_s.humanize if c.blank?
|
||||
c
|
||||
else
|
||||
# check if localized string exists on first render (after GLoc strings are loaded)
|
||||
@caption_key ||= (@caption || (l_has_string?("label_#{@name}".to_sym) ? "label_#{@name}".to_sym : @name.to_s.humanize))
|
||||
end
|
||||
end
|
||||
|
||||
def html_options(options={})
|
||||
if options[:selected]
|
||||
o = @html_options.dup
|
||||
o[:class] += ' selected'
|
||||
o
|
||||
else
|
||||
@html_options
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
@@ -0,0 +1,70 @@
|
||||
# redMine - project management software
|
||||
# Copyright (C) 2006-2007 Jean-Philippe Lang
|
||||
#
|
||||
# This program is free software; you can redistribute it and/or
|
||||
# modify it under the terms of the GNU General Public License
|
||||
# as published by the Free Software Foundation; either version 2
|
||||
# of the License, or (at your option) any later version.
|
||||
#
|
||||
# This program is distributed in the hope that it will be useful,
|
||||
# but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
# GNU General Public License for more details.
|
||||
#
|
||||
# You should have received a copy of the GNU General Public License
|
||||
# along with this program; if not, write to the Free Software
|
||||
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
|
||||
|
||||
module Redmine
|
||||
module MimeType
|
||||
|
||||
MIME_TYPES = {
|
||||
'text/plain' => 'txt,tpl,properties,patch,diff,ini,readme,install,upgrade',
|
||||
'text/css' => 'css',
|
||||
'text/html' => 'html,htm,xhtml',
|
||||
'text/jsp' => 'jsp',
|
||||
'text/x-c' => 'c,cpp,cc,h,hh',
|
||||
'text/x-java' => 'java',
|
||||
'text/x-javascript' => 'js',
|
||||
'text/x-html-template' => 'rhtml',
|
||||
'text/x-perl' => 'pl,pm',
|
||||
'text/x-php' => 'php,php3,php4,php5',
|
||||
'text/x-python' => 'py',
|
||||
'text/x-ruby' => 'rb,rbw,ruby,rake',
|
||||
'text/x-csh' => 'csh',
|
||||
'text/x-sh' => 'sh',
|
||||
'text/xml' => 'xml,xsd,mxml',
|
||||
'text/yaml' => 'yml,yaml',
|
||||
'image/gif' => 'gif',
|
||||
'image/jpeg' => 'jpg,jpeg,jpe',
|
||||
'image/png' => 'png',
|
||||
'image/tiff' => 'tiff,tif',
|
||||
'image/x-ms-bmp' => 'bmp',
|
||||
'image/x-xpixmap' => 'xpm',
|
||||
}.freeze
|
||||
|
||||
EXTENSIONS = MIME_TYPES.inject({}) do |map, (type, exts)|
|
||||
exts.split(',').each {|ext| map[ext.strip] = type}
|
||||
map
|
||||
end
|
||||
|
||||
# returns mime type for name or nil if unknown
|
||||
def self.of(name)
|
||||
return nil unless name
|
||||
m = name.to_s.match(/(^|\.)([^\.]+)$/)
|
||||
EXTENSIONS[m[2].downcase] if m
|
||||
end
|
||||
|
||||
def self.main_mimetype_of(name)
|
||||
mimetype = of(name)
|
||||
mimetype.split('/').first if mimetype
|
||||
end
|
||||
|
||||
# return true if mime-type for name is type/*
|
||||
# otherwise false
|
||||
def self.is_type?(type, name)
|
||||
main_mimetype = main_mimetype_of(name)
|
||||
type.to_s == main_mimetype
|
||||
end
|
||||
end
|
||||
end
|
||||
@@ -0,0 +1,26 @@
|
||||
# Redmine - project management software
|
||||
# Copyright (C) 2006-2008 Jean-Philippe Lang
|
||||
#
|
||||
# This program is free software; you can redistribute it and/or
|
||||
# modify it under the terms of the GNU General Public License
|
||||
# as published by the Free Software Foundation; either version 2
|
||||
# of the License, or (at your option) any later version.
|
||||
#
|
||||
# This program is distributed in the hope that it will be useful,
|
||||
# but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
# GNU General Public License for more details.
|
||||
#
|
||||
# You should have received a copy of the GNU General Public License
|
||||
# along with this program; if not, write to the Free Software
|
||||
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
|
||||
|
||||
module Redmine
|
||||
module Platform
|
||||
class << self
|
||||
def mswin?
|
||||
(RUBY_PLATFORM =~ /(:?mswin|mingw)/) || (RUBY_PLATFORM == 'java' && (ENV['OS'] || ENV['os']) =~ /windows/i)
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
@@ -0,0 +1,232 @@
|
||||
# redMine - project management software
|
||||
# Copyright (C) 2006-2007 Jean-Philippe Lang
|
||||
#
|
||||
# This program is free software; you can redistribute it and/or
|
||||
# modify it under the terms of the GNU General Public License
|
||||
# as published by the Free Software Foundation; either version 2
|
||||
# of the License, or (at your option) any later version.
|
||||
#
|
||||
# This program is distributed in the hope that it will be useful,
|
||||
# but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
# GNU General Public License for more details.
|
||||
#
|
||||
# You should have received a copy of the GNU General Public License
|
||||
# along with this program; if not, write to the Free Software
|
||||
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
|
||||
|
||||
module Redmine #:nodoc:
|
||||
|
||||
class PluginNotFound < StandardError; end
|
||||
class PluginRequirementError < StandardError; end
|
||||
|
||||
# Base class for Redmine plugins.
|
||||
# Plugins are registered using the <tt>register</tt> class method that acts as the public constructor.
|
||||
#
|
||||
# Redmine::Plugin.register :example do
|
||||
# name 'Example plugin'
|
||||
# author 'John Smith'
|
||||
# description 'This is an example plugin for Redmine'
|
||||
# version '0.0.1'
|
||||
# settings :default => {'foo'=>'bar'}, :partial => 'settings/settings'
|
||||
# end
|
||||
#
|
||||
# === Plugin attributes
|
||||
#
|
||||
# +settings+ is an optional attribute that let the plugin be configurable.
|
||||
# It must be a hash with the following keys:
|
||||
# * <tt>:default</tt>: default value for the plugin settings
|
||||
# * <tt>:partial</tt>: path of the configuration partial view, relative to the plugin <tt>app/views</tt> directory
|
||||
# Example:
|
||||
# settings :default => {'foo'=>'bar'}, :partial => 'settings/settings'
|
||||
# In this example, the settings partial will be found here in the plugin directory: <tt>app/views/settings/_settings.rhtml</tt>.
|
||||
#
|
||||
# When rendered, the plugin settings value is available as the local variable +settings+
|
||||
class Plugin
|
||||
@registered_plugins = {}
|
||||
class << self
|
||||
attr_reader :registered_plugins
|
||||
private :new
|
||||
|
||||
def def_field(*names)
|
||||
class_eval do
|
||||
names.each do |name|
|
||||
define_method(name) do |*args|
|
||||
args.empty? ? instance_variable_get("@#{name}") : instance_variable_set("@#{name}", *args)
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
def_field :name, :description, :url, :author, :author_url, :version, :settings
|
||||
attr_reader :id
|
||||
|
||||
# Plugin constructor
|
||||
def self.register(id, &block)
|
||||
p = new(id)
|
||||
p.instance_eval(&block)
|
||||
# Set a default name if it was not provided during registration
|
||||
p.name(id.to_s.humanize) if p.name.nil?
|
||||
registered_plugins[id] = p
|
||||
end
|
||||
|
||||
# Returns an array off all registered plugins
|
||||
def self.all
|
||||
registered_plugins.values.sort
|
||||
end
|
||||
|
||||
# Finds a plugin by its id
|
||||
# Returns a PluginNotFound exception if the plugin doesn't exist
|
||||
def self.find(id)
|
||||
registered_plugins[id.to_sym] || raise(PluginNotFound)
|
||||
end
|
||||
|
||||
# Clears the registered plugins hash
|
||||
# It doesn't unload installed plugins
|
||||
def self.clear
|
||||
@registered_plugins = {}
|
||||
end
|
||||
|
||||
def initialize(id)
|
||||
@id = id.to_sym
|
||||
end
|
||||
|
||||
def <=>(plugin)
|
||||
self.id.to_s <=> plugin.id.to_s
|
||||
end
|
||||
|
||||
# Sets a requirement on Redmine version
|
||||
# Raises a PluginRequirementError exception if the requirement is not met
|
||||
#
|
||||
# Examples
|
||||
# # Requires Redmine 0.7.3 or higher
|
||||
# requires_redmine :version_or_higher => '0.7.3'
|
||||
# requires_redmine '0.7.3'
|
||||
#
|
||||
# # Requires a specific Redmine version
|
||||
# requires_redmine :version => '0.7.3' # 0.7.3 only
|
||||
# requires_redmine :version => ['0.7.3', '0.8.0'] # 0.7.3 or 0.8.0
|
||||
def requires_redmine(arg)
|
||||
arg = { :version_or_higher => arg } unless arg.is_a?(Hash)
|
||||
arg.assert_valid_keys(:version, :version_or_higher)
|
||||
|
||||
current = Redmine::VERSION.to_a
|
||||
arg.each do |k, v|
|
||||
v = [] << v unless v.is_a?(Array)
|
||||
versions = v.collect {|s| s.split('.').collect(&:to_i)}
|
||||
case k
|
||||
when :version_or_higher
|
||||
raise ArgumentError.new("wrong number of versions (#{versions.size} for 1)") unless versions.size == 1
|
||||
unless (current <=> versions.first) >= 0
|
||||
raise PluginRequirementError.new("#{id} plugin requires Redmine #{v} or higher but current is #{current.join('.')}")
|
||||
end
|
||||
when :version
|
||||
unless versions.include?(current.slice(0,3))
|
||||
raise PluginRequirementError.new("#{id} plugin requires one the following Redmine versions: #{v.join(', ')} but current is #{current.join('.')}")
|
||||
end
|
||||
end
|
||||
end
|
||||
true
|
||||
end
|
||||
|
||||
# Adds an item to the given +menu+.
|
||||
# The +id+ parameter (equals to the project id) is automatically added to the url.
|
||||
# menu :project_menu, :plugin_example, { :controller => 'example', :action => 'say_hello' }, :caption => 'Sample'
|
||||
#
|
||||
# +name+ parameter can be: :top_menu, :account_menu, :application_menu or :project_menu
|
||||
#
|
||||
def menu(menu, item, url, options={})
|
||||
Redmine::MenuManager.map(menu).push(item, url, options)
|
||||
end
|
||||
alias :add_menu_item :menu
|
||||
|
||||
# Removes +item+ from the given +menu+.
|
||||
def delete_menu_item(menu, item)
|
||||
Redmine::MenuManager.map(menu).delete(item)
|
||||
end
|
||||
|
||||
# Defines a permission called +name+ for the given +actions+.
|
||||
#
|
||||
# The +actions+ argument is a hash with controllers as keys and actions as values (a single value or an array):
|
||||
# permission :destroy_contacts, { :contacts => :destroy }
|
||||
# permission :view_contacts, { :contacts => [:index, :show] }
|
||||
#
|
||||
# The +options+ argument can be used to make the permission public (implicitly given to any user)
|
||||
# or to restrict users the permission can be given to.
|
||||
#
|
||||
# Examples
|
||||
# # A permission that is implicitly given to any user
|
||||
# # This permission won't appear on the Roles & Permissions setup screen
|
||||
# permission :say_hello, { :example => :say_hello }, :public => true
|
||||
#
|
||||
# # A permission that can be given to any user
|
||||
# permission :say_hello, { :example => :say_hello }
|
||||
#
|
||||
# # A permission that can be given to registered users only
|
||||
# permission :say_hello, { :example => :say_hello }, :require => loggedin
|
||||
#
|
||||
# # A permission that can be given to project members only
|
||||
# permission :say_hello, { :example => :say_hello }, :require => member
|
||||
def permission(name, actions, options = {})
|
||||
if @project_module
|
||||
Redmine::AccessControl.map {|map| map.project_module(@project_module) {|map|map.permission(name, actions, options)}}
|
||||
else
|
||||
Redmine::AccessControl.map {|map| map.permission(name, actions, options)}
|
||||
end
|
||||
end
|
||||
|
||||
# Defines a project module, that can be enabled/disabled for each project.
|
||||
# Permissions defined inside +block+ will be bind to the module.
|
||||
#
|
||||
# project_module :things do
|
||||
# permission :view_contacts, { :contacts => [:list, :show] }, :public => true
|
||||
# permission :destroy_contacts, { :contacts => :destroy }
|
||||
# end
|
||||
def project_module(name, &block)
|
||||
@project_module = name
|
||||
self.instance_eval(&block)
|
||||
@project_module = nil
|
||||
end
|
||||
|
||||
# Registers an activity provider.
|
||||
#
|
||||
# Options:
|
||||
# * <tt>:class_name</tt> - one or more model(s) that provide these events (inferred from event_type by default)
|
||||
# * <tt>:default</tt> - setting this option to false will make the events not displayed by default
|
||||
#
|
||||
# A model can provide several activity event types.
|
||||
#
|
||||
# Examples:
|
||||
# register :news
|
||||
# register :scrums, :class_name => 'Meeting'
|
||||
# register :issues, :class_name => ['Issue', 'Journal']
|
||||
#
|
||||
# Retrieving events:
|
||||
# Associated model(s) must implement the find_events class method.
|
||||
# ActiveRecord models can use acts_as_activity_provider as a way to implement this class method.
|
||||
#
|
||||
# The following call should return all the scrum events visible by current user that occured in the 5 last days:
|
||||
# Meeting.find_events('scrums', User.current, 5.days.ago, Date.today)
|
||||
# Meeting.find_events('scrums', User.current, 5.days.ago, Date.today, :project => foo) # events for project foo only
|
||||
#
|
||||
# Note that :view_scrums permission is required to view these events in the activity view.
|
||||
def activity_provider(*args)
|
||||
Redmine::Activity.register(*args)
|
||||
end
|
||||
|
||||
# Registers a wiki formatter.
|
||||
#
|
||||
# Parameters:
|
||||
# * +name+ - human-readable name
|
||||
# * +formatter+ - formatter class, which should have an instance method +to_html+
|
||||
# * +helper+ - helper module, which will be included by wiki pages
|
||||
def wiki_format_provider(name, formatter, helper)
|
||||
Redmine::WikiFormatting.register(name, formatter, helper)
|
||||
end
|
||||
|
||||
# Returns +true+ if the plugin can be configured.
|
||||
def configurable?
|
||||
settings && settings.is_a?(Hash) && !settings[:partial].blank?
|
||||
end
|
||||
end
|
||||
end
|
||||
@@ -0,0 +1,300 @@
|
||||
# redMine - project management software
|
||||
# Copyright (C) 2006-2007 Jean-Philippe Lang
|
||||
#
|
||||
# This program is free software; you can redistribute it and/or
|
||||
# modify it under the terms of the GNU General Public License
|
||||
# as published by the Free Software Foundation; either version 2
|
||||
# of the License, or (at your option) any later version.
|
||||
#
|
||||
# This program is distributed in the hope that it will be useful,
|
||||
# but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
# GNU General Public License for more details.
|
||||
#
|
||||
# You should have received a copy of the GNU General Public License
|
||||
# along with this program; if not, write to the Free Software
|
||||
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
|
||||
|
||||
require 'cgi'
|
||||
|
||||
module Redmine
|
||||
module Scm
|
||||
module Adapters
|
||||
class CommandFailed < StandardError #:nodoc:
|
||||
end
|
||||
|
||||
class AbstractAdapter #:nodoc:
|
||||
class << self
|
||||
# Returns the version of the scm client
|
||||
# Eg: [1, 5, 0] or [] if unknown
|
||||
def client_version
|
||||
[]
|
||||
end
|
||||
|
||||
# Returns the version string of the scm client
|
||||
# Eg: '1.5.0' or 'Unknown version' if unknown
|
||||
def client_version_string
|
||||
v = client_version || 'Unknown version'
|
||||
v.is_a?(Array) ? v.join('.') : v.to_s
|
||||
end
|
||||
|
||||
# Returns true if the current client version is above
|
||||
# or equals the given one
|
||||
# If option is :unknown is set to true, it will return
|
||||
# true if the client version is unknown
|
||||
def client_version_above?(v, options={})
|
||||
((client_version <=> v) >= 0) || (client_version.empty? && options[:unknown])
|
||||
end
|
||||
end
|
||||
|
||||
def initialize(url, root_url=nil, login=nil, password=nil)
|
||||
@url = url
|
||||
@login = login if login && !login.empty?
|
||||
@password = (password || "") if @login
|
||||
@root_url = root_url.blank? ? retrieve_root_url : root_url
|
||||
end
|
||||
|
||||
def adapter_name
|
||||
'Abstract'
|
||||
end
|
||||
|
||||
def supports_cat?
|
||||
true
|
||||
end
|
||||
|
||||
def supports_annotate?
|
||||
respond_to?('annotate')
|
||||
end
|
||||
|
||||
def root_url
|
||||
@root_url
|
||||
end
|
||||
|
||||
def url
|
||||
@url
|
||||
end
|
||||
|
||||
# get info about the svn repository
|
||||
def info
|
||||
return nil
|
||||
end
|
||||
|
||||
# Returns the entry identified by path and revision identifier
|
||||
# or nil if entry doesn't exist in the repository
|
||||
def entry(path=nil, identifier=nil)
|
||||
parts = path.to_s.split(%r{[\/\\]}).select {|n| !n.blank?}
|
||||
search_path = parts[0..-2].join('/')
|
||||
search_name = parts[-1]
|
||||
if search_path.blank? && search_name.blank?
|
||||
# Root entry
|
||||
Entry.new(:path => '', :kind => 'dir')
|
||||
else
|
||||
# Search for the entry in the parent directory
|
||||
es = entries(search_path, identifier)
|
||||
es ? es.detect {|e| e.name == search_name} : nil
|
||||
end
|
||||
end
|
||||
|
||||
# Returns an Entries collection
|
||||
# or nil if the given path doesn't exist in the repository
|
||||
def entries(path=nil, identifier=nil)
|
||||
return nil
|
||||
end
|
||||
|
||||
def properties(path, identifier=nil)
|
||||
return nil
|
||||
end
|
||||
|
||||
def revisions(path=nil, identifier_from=nil, identifier_to=nil, options={})
|
||||
return nil
|
||||
end
|
||||
|
||||
def diff(path, identifier_from, identifier_to=nil)
|
||||
return nil
|
||||
end
|
||||
|
||||
def cat(path, identifier=nil)
|
||||
return nil
|
||||
end
|
||||
|
||||
def with_leading_slash(path)
|
||||
path ||= ''
|
||||
(path[0,1]!="/") ? "/#{path}" : path
|
||||
end
|
||||
|
||||
def with_trailling_slash(path)
|
||||
path ||= ''
|
||||
(path[-1,1] == "/") ? path : "#{path}/"
|
||||
end
|
||||
|
||||
def without_leading_slash(path)
|
||||
path ||= ''
|
||||
path.gsub(%r{^/+}, '')
|
||||
end
|
||||
|
||||
def without_trailling_slash(path)
|
||||
path ||= ''
|
||||
(path[-1,1] == "/") ? path[0..-2] : path
|
||||
end
|
||||
|
||||
def shell_quote(str)
|
||||
if Redmine::Platform.mswin?
|
||||
'"' + str.gsub(/"/, '\\"') + '"'
|
||||
else
|
||||
"'" + str.gsub(/'/, "'\"'\"'") + "'"
|
||||
end
|
||||
end
|
||||
|
||||
private
|
||||
def retrieve_root_url
|
||||
info = self.info
|
||||
info ? info.root_url : nil
|
||||
end
|
||||
|
||||
def target(path)
|
||||
path ||= ''
|
||||
base = path.match(/^\//) ? root_url : url
|
||||
shell_quote("#{base}/#{path}".gsub(/[?<>\*]/, ''))
|
||||
end
|
||||
|
||||
def logger
|
||||
self.class.logger
|
||||
end
|
||||
|
||||
def shellout(cmd, &block)
|
||||
self.class.shellout(cmd, &block)
|
||||
end
|
||||
|
||||
def self.logger
|
||||
RAILS_DEFAULT_LOGGER
|
||||
end
|
||||
|
||||
def self.shellout(cmd, &block)
|
||||
logger.debug "Shelling out: #{cmd}" if logger && logger.debug?
|
||||
if Rails.env == 'development'
|
||||
# Capture stderr when running in dev environment
|
||||
cmd = "#{cmd} 2>>#{RAILS_ROOT}/log/scm.stderr.log"
|
||||
end
|
||||
begin
|
||||
IO.popen(cmd, "r+") do |io|
|
||||
io.close_write
|
||||
block.call(io) if block_given?
|
||||
end
|
||||
rescue Errno::ENOENT => e
|
||||
msg = strip_credential(e.message)
|
||||
# The command failed, log it and re-raise
|
||||
logger.error("SCM command failed, make sure that your SCM binary (eg. svn) is in PATH (#{ENV['PATH']}): #{strip_credential(cmd)}\n with: #{msg}")
|
||||
raise CommandFailed.new(msg)
|
||||
end
|
||||
end
|
||||
|
||||
# Hides username/password in a given command
|
||||
def self.strip_credential(cmd)
|
||||
q = (Redmine::Platform.mswin? ? '"' : "'")
|
||||
cmd.to_s.gsub(/(\-\-(password|username))\s+(#{q}[^#{q}]+#{q}|[^#{q}]\S+)/, '\\1 xxxx')
|
||||
end
|
||||
|
||||
def strip_credential(cmd)
|
||||
self.class.strip_credential(cmd)
|
||||
end
|
||||
end
|
||||
|
||||
class Entries < Array
|
||||
def sort_by_name
|
||||
sort {|x,y|
|
||||
if x.kind == y.kind
|
||||
x.name <=> y.name
|
||||
else
|
||||
x.kind <=> y.kind
|
||||
end
|
||||
}
|
||||
end
|
||||
|
||||
def revisions
|
||||
revisions ||= Revisions.new(collect{|entry| entry.lastrev}.compact)
|
||||
end
|
||||
end
|
||||
|
||||
class Info
|
||||
attr_accessor :root_url, :lastrev
|
||||
def initialize(attributes={})
|
||||
self.root_url = attributes[:root_url] if attributes[:root_url]
|
||||
self.lastrev = attributes[:lastrev]
|
||||
end
|
||||
end
|
||||
|
||||
class Entry
|
||||
attr_accessor :name, :path, :kind, :size, :lastrev
|
||||
def initialize(attributes={})
|
||||
self.name = attributes[:name] if attributes[:name]
|
||||
self.path = attributes[:path] if attributes[:path]
|
||||
self.kind = attributes[:kind] if attributes[:kind]
|
||||
self.size = attributes[:size].to_i if attributes[:size]
|
||||
self.lastrev = attributes[:lastrev]
|
||||
end
|
||||
|
||||
def is_file?
|
||||
'file' == self.kind
|
||||
end
|
||||
|
||||
def is_dir?
|
||||
'dir' == self.kind
|
||||
end
|
||||
|
||||
def is_text?
|
||||
Redmine::MimeType.is_type?('text', name)
|
||||
end
|
||||
end
|
||||
|
||||
class Revisions < Array
|
||||
def latest
|
||||
sort {|x,y|
|
||||
unless x.time.nil? or y.time.nil?
|
||||
x.time <=> y.time
|
||||
else
|
||||
0
|
||||
end
|
||||
}.last
|
||||
end
|
||||
end
|
||||
|
||||
class Revision
|
||||
attr_accessor :identifier, :scmid, :name, :author, :time, :message, :paths, :revision, :branch
|
||||
def initialize(attributes={})
|
||||
self.identifier = attributes[:identifier]
|
||||
self.scmid = attributes[:scmid]
|
||||
self.name = attributes[:name] || self.identifier
|
||||
self.author = attributes[:author]
|
||||
self.time = attributes[:time]
|
||||
self.message = attributes[:message] || ""
|
||||
self.paths = attributes[:paths]
|
||||
self.revision = attributes[:revision]
|
||||
self.branch = attributes[:branch]
|
||||
end
|
||||
|
||||
end
|
||||
|
||||
class Annotate
|
||||
attr_reader :lines, :revisions
|
||||
|
||||
def initialize
|
||||
@lines = []
|
||||
@revisions = []
|
||||
end
|
||||
|
||||
def add_line(line, revision)
|
||||
@lines << line
|
||||
@revisions << revision
|
||||
end
|
||||
|
||||
def content
|
||||
content = lines.join("\n")
|
||||
end
|
||||
|
||||
def empty?
|
||||
lines.empty?
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
@@ -0,0 +1,186 @@
|
||||
# redMine - project management software
|
||||
# Copyright (C) 2006-2007 Jean-Philippe Lang
|
||||
#
|
||||
# This program is free software; you can redistribute it and/or
|
||||
# modify it under the terms of the GNU General Public License
|
||||
# as published by the Free Software Foundation; either version 2
|
||||
# of the License, or (at your option) any later version.
|
||||
#
|
||||
# This program is distributed in the hope that it will be useful,
|
||||
# but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
# GNU General Public License for more details.
|
||||
#
|
||||
# You should have received a copy of the GNU General Public License
|
||||
# along with this program; if not, write to the Free Software
|
||||
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
|
||||
|
||||
require 'redmine/scm/adapters/abstract_adapter'
|
||||
|
||||
module Redmine
|
||||
module Scm
|
||||
module Adapters
|
||||
class BazaarAdapter < AbstractAdapter
|
||||
|
||||
# Bazaar executable name
|
||||
BZR_BIN = "bzr"
|
||||
|
||||
# Get info about the repository
|
||||
def info
|
||||
cmd = "#{BZR_BIN} revno #{target('')}"
|
||||
info = nil
|
||||
shellout(cmd) do |io|
|
||||
if io.read =~ %r{^(\d+)$}
|
||||
info = Info.new({:root_url => url,
|
||||
:lastrev => Revision.new({
|
||||
:identifier => $1
|
||||
})
|
||||
})
|
||||
end
|
||||
end
|
||||
return nil if $? && $?.exitstatus != 0
|
||||
info
|
||||
rescue CommandFailed
|
||||
return nil
|
||||
end
|
||||
|
||||
# Returns an Entries collection
|
||||
# or nil if the given path doesn't exist in the repository
|
||||
def entries(path=nil, identifier=nil)
|
||||
path ||= ''
|
||||
entries = Entries.new
|
||||
cmd = "#{BZR_BIN} ls -v --show-ids"
|
||||
identifier = -1 unless identifier && identifier.to_i > 0
|
||||
cmd << " -r#{identifier.to_i}"
|
||||
cmd << " #{target(path)}"
|
||||
shellout(cmd) do |io|
|
||||
prefix = "#{url}/#{path}".gsub('\\', '/')
|
||||
logger.debug "PREFIX: #{prefix}"
|
||||
re = %r{^V\s+#{Regexp.escape(prefix)}(\/?)([^\/]+)(\/?)\s+(\S+)$}
|
||||
io.each_line do |line|
|
||||
next unless line =~ re
|
||||
entries << Entry.new({:name => $2.strip,
|
||||
:path => ((path.empty? ? "" : "#{path}/") + $2.strip),
|
||||
:kind => ($3.blank? ? 'file' : 'dir'),
|
||||
:size => nil,
|
||||
:lastrev => Revision.new(:revision => $4.strip)
|
||||
})
|
||||
end
|
||||
end
|
||||
return nil if $? && $?.exitstatus != 0
|
||||
logger.debug("Found #{entries.size} entries in the repository for #{target(path)}") if logger && logger.debug?
|
||||
entries.sort_by_name
|
||||
end
|
||||
|
||||
def revisions(path=nil, identifier_from=nil, identifier_to=nil, options={})
|
||||
path ||= ''
|
||||
identifier_from = 'last:1' unless identifier_from and identifier_from.to_i > 0
|
||||
identifier_to = 1 unless identifier_to and identifier_to.to_i > 0
|
||||
revisions = Revisions.new
|
||||
cmd = "#{BZR_BIN} log -v --show-ids -r#{identifier_to.to_i}..#{identifier_from} #{target(path)}"
|
||||
shellout(cmd) do |io|
|
||||
revision = nil
|
||||
parsing = nil
|
||||
io.each_line do |line|
|
||||
if line =~ /^----/
|
||||
revisions << revision if revision
|
||||
revision = Revision.new(:paths => [], :message => '')
|
||||
parsing = nil
|
||||
else
|
||||
next unless revision
|
||||
|
||||
if line =~ /^revno: (\d+)$/
|
||||
revision.identifier = $1.to_i
|
||||
elsif line =~ /^committer: (.+)$/
|
||||
revision.author = $1.strip
|
||||
elsif line =~ /^revision-id:(.+)$/
|
||||
revision.scmid = $1.strip
|
||||
elsif line =~ /^timestamp: (.+)$/
|
||||
revision.time = Time.parse($1).localtime
|
||||
elsif line =~ /^ -----/
|
||||
# partial revisions
|
||||
parsing = nil unless parsing == 'message'
|
||||
elsif line =~ /^(message|added|modified|removed|renamed):/
|
||||
parsing = $1
|
||||
elsif line =~ /^ (.*)$/
|
||||
if parsing == 'message'
|
||||
revision.message << "#{$1}\n"
|
||||
else
|
||||
if $1 =~ /^(.*)\s+(\S+)$/
|
||||
path = $1.strip
|
||||
revid = $2
|
||||
case parsing
|
||||
when 'added'
|
||||
revision.paths << {:action => 'A', :path => "/#{path}", :revision => revid}
|
||||
when 'modified'
|
||||
revision.paths << {:action => 'M', :path => "/#{path}", :revision => revid}
|
||||
when 'removed'
|
||||
revision.paths << {:action => 'D', :path => "/#{path}", :revision => revid}
|
||||
when 'renamed'
|
||||
new_path = path.split('=>').last
|
||||
revision.paths << {:action => 'M', :path => "/#{new_path.strip}", :revision => revid} if new_path
|
||||
end
|
||||
end
|
||||
end
|
||||
else
|
||||
parsing = nil
|
||||
end
|
||||
end
|
||||
end
|
||||
revisions << revision if revision
|
||||
end
|
||||
return nil if $? && $?.exitstatus != 0
|
||||
revisions
|
||||
end
|
||||
|
||||
def diff(path, identifier_from, identifier_to=nil)
|
||||
path ||= ''
|
||||
if identifier_to
|
||||
identifier_to = identifier_to.to_i
|
||||
else
|
||||
identifier_to = identifier_from.to_i - 1
|
||||
end
|
||||
cmd = "#{BZR_BIN} diff -r#{identifier_to}..#{identifier_from} #{target(path)}"
|
||||
diff = []
|
||||
shellout(cmd) do |io|
|
||||
io.each_line do |line|
|
||||
diff << line
|
||||
end
|
||||
end
|
||||
#return nil if $? && $?.exitstatus != 0
|
||||
diff
|
||||
end
|
||||
|
||||
def cat(path, identifier=nil)
|
||||
cmd = "#{BZR_BIN} cat"
|
||||
cmd << " -r#{identifier.to_i}" if identifier && identifier.to_i > 0
|
||||
cmd << " #{target(path)}"
|
||||
cat = nil
|
||||
shellout(cmd) do |io|
|
||||
io.binmode
|
||||
cat = io.read
|
||||
end
|
||||
return nil if $? && $?.exitstatus != 0
|
||||
cat
|
||||
end
|
||||
|
||||
def annotate(path, identifier=nil)
|
||||
cmd = "#{BZR_BIN} annotate --all"
|
||||
cmd << " -r#{identifier.to_i}" if identifier && identifier.to_i > 0
|
||||
cmd << " #{target(path)}"
|
||||
blame = Annotate.new
|
||||
shellout(cmd) do |io|
|
||||
author = nil
|
||||
identifier = nil
|
||||
io.each_line do |line|
|
||||
next unless line =~ %r{^(\d+) ([^|]+)\| (.*)$}
|
||||
blame.add_line($3.rstrip, Revision.new(:identifier => $1.to_i, :author => $2.strip))
|
||||
end
|
||||
end
|
||||
return nil if $? && $?.exitstatus != 0
|
||||
blame
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
@@ -0,0 +1,362 @@
|
||||
# redMine - project management software
|
||||
# Copyright (C) 2006-2007 Jean-Philippe Lang
|
||||
#
|
||||
# This program is free software; you can redistribute it and/or
|
||||
# modify it under the terms of the GNU General Public License
|
||||
# as published by the Free Software Foundation; either version 2
|
||||
# of the License, or (at your option) any later version.
|
||||
#
|
||||
# This program is distributed in the hope that it will be useful,
|
||||
# but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
# GNU General Public License for more details.
|
||||
#
|
||||
# You should have received a copy of the GNU General Public License
|
||||
# along with this program; if not, write to the Free Software
|
||||
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
|
||||
|
||||
require 'redmine/scm/adapters/abstract_adapter'
|
||||
|
||||
module Redmine
|
||||
module Scm
|
||||
module Adapters
|
||||
class CvsAdapter < AbstractAdapter
|
||||
|
||||
# CVS executable name
|
||||
CVS_BIN = "cvs"
|
||||
|
||||
# Guidelines for the input:
|
||||
# url -> the project-path, relative to the cvsroot (eg. module name)
|
||||
# root_url -> the good old, sometimes damned, CVSROOT
|
||||
# login -> unnecessary
|
||||
# password -> unnecessary too
|
||||
def initialize(url, root_url=nil, login=nil, password=nil)
|
||||
@url = url
|
||||
@login = login if login && !login.empty?
|
||||
@password = (password || "") if @login
|
||||
#TODO: better Exception here (IllegalArgumentException)
|
||||
raise CommandFailed if root_url.blank?
|
||||
@root_url = root_url
|
||||
end
|
||||
|
||||
def root_url
|
||||
@root_url
|
||||
end
|
||||
|
||||
def url
|
||||
@url
|
||||
end
|
||||
|
||||
def info
|
||||
logger.debug "<cvs> info"
|
||||
Info.new({:root_url => @root_url, :lastrev => nil})
|
||||
end
|
||||
|
||||
def get_previous_revision(revision)
|
||||
CvsRevisionHelper.new(revision).prevRev
|
||||
end
|
||||
|
||||
# Returns an Entries collection
|
||||
# or nil if the given path doesn't exist in the repository
|
||||
# this method is used by the repository-browser (aka LIST)
|
||||
def entries(path=nil, identifier=nil)
|
||||
logger.debug "<cvs> entries '#{path}' with identifier '#{identifier}'"
|
||||
path_with_project="#{url}#{with_leading_slash(path)}"
|
||||
entries = Entries.new
|
||||
cmd = "#{CVS_BIN} -d #{root_url} rls -e"
|
||||
cmd << " -D \"#{time_to_cvstime(identifier)}\"" if identifier
|
||||
cmd << " #{shell_quote path_with_project}"
|
||||
shellout(cmd) do |io|
|
||||
io.each_line(){|line|
|
||||
fields=line.chop.split('/',-1)
|
||||
logger.debug(">>InspectLine #{fields.inspect}")
|
||||
|
||||
if fields[0]!="D"
|
||||
entries << Entry.new({:name => fields[-5],
|
||||
#:path => fields[-4].include?(path)?fields[-4]:(path + "/"+ fields[-4]),
|
||||
:path => "#{path}/#{fields[-5]}",
|
||||
:kind => 'file',
|
||||
:size => nil,
|
||||
:lastrev => Revision.new({
|
||||
:revision => fields[-4],
|
||||
:name => fields[-4],
|
||||
:time => Time.parse(fields[-3]),
|
||||
:author => ''
|
||||
})
|
||||
})
|
||||
else
|
||||
entries << Entry.new({:name => fields[1],
|
||||
:path => "#{path}/#{fields[1]}",
|
||||
:kind => 'dir',
|
||||
:size => nil,
|
||||
:lastrev => nil
|
||||
})
|
||||
end
|
||||
}
|
||||
end
|
||||
return nil if $? && $?.exitstatus != 0
|
||||
entries.sort_by_name
|
||||
end
|
||||
|
||||
STARTLOG="----------------------------"
|
||||
ENDLOG ="============================================================================="
|
||||
|
||||
# Returns all revisions found between identifier_from and identifier_to
|
||||
# in the repository. both identifier have to be dates or nil.
|
||||
# these method returns nothing but yield every result in block
|
||||
def revisions(path=nil, identifier_from=nil, identifier_to=nil, options={}, &block)
|
||||
logger.debug "<cvs> revisions path:'#{path}',identifier_from #{identifier_from}, identifier_to #{identifier_to}"
|
||||
|
||||
path_with_project="#{url}#{with_leading_slash(path)}"
|
||||
cmd = "#{CVS_BIN} -d #{root_url} rlog"
|
||||
cmd << " -d\">#{time_to_cvstime(identifier_from)}\"" if identifier_from
|
||||
cmd << " #{shell_quote path_with_project}"
|
||||
shellout(cmd) do |io|
|
||||
state="entry_start"
|
||||
|
||||
commit_log=String.new
|
||||
revision=nil
|
||||
date=nil
|
||||
author=nil
|
||||
entry_path=nil
|
||||
entry_name=nil
|
||||
file_state=nil
|
||||
branch_map=nil
|
||||
|
||||
io.each_line() do |line|
|
||||
|
||||
if state!="revision" && /^#{ENDLOG}/ =~ line
|
||||
commit_log=String.new
|
||||
revision=nil
|
||||
state="entry_start"
|
||||
end
|
||||
|
||||
if state=="entry_start"
|
||||
branch_map=Hash.new
|
||||
if /^RCS file: #{Regexp.escape(root_url_path)}\/#{Regexp.escape(path_with_project)}(.+),v$/ =~ line
|
||||
entry_path = normalize_cvs_path($1)
|
||||
entry_name = normalize_path(File.basename($1))
|
||||
logger.debug("Path #{entry_path} <=> Name #{entry_name}")
|
||||
elsif /^head: (.+)$/ =~ line
|
||||
entry_headRev = $1 #unless entry.nil?
|
||||
elsif /^symbolic names:/ =~ line
|
||||
state="symbolic" #unless entry.nil?
|
||||
elsif /^#{STARTLOG}/ =~ line
|
||||
commit_log=String.new
|
||||
state="revision"
|
||||
end
|
||||
next
|
||||
elsif state=="symbolic"
|
||||
if /^(.*):\s(.*)/ =~ (line.strip)
|
||||
branch_map[$1]=$2
|
||||
else
|
||||
state="tags"
|
||||
next
|
||||
end
|
||||
elsif state=="tags"
|
||||
if /^#{STARTLOG}/ =~ line
|
||||
commit_log = ""
|
||||
state="revision"
|
||||
elsif /^#{ENDLOG}/ =~ line
|
||||
state="head"
|
||||
end
|
||||
next
|
||||
elsif state=="revision"
|
||||
if /^#{ENDLOG}/ =~ line || /^#{STARTLOG}/ =~ line
|
||||
if revision
|
||||
|
||||
revHelper=CvsRevisionHelper.new(revision)
|
||||
revBranch="HEAD"
|
||||
|
||||
branch_map.each() do |branch_name,branch_point|
|
||||
if revHelper.is_in_branch_with_symbol(branch_point)
|
||||
revBranch=branch_name
|
||||
end
|
||||
end
|
||||
|
||||
logger.debug("********** YIELD Revision #{revision}::#{revBranch}")
|
||||
|
||||
yield Revision.new({
|
||||
:time => date,
|
||||
:author => author,
|
||||
:message=>commit_log.chomp,
|
||||
:paths => [{
|
||||
:revision => revision,
|
||||
:branch=> revBranch,
|
||||
:path=>entry_path,
|
||||
:name=>entry_name,
|
||||
:kind=>'file',
|
||||
:action=>file_state
|
||||
}]
|
||||
})
|
||||
end
|
||||
|
||||
commit_log=String.new
|
||||
revision=nil
|
||||
|
||||
if /^#{ENDLOG}/ =~ line
|
||||
state="entry_start"
|
||||
end
|
||||
next
|
||||
end
|
||||
|
||||
if /^branches: (.+)$/ =~ line
|
||||
#TODO: version.branch = $1
|
||||
elsif /^revision (\d+(?:\.\d+)+).*$/ =~ line
|
||||
revision = $1
|
||||
elsif /^date:\s+(\d+.\d+.\d+\s+\d+:\d+:\d+)/ =~ line
|
||||
date = Time.parse($1)
|
||||
author = /author: ([^;]+)/.match(line)[1]
|
||||
file_state = /state: ([^;]+)/.match(line)[1]
|
||||
#TODO: linechanges only available in CVS.... maybe a feature our SVN implementation. i'm sure, they are
|
||||
# useful for stats or something else
|
||||
# linechanges =/lines: \+(\d+) -(\d+)/.match(line)
|
||||
# unless linechanges.nil?
|
||||
# version.line_plus = linechanges[1]
|
||||
# version.line_minus = linechanges[2]
|
||||
# else
|
||||
# version.line_plus = 0
|
||||
# version.line_minus = 0
|
||||
# end
|
||||
else
|
||||
commit_log << line unless line =~ /^\*\*\* empty log message \*\*\*/
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
def diff(path, identifier_from, identifier_to=nil)
|
||||
logger.debug "<cvs> diff path:'#{path}',identifier_from #{identifier_from}, identifier_to #{identifier_to}"
|
||||
path_with_project="#{url}#{with_leading_slash(path)}"
|
||||
cmd = "#{CVS_BIN} -d #{root_url} rdiff -u -r#{identifier_to} -r#{identifier_from} #{shell_quote path_with_project}"
|
||||
diff = []
|
||||
shellout(cmd) do |io|
|
||||
io.each_line do |line|
|
||||
diff << line
|
||||
end
|
||||
end
|
||||
return nil if $? && $?.exitstatus != 0
|
||||
diff
|
||||
end
|
||||
|
||||
def cat(path, identifier=nil)
|
||||
identifier = (identifier) ? identifier : "HEAD"
|
||||
logger.debug "<cvs> cat path:'#{path}',identifier #{identifier}"
|
||||
path_with_project="#{url}#{with_leading_slash(path)}"
|
||||
cmd = "#{CVS_BIN} -d #{root_url} co"
|
||||
cmd << " -D \"#{time_to_cvstime(identifier)}\"" if identifier
|
||||
cmd << " -p #{shell_quote path_with_project}"
|
||||
cat = nil
|
||||
shellout(cmd) do |io|
|
||||
cat = io.read
|
||||
end
|
||||
return nil if $? && $?.exitstatus != 0
|
||||
cat
|
||||
end
|
||||
|
||||
def annotate(path, identifier=nil)
|
||||
identifier = (identifier) ? identifier : "HEAD"
|
||||
logger.debug "<cvs> annotate path:'#{path}',identifier #{identifier}"
|
||||
path_with_project="#{url}#{with_leading_slash(path)}"
|
||||
cmd = "#{CVS_BIN} -d #{root_url} rannotate -r#{identifier} #{shell_quote path_with_project}"
|
||||
blame = Annotate.new
|
||||
shellout(cmd) do |io|
|
||||
io.each_line do |line|
|
||||
next unless line =~ %r{^([\d\.]+)\s+\(([^\)]+)\s+[^\)]+\):\s(.*)$}
|
||||
blame.add_line($3.rstrip, Revision.new(:revision => $1, :author => $2.strip))
|
||||
end
|
||||
end
|
||||
return nil if $? && $?.exitstatus != 0
|
||||
blame
|
||||
end
|
||||
|
||||
private
|
||||
|
||||
# Returns the root url without the connexion string
|
||||
# :pserver:anonymous@foo.bar:/path => /path
|
||||
# :ext:cvsservername:/path => /path
|
||||
def root_url_path
|
||||
root_url.to_s.gsub(/^:.+:\d*/, '')
|
||||
end
|
||||
|
||||
# convert a date/time into the CVS-format
|
||||
def time_to_cvstime(time)
|
||||
return nil if time.nil?
|
||||
unless time.kind_of? Time
|
||||
time = Time.parse(time)
|
||||
end
|
||||
return time.strftime("%Y-%m-%d %H:%M:%S")
|
||||
end
|
||||
|
||||
def normalize_cvs_path(path)
|
||||
normalize_path(path.gsub(/Attic\//,''))
|
||||
end
|
||||
|
||||
def normalize_path(path)
|
||||
path.sub(/^(\/)*(.*)/,'\2').sub(/(.*)(,v)+/,'\1')
|
||||
end
|
||||
end
|
||||
|
||||
class CvsRevisionHelper
|
||||
attr_accessor :complete_rev, :revision, :base, :branchid
|
||||
|
||||
def initialize(complete_rev)
|
||||
@complete_rev = complete_rev
|
||||
parseRevision()
|
||||
end
|
||||
|
||||
def branchPoint
|
||||
return @base
|
||||
end
|
||||
|
||||
def branchVersion
|
||||
if isBranchRevision
|
||||
return @base+"."+@branchid
|
||||
end
|
||||
return @base
|
||||
end
|
||||
|
||||
def isBranchRevision
|
||||
!@branchid.nil?
|
||||
end
|
||||
|
||||
def prevRev
|
||||
unless @revision==0
|
||||
return buildRevision(@revision-1)
|
||||
end
|
||||
return buildRevision(@revision)
|
||||
end
|
||||
|
||||
def is_in_branch_with_symbol(branch_symbol)
|
||||
bpieces=branch_symbol.split(".")
|
||||
branch_start="#{bpieces[0..-3].join(".")}.#{bpieces[-1]}"
|
||||
return (branchVersion==branch_start)
|
||||
end
|
||||
|
||||
private
|
||||
def buildRevision(rev)
|
||||
if rev== 0
|
||||
@base
|
||||
elsif @branchid.nil?
|
||||
@base+"."+rev.to_s
|
||||
else
|
||||
@base+"."+@branchid+"."+rev.to_s
|
||||
end
|
||||
end
|
||||
|
||||
# Interpretiert die cvs revisionsnummern wie z.b. 1.14 oder 1.3.0.15
|
||||
def parseRevision()
|
||||
pieces=@complete_rev.split(".")
|
||||
@revision=pieces.last.to_i
|
||||
baseSize=1
|
||||
baseSize+=(pieces.size/2)
|
||||
@base=pieces[0..-baseSize].join(".")
|
||||
if baseSize > 2
|
||||
@branchid=pieces[-2]
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
@@ -0,0 +1,189 @@
|
||||
# redMine - project management software
|
||||
# Copyright (C) 2006-2007 Jean-Philippe Lang
|
||||
#
|
||||
# This program is free software; you can redistribute it and/or
|
||||
# modify it under the terms of the GNU General Public License
|
||||
# as published by the Free Software Foundation; either version 2
|
||||
# of the License, or (at your option) any later version.
|
||||
#
|
||||
# This program is distributed in the hope that it will be useful,
|
||||
# but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
# GNU General Public License for more details.
|
||||
#
|
||||
# You should have received a copy of the GNU General Public License
|
||||
# along with this program; if not, write to the Free Software
|
||||
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
|
||||
|
||||
require 'redmine/scm/adapters/abstract_adapter'
|
||||
require 'rexml/document'
|
||||
|
||||
module Redmine
|
||||
module Scm
|
||||
module Adapters
|
||||
class DarcsAdapter < AbstractAdapter
|
||||
# Darcs executable name
|
||||
DARCS_BIN = "darcs"
|
||||
|
||||
class << self
|
||||
def client_version
|
||||
@@client_version ||= (darcs_binary_version || [])
|
||||
end
|
||||
|
||||
def darcs_binary_version
|
||||
cmd = "#{DARCS_BIN} --version"
|
||||
version = nil
|
||||
shellout(cmd) do |io|
|
||||
# Read darcs version in first returned line
|
||||
if m = io.gets.match(%r{((\d+\.)+\d+)})
|
||||
version = m[0].scan(%r{\d+}).collect(&:to_i)
|
||||
end
|
||||
end
|
||||
return nil if $? && $?.exitstatus != 0
|
||||
version
|
||||
end
|
||||
end
|
||||
|
||||
def initialize(url, root_url=nil, login=nil, password=nil)
|
||||
@url = url
|
||||
@root_url = url
|
||||
end
|
||||
|
||||
def supports_cat?
|
||||
# cat supported in darcs 2.0.0 and higher
|
||||
self.class.client_version_above?([2, 0, 0])
|
||||
end
|
||||
|
||||
# Get info about the darcs repository
|
||||
def info
|
||||
rev = revisions(nil,nil,nil,{:limit => 1})
|
||||
rev ? Info.new({:root_url => @url, :lastrev => rev.last}) : nil
|
||||
end
|
||||
|
||||
# Returns an Entries collection
|
||||
# or nil if the given path doesn't exist in the repository
|
||||
def entries(path=nil, identifier=nil)
|
||||
path_prefix = (path.blank? ? '' : "#{path}/")
|
||||
path = '.' if path.blank?
|
||||
entries = Entries.new
|
||||
cmd = "#{DARCS_BIN} annotate --repodir #{@url} --xml-output"
|
||||
cmd << " --match \"hash #{identifier}\"" if identifier
|
||||
cmd << " #{path}"
|
||||
shellout(cmd) do |io|
|
||||
begin
|
||||
doc = REXML::Document.new(io)
|
||||
if doc.root.name == 'directory'
|
||||
doc.elements.each('directory/*') do |element|
|
||||
next unless ['file', 'directory'].include? element.name
|
||||
entries << entry_from_xml(element, path_prefix)
|
||||
end
|
||||
elsif doc.root.name == 'file'
|
||||
entries << entry_from_xml(doc.root, path_prefix)
|
||||
end
|
||||
rescue
|
||||
end
|
||||
end
|
||||
return nil if $? && $?.exitstatus != 0
|
||||
entries.sort_by_name
|
||||
end
|
||||
|
||||
def revisions(path=nil, identifier_from=nil, identifier_to=nil, options={})
|
||||
path = '.' if path.blank?
|
||||
revisions = Revisions.new
|
||||
cmd = "#{DARCS_BIN} changes --repodir #{@url} --xml-output"
|
||||
cmd << " --from-match \"hash #{identifier_from}\"" if identifier_from
|
||||
cmd << " --last #{options[:limit].to_i}" if options[:limit]
|
||||
shellout(cmd) do |io|
|
||||
begin
|
||||
doc = REXML::Document.new(io)
|
||||
doc.elements.each("changelog/patch") do |patch|
|
||||
message = patch.elements['name'].text
|
||||
message << "\n" + patch.elements['comment'].text.gsub(/\*\*\*END OF DESCRIPTION\*\*\*.*\z/m, '') if patch.elements['comment']
|
||||
revisions << Revision.new({:identifier => nil,
|
||||
:author => patch.attributes['author'],
|
||||
:scmid => patch.attributes['hash'],
|
||||
:time => Time.parse(patch.attributes['local_date']),
|
||||
:message => message,
|
||||
:paths => (options[:with_path] ? get_paths_for_patch(patch.attributes['hash']) : nil)
|
||||
})
|
||||
end
|
||||
rescue
|
||||
end
|
||||
end
|
||||
return nil if $? && $?.exitstatus != 0
|
||||
revisions
|
||||
end
|
||||
|
||||
def diff(path, identifier_from, identifier_to=nil)
|
||||
path = '*' if path.blank?
|
||||
cmd = "#{DARCS_BIN} diff --repodir #{@url}"
|
||||
if identifier_to.nil?
|
||||
cmd << " --match \"hash #{identifier_from}\""
|
||||
else
|
||||
cmd << " --to-match \"hash #{identifier_from}\""
|
||||
cmd << " --from-match \"hash #{identifier_to}\""
|
||||
end
|
||||
cmd << " -u #{path}"
|
||||
diff = []
|
||||
shellout(cmd) do |io|
|
||||
io.each_line do |line|
|
||||
diff << line
|
||||
end
|
||||
end
|
||||
return nil if $? && $?.exitstatus != 0
|
||||
diff
|
||||
end
|
||||
|
||||
def cat(path, identifier=nil)
|
||||
cmd = "#{DARCS_BIN} show content --repodir #{@url}"
|
||||
cmd << " --match \"hash #{identifier}\"" if identifier
|
||||
cmd << " #{shell_quote path}"
|
||||
cat = nil
|
||||
shellout(cmd) do |io|
|
||||
io.binmode
|
||||
cat = io.read
|
||||
end
|
||||
return nil if $? && $?.exitstatus != 0
|
||||
cat
|
||||
end
|
||||
|
||||
private
|
||||
|
||||
def entry_from_xml(element, path_prefix)
|
||||
Entry.new({:name => element.attributes['name'],
|
||||
:path => path_prefix + element.attributes['name'],
|
||||
:kind => element.name == 'file' ? 'file' : 'dir',
|
||||
:size => nil,
|
||||
:lastrev => Revision.new({
|
||||
:identifier => nil,
|
||||
:scmid => element.elements['modified'].elements['patch'].attributes['hash']
|
||||
})
|
||||
})
|
||||
end
|
||||
|
||||
# Retrieve changed paths for a single patch
|
||||
def get_paths_for_patch(hash)
|
||||
cmd = "#{DARCS_BIN} annotate --repodir #{@url} --summary --xml-output"
|
||||
cmd << " --match \"hash #{hash}\" "
|
||||
paths = []
|
||||
shellout(cmd) do |io|
|
||||
begin
|
||||
# Darcs xml output has multiple root elements in this case (tested with darcs 1.0.7)
|
||||
# A root element is added so that REXML doesn't raise an error
|
||||
doc = REXML::Document.new("<fake_root>" + io.read + "</fake_root>")
|
||||
doc.elements.each('fake_root/summary/*') do |modif|
|
||||
paths << {:action => modif.name[0,1].upcase,
|
||||
:path => "/" + modif.text.chomp.gsub(/^\s*/, '')
|
||||
}
|
||||
end
|
||||
rescue
|
||||
end
|
||||
end
|
||||
paths
|
||||
rescue CommandFailed
|
||||
paths
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
@@ -0,0 +1,93 @@
|
||||
# redMine - project management software
|
||||
# Copyright (C) 2006-2007 Jean-Philippe Lang
|
||||
#
|
||||
# FileSystem adapter
|
||||
# File written by Paul Rivier, at Demotera.
|
||||
#
|
||||
# This program is free software; you can redistribute it and/or
|
||||
# modify it under the terms of the GNU General Public License
|
||||
# as published by the Free Software Foundation; either version 2
|
||||
# of the License, or (at your option) any later version.
|
||||
#
|
||||
# This program is distributed in the hope that it will be useful,
|
||||
# but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
# GNU General Public License for more details.
|
||||
#
|
||||
# You should have received a copy of the GNU General Public License
|
||||
# along with this program; if not, write to the Free Software
|
||||
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
|
||||
|
||||
require 'redmine/scm/adapters/abstract_adapter'
|
||||
require 'find'
|
||||
|
||||
module Redmine
|
||||
module Scm
|
||||
module Adapters
|
||||
class FilesystemAdapter < AbstractAdapter
|
||||
|
||||
|
||||
def initialize(url, root_url=nil, login=nil, password=nil)
|
||||
@url = with_trailling_slash(url)
|
||||
end
|
||||
|
||||
def format_path_ends(path, leading=true, trailling=true)
|
||||
path = leading ? with_leading_slash(path) :
|
||||
without_leading_slash(path)
|
||||
trailling ? with_trailling_slash(path) :
|
||||
without_trailling_slash(path)
|
||||
end
|
||||
|
||||
def info
|
||||
info = Info.new({:root_url => target(),
|
||||
:lastrev => nil
|
||||
})
|
||||
info
|
||||
rescue CommandFailed
|
||||
return nil
|
||||
end
|
||||
|
||||
def entries(path="", identifier=nil)
|
||||
entries = Entries.new
|
||||
Dir.new(target(path)).each do |e|
|
||||
relative_path = format_path_ends((format_path_ends(path,
|
||||
false,
|
||||
true) + e),
|
||||
false,false)
|
||||
target = target(relative_path)
|
||||
entries <<
|
||||
Entry.new({ :name => File.basename(e),
|
||||
# below : list unreadable files, but dont link them.
|
||||
:path => File.readable?(target) ? relative_path : "",
|
||||
:kind => (File.directory?(target) ? 'dir' : 'file'),
|
||||
:size => (File.directory?(target) ? nil : [File.size(target)].pack('l').unpack('L').first),
|
||||
:lastrev =>
|
||||
Revision.new({:time => (File.mtime(target)).localtime,
|
||||
})
|
||||
}) if File.exist?(target) and # paranoid test
|
||||
%w{file directory}.include?(File.ftype(target)) and # avoid special types
|
||||
not File.basename(e).match(/^\.+$/) # avoid . and ..
|
||||
end
|
||||
entries.sort_by_name
|
||||
end
|
||||
|
||||
def cat(path, identifier=nil)
|
||||
File.new(target(path), "rb").read
|
||||
end
|
||||
|
||||
private
|
||||
|
||||
# AbstractAdapter::target is implicitly made to quote paths.
|
||||
# Here we do not shell-out, so we do not want quotes.
|
||||
def target(path=nil)
|
||||
#Prevent the use of ..
|
||||
if path and !path.match(/(^|\/)\.\.(\/|$)/)
|
||||
return "#{self.url}#{without_leading_slash(path)}"
|
||||
end
|
||||
return self.url
|
||||
end
|
||||
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
@@ -0,0 +1,270 @@
|
||||
# redMine - project management software
|
||||
# Copyright (C) 2006-2007 Jean-Philippe Lang
|
||||
#
|
||||
# This program is free software; you can redistribute it and/or
|
||||
# modify it under the terms of the GNU General Public License
|
||||
# as published by the Free Software Foundation; either version 2
|
||||
# of the License, or (at your option) any later version.
|
||||
#
|
||||
# This program is distributed in the hope that it will be useful,
|
||||
# but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
# GNU General Public License for more details.
|
||||
#
|
||||
# You should have received a copy of the GNU General Public License
|
||||
# along with this program; if not, write to the Free Software
|
||||
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
|
||||
|
||||
require 'redmine/scm/adapters/abstract_adapter'
|
||||
|
||||
module Redmine
|
||||
module Scm
|
||||
module Adapters
|
||||
class GitAdapter < AbstractAdapter
|
||||
|
||||
# Git executable name
|
||||
GIT_BIN = "git"
|
||||
|
||||
# Get the revision of a particuliar file
|
||||
def get_rev (rev,path)
|
||||
|
||||
if rev != 'latest' && !rev.nil?
|
||||
cmd="#{GIT_BIN} --git-dir #{target('')} show --date=iso --pretty=fuller #{shell_quote rev} -- #{shell_quote path}"
|
||||
else
|
||||
@branch ||= shellout("#{GIT_BIN} --git-dir #{target('')} branch") { |io| io.grep(/\*/)[0].strip.match(/\* (.*)/)[1] }
|
||||
cmd="#{GIT_BIN} --git-dir #{target('')} log --date=iso --pretty=fuller -1 #{@branch} -- #{shell_quote path}"
|
||||
end
|
||||
rev=[]
|
||||
i=0
|
||||
shellout(cmd) do |io|
|
||||
files=[]
|
||||
changeset = {}
|
||||
parsing_descr = 0 #0: not parsing desc or files, 1: parsing desc, 2: parsing files
|
||||
|
||||
io.each_line do |line|
|
||||
if line =~ /^commit ([0-9a-f]{40})$/
|
||||
key = "commit"
|
||||
value = $1
|
||||
if (parsing_descr == 1 || parsing_descr == 2)
|
||||
parsing_descr = 0
|
||||
rev = Revision.new({:identifier => changeset[:commit],
|
||||
:scmid => changeset[:commit],
|
||||
:author => changeset[:author],
|
||||
:time => Time.parse(changeset[:date]),
|
||||
:message => changeset[:description],
|
||||
:paths => files
|
||||
})
|
||||
changeset = {}
|
||||
files = []
|
||||
end
|
||||
changeset[:commit] = $1
|
||||
elsif (parsing_descr == 0) && line =~ /^(\w+):\s*(.*)$/
|
||||
key = $1
|
||||
value = $2
|
||||
if key == "Author"
|
||||
changeset[:author] = value
|
||||
elsif key == "CommitDate"
|
||||
changeset[:date] = value
|
||||
end
|
||||
elsif (parsing_descr == 0) && line.chomp.to_s == ""
|
||||
parsing_descr = 1
|
||||
changeset[:description] = ""
|
||||
elsif (parsing_descr == 1 || parsing_descr == 2) && line =~ /^:\d+\s+\d+\s+[0-9a-f.]+\s+[0-9a-f.]+\s+(\w)\s+(.+)$/
|
||||
parsing_descr = 2
|
||||
fileaction = $1
|
||||
filepath = $2
|
||||
files << {:action => fileaction, :path => filepath}
|
||||
elsif (parsing_descr == 1) && line.chomp.to_s == ""
|
||||
parsing_descr = 2
|
||||
elsif (parsing_descr == 1)
|
||||
changeset[:description] << line
|
||||
end
|
||||
end
|
||||
rev = Revision.new({:identifier => changeset[:commit],
|
||||
:scmid => changeset[:commit],
|
||||
:author => changeset[:author],
|
||||
:time => (changeset[:date] ? Time.parse(changeset[:date]) : nil),
|
||||
:message => changeset[:description],
|
||||
:paths => files
|
||||
})
|
||||
|
||||
end
|
||||
|
||||
get_rev('latest',path) if rev == []
|
||||
|
||||
return nil if $? && $?.exitstatus != 0
|
||||
return rev
|
||||
end
|
||||
|
||||
def info
|
||||
revs = revisions(url,nil,nil,{:limit => 1})
|
||||
if revs && revs.any?
|
||||
Info.new(:root_url => url, :lastrev => revs.first)
|
||||
else
|
||||
nil
|
||||
end
|
||||
rescue Errno::ENOENT => e
|
||||
return nil
|
||||
end
|
||||
|
||||
def entries(path=nil, identifier=nil)
|
||||
path ||= ''
|
||||
entries = Entries.new
|
||||
cmd = "#{GIT_BIN} --git-dir #{target('')} ls-tree -l "
|
||||
cmd << shell_quote("HEAD:" + path) if identifier.nil?
|
||||
cmd << shell_quote(identifier + ":" + path) if identifier
|
||||
shellout(cmd) do |io|
|
||||
io.each_line do |line|
|
||||
e = line.chomp.to_s
|
||||
if e =~ /^\d+\s+(\w+)\s+([0-9a-f]{40})\s+([0-9-]+)\s+(.+)$/
|
||||
type = $1
|
||||
sha = $2
|
||||
size = $3
|
||||
name = $4
|
||||
entries << Entry.new({:name => name,
|
||||
:path => (path.empty? ? name : "#{path}/#{name}"),
|
||||
:kind => ((type == "tree") ? 'dir' : 'file'),
|
||||
:size => ((type == "tree") ? nil : size),
|
||||
:lastrev => get_rev(identifier,(path.empty? ? name : "#{path}/#{name}"))
|
||||
|
||||
}) unless entries.detect{|entry| entry.name == name}
|
||||
end
|
||||
end
|
||||
end
|
||||
return nil if $? && $?.exitstatus != 0
|
||||
entries.sort_by_name
|
||||
end
|
||||
|
||||
def revisions(path, identifier_from, identifier_to, options={})
|
||||
revisions = Revisions.new
|
||||
cmd = "#{GIT_BIN} --git-dir #{target('')} log --raw --date=iso --pretty=fuller"
|
||||
cmd << " --reverse" if options[:reverse]
|
||||
cmd << " -n #{options[:limit].to_i} " if (!options.nil?) && options[:limit]
|
||||
cmd << " #{shell_quote(identifier_from + '..')} " if identifier_from
|
||||
cmd << " #{shell_quote identifier_to} " if identifier_to
|
||||
shellout(cmd) do |io|
|
||||
files=[]
|
||||
changeset = {}
|
||||
parsing_descr = 0 #0: not parsing desc or files, 1: parsing desc, 2: parsing files
|
||||
revno = 1
|
||||
|
||||
io.each_line do |line|
|
||||
if line =~ /^commit ([0-9a-f]{40})$/
|
||||
key = "commit"
|
||||
value = $1
|
||||
if (parsing_descr == 1 || parsing_descr == 2)
|
||||
parsing_descr = 0
|
||||
revision = Revision.new({:identifier => changeset[:commit],
|
||||
:scmid => changeset[:commit],
|
||||
:author => changeset[:author],
|
||||
:time => Time.parse(changeset[:date]),
|
||||
:message => changeset[:description],
|
||||
:paths => files
|
||||
})
|
||||
if block_given?
|
||||
yield revision
|
||||
else
|
||||
revisions << revision
|
||||
end
|
||||
changeset = {}
|
||||
files = []
|
||||
revno = revno + 1
|
||||
end
|
||||
changeset[:commit] = $1
|
||||
elsif (parsing_descr == 0) && line =~ /^(\w+):\s*(.*)$/
|
||||
key = $1
|
||||
value = $2
|
||||
if key == "Author"
|
||||
changeset[:author] = value
|
||||
elsif key == "CommitDate"
|
||||
changeset[:date] = value
|
||||
end
|
||||
elsif (parsing_descr == 0) && line.chomp.to_s == ""
|
||||
parsing_descr = 1
|
||||
changeset[:description] = ""
|
||||
elsif (parsing_descr == 1 || parsing_descr == 2) && line =~ /^:\d+\s+\d+\s+[0-9a-f.]+\s+[0-9a-f.]+\s+(\w)\s+(.+)$/
|
||||
parsing_descr = 2
|
||||
fileaction = $1
|
||||
filepath = $2
|
||||
files << {:action => fileaction, :path => filepath}
|
||||
elsif (parsing_descr == 1) && line.chomp.to_s == ""
|
||||
parsing_descr = 2
|
||||
elsif (parsing_descr == 1)
|
||||
changeset[:description] << line[4..-1]
|
||||
end
|
||||
end
|
||||
|
||||
if changeset[:commit]
|
||||
revision = Revision.new({:identifier => changeset[:commit],
|
||||
:scmid => changeset[:commit],
|
||||
:author => changeset[:author],
|
||||
:time => Time.parse(changeset[:date]),
|
||||
:message => changeset[:description],
|
||||
:paths => files
|
||||
})
|
||||
if block_given?
|
||||
yield revision
|
||||
else
|
||||
revisions << revision
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
return nil if $? && $?.exitstatus != 0
|
||||
revisions
|
||||
end
|
||||
|
||||
def diff(path, identifier_from, identifier_to=nil)
|
||||
path ||= ''
|
||||
if !identifier_to
|
||||
identifier_to = nil
|
||||
end
|
||||
|
||||
cmd = "#{GIT_BIN} --git-dir #{target('')} show #{shell_quote identifier_from}" if identifier_to.nil?
|
||||
cmd = "#{GIT_BIN} --git-dir #{target('')} diff #{shell_quote identifier_to} #{shell_quote identifier_from}" if !identifier_to.nil?
|
||||
cmd << " -- #{shell_quote path}" unless path.empty?
|
||||
diff = []
|
||||
shellout(cmd) do |io|
|
||||
io.each_line do |line|
|
||||
diff << line
|
||||
end
|
||||
end
|
||||
return nil if $? && $?.exitstatus != 0
|
||||
diff
|
||||
end
|
||||
|
||||
def annotate(path, identifier=nil)
|
||||
identifier = 'HEAD' if identifier.blank?
|
||||
cmd = "#{GIT_BIN} --git-dir #{target('')} blame -l #{shell_quote identifier} -- #{shell_quote path}"
|
||||
blame = Annotate.new
|
||||
content = nil
|
||||
shellout(cmd) { |io| io.binmode; content = io.read }
|
||||
return nil if $? && $?.exitstatus != 0
|
||||
# git annotates binary files
|
||||
return nil if content.is_binary_data?
|
||||
content.split("\n").each do |line|
|
||||
next unless line =~ /([0-9a-f]{39,40})\s\((\w*)[^\)]*\)(.*)/
|
||||
blame.add_line($3.rstrip, Revision.new(:identifier => $1, :author => $2.strip))
|
||||
end
|
||||
blame
|
||||
end
|
||||
|
||||
def cat(path, identifier=nil)
|
||||
if identifier.nil?
|
||||
identifier = 'HEAD'
|
||||
end
|
||||
cmd = "#{GIT_BIN} --git-dir #{target('')} show #{shell_quote(identifier + ':' + path)}"
|
||||
cat = nil
|
||||
shellout(cmd) do |io|
|
||||
io.binmode
|
||||
cat = io.read
|
||||
end
|
||||
return nil if $? && $?.exitstatus != 0
|
||||
cat
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
end
|
||||
|
||||
@@ -0,0 +1,12 @@
|
||||
changeset = 'This template must be used with --debug option\n'
|
||||
changeset_quiet = 'This template must be used with --debug option\n'
|
||||
changeset_verbose = 'This template must be used with --debug option\n'
|
||||
changeset_debug = '<logentry revision="{rev}" node="{node|short}">\n<author>{author|escape}</author>\n<date>{date|isodate}</date>\n<paths>\n{files}{file_adds}{file_dels}{file_copies}</paths>\n<msg>{desc|escape}</msg>\n{tags}</logentry>\n\n'
|
||||
|
||||
file = '<path action="M">{file|escape}</path>\n'
|
||||
file_add = '<path action="A">{file_add|escape}</path>\n'
|
||||
file_del = '<path action="D">{file_del|escape}</path>\n'
|
||||
file_copy = '<path-copied copyfrom-path="{source|escape}">{name|urlescape}</path-copied>\n'
|
||||
tag = '<tag>{tag|escape}</tag>\n'
|
||||
header='<?xml version="1.0" encoding="UTF-8" ?>\n<log>\n\n'
|
||||
# footer="</log>"
|
||||
@@ -0,0 +1,12 @@
|
||||
changeset = 'This template must be used with --debug option\n'
|
||||
changeset_quiet = 'This template must be used with --debug option\n'
|
||||
changeset_verbose = 'This template must be used with --debug option\n'
|
||||
changeset_debug = '<logentry revision="{rev}" node="{node|short}">\n<author>{author|escape}</author>\n<date>{date|isodate}</date>\n<paths>\n{file_mods}{file_adds}{file_dels}{file_copies}</paths>\n<msg>{desc|escape}</msg>\n{tags}</logentry>\n\n'
|
||||
|
||||
file_mod = '<path action="M">{file_mod|escape}</path>\n'
|
||||
file_add = '<path action="A">{file_add|escape}</path>\n'
|
||||
file_del = '<path action="D">{file_del|escape}</path>\n'
|
||||
file_copy = '<path-copied copyfrom-path="{source|escape}">{name|urlescape}</path-copied>\n'
|
||||
tag = '<tag>{tag|escape}</tag>\n'
|
||||
header='<?xml version="1.0" encoding="UTF-8" ?>\n<log>\n\n'
|
||||
# footer="</log>"
|
||||
@@ -0,0 +1,205 @@
|
||||
# redMine - project management software
|
||||
# Copyright (C) 2006-2007 Jean-Philippe Lang
|
||||
#
|
||||
# This program is free software; you can redistribute it and/or
|
||||
# modify it under the terms of the GNU General Public License
|
||||
# as published by the Free Software Foundation; either version 2
|
||||
# of the License, or (at your option) any later version.
|
||||
#
|
||||
# This program is distributed in the hope that it will be useful,
|
||||
# but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
# GNU General Public License for more details.
|
||||
#
|
||||
# You should have received a copy of the GNU General Public License
|
||||
# along with this program; if not, write to the Free Software
|
||||
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
|
||||
|
||||
require 'redmine/scm/adapters/abstract_adapter'
|
||||
|
||||
module Redmine
|
||||
module Scm
|
||||
module Adapters
|
||||
class MercurialAdapter < AbstractAdapter
|
||||
|
||||
# Mercurial executable name
|
||||
HG_BIN = "hg"
|
||||
TEMPLATES_DIR = File.dirname(__FILE__) + "/mercurial"
|
||||
TEMPLATE_NAME = "hg-template"
|
||||
TEMPLATE_EXTENSION = "tmpl"
|
||||
|
||||
class << self
|
||||
def client_version
|
||||
@@client_version ||= (hgversion || [])
|
||||
end
|
||||
|
||||
def hgversion
|
||||
# The hg version is expressed either as a
|
||||
# release number (eg 0.9.5 or 1.0) or as a revision
|
||||
# id composed of 12 hexa characters.
|
||||
theversion = hgversion_from_command_line
|
||||
if theversion.match(/^\d+(\.\d+)+/)
|
||||
theversion.split(".").collect(&:to_i)
|
||||
end
|
||||
end
|
||||
|
||||
def hgversion_from_command_line
|
||||
%x{#{HG_BIN} --version}.match(/\(version (.*)\)/)[1]
|
||||
end
|
||||
|
||||
def template_path
|
||||
@@template_path ||= template_path_for(client_version)
|
||||
end
|
||||
|
||||
def template_path_for(version)
|
||||
if ((version <=> [0,9,5]) > 0) || version.empty?
|
||||
ver = "1.0"
|
||||
else
|
||||
ver = "0.9.5"
|
||||
end
|
||||
"#{TEMPLATES_DIR}/#{TEMPLATE_NAME}-#{ver}.#{TEMPLATE_EXTENSION}"
|
||||
end
|
||||
end
|
||||
|
||||
def info
|
||||
cmd = "#{HG_BIN} -R #{target('')} root"
|
||||
root_url = nil
|
||||
shellout(cmd) do |io|
|
||||
root_url = io.gets
|
||||
end
|
||||
return nil if $? && $?.exitstatus != 0
|
||||
info = Info.new({:root_url => root_url.chomp,
|
||||
:lastrev => revisions(nil,nil,nil,{:limit => 1}).last
|
||||
})
|
||||
info
|
||||
rescue CommandFailed
|
||||
return nil
|
||||
end
|
||||
|
||||
def entries(path=nil, identifier=nil)
|
||||
path ||= ''
|
||||
entries = Entries.new
|
||||
cmd = "#{HG_BIN} -R #{target('')} --cwd #{target('')} locate"
|
||||
cmd << " -r " + (identifier ? identifier.to_s : "tip")
|
||||
cmd << " " + shell_quote("path:#{path}") unless path.empty?
|
||||
shellout(cmd) do |io|
|
||||
io.each_line do |line|
|
||||
# HG uses antislashs as separator on Windows
|
||||
line = line.gsub(/\\/, "/")
|
||||
if path.empty? or e = line.gsub!(%r{^#{with_trailling_slash(path)}},'')
|
||||
e ||= line
|
||||
e = e.chomp.split(%r{[\/\\]})
|
||||
entries << Entry.new({:name => e.first,
|
||||
:path => (path.nil? or path.empty? ? e.first : "#{with_trailling_slash(path)}#{e.first}"),
|
||||
:kind => (e.size > 1 ? 'dir' : 'file'),
|
||||
:lastrev => Revision.new
|
||||
}) unless entries.detect{|entry| entry.name == e.first}
|
||||
end
|
||||
end
|
||||
end
|
||||
return nil if $? && $?.exitstatus != 0
|
||||
entries.sort_by_name
|
||||
end
|
||||
|
||||
# Fetch the revisions by using a template file that
|
||||
# makes Mercurial produce a xml output.
|
||||
def revisions(path=nil, identifier_from=nil, identifier_to=nil, options={})
|
||||
revisions = Revisions.new
|
||||
cmd = "#{HG_BIN} --debug --encoding utf8 -R #{target('')} log -C --style #{self.class.template_path}"
|
||||
if identifier_from && identifier_to
|
||||
cmd << " -r #{identifier_from.to_i}:#{identifier_to.to_i}"
|
||||
elsif identifier_from
|
||||
cmd << " -r #{identifier_from.to_i}:"
|
||||
end
|
||||
cmd << " --limit #{options[:limit].to_i}" if options[:limit]
|
||||
cmd << " #{path}" if path
|
||||
shellout(cmd) do |io|
|
||||
begin
|
||||
# HG doesn't close the XML Document...
|
||||
doc = REXML::Document.new(io.read << "</log>")
|
||||
doc.elements.each("log/logentry") do |logentry|
|
||||
paths = []
|
||||
copies = logentry.get_elements('paths/path-copied')
|
||||
logentry.elements.each("paths/path") do |path|
|
||||
# Detect if the added file is a copy
|
||||
if path.attributes['action'] == 'A' and c = copies.find{ |e| e.text == path.text }
|
||||
from_path = c.attributes['copyfrom-path']
|
||||
from_rev = logentry.attributes['revision']
|
||||
end
|
||||
paths << {:action => path.attributes['action'],
|
||||
:path => "/#{path.text}",
|
||||
:from_path => from_path ? "/#{from_path}" : nil,
|
||||
:from_revision => from_rev ? from_rev : nil
|
||||
}
|
||||
end
|
||||
paths.sort! { |x,y| x[:path] <=> y[:path] }
|
||||
|
||||
revisions << Revision.new({:identifier => logentry.attributes['revision'],
|
||||
:scmid => logentry.attributes['node'],
|
||||
:author => (logentry.elements['author'] ? logentry.elements['author'].text : ""),
|
||||
:time => Time.parse(logentry.elements['date'].text).localtime,
|
||||
:message => logentry.elements['msg'].text,
|
||||
:paths => paths
|
||||
})
|
||||
end
|
||||
rescue
|
||||
logger.debug($!)
|
||||
end
|
||||
end
|
||||
return nil if $? && $?.exitstatus != 0
|
||||
revisions
|
||||
end
|
||||
|
||||
def diff(path, identifier_from, identifier_to=nil)
|
||||
path ||= ''
|
||||
if identifier_to
|
||||
identifier_to = identifier_to.to_i
|
||||
else
|
||||
identifier_to = identifier_from.to_i - 1
|
||||
end
|
||||
cmd = "#{HG_BIN} -R #{target('')} diff -r #{identifier_to} -r #{identifier_from} --nodates"
|
||||
cmd << " -I #{target(path)}" unless path.empty?
|
||||
diff = []
|
||||
shellout(cmd) do |io|
|
||||
io.each_line do |line|
|
||||
diff << line
|
||||
end
|
||||
end
|
||||
return nil if $? && $?.exitstatus != 0
|
||||
diff
|
||||
end
|
||||
|
||||
def cat(path, identifier=nil)
|
||||
cmd = "#{HG_BIN} -R #{target('')} cat"
|
||||
cmd << " -r " + (identifier ? identifier.to_s : "tip")
|
||||
cmd << " #{target(path)}"
|
||||
cat = nil
|
||||
shellout(cmd) do |io|
|
||||
io.binmode
|
||||
cat = io.read
|
||||
end
|
||||
return nil if $? && $?.exitstatus != 0
|
||||
cat
|
||||
end
|
||||
|
||||
def annotate(path, identifier=nil)
|
||||
path ||= ''
|
||||
cmd = "#{HG_BIN} -R #{target('')}"
|
||||
cmd << " annotate -n -u"
|
||||
cmd << " -r " + (identifier ? identifier.to_s : "tip")
|
||||
cmd << " -r #{identifier.to_i}" if identifier
|
||||
cmd << " #{target(path)}"
|
||||
blame = Annotate.new
|
||||
shellout(cmd) do |io|
|
||||
io.each_line do |line|
|
||||
next unless line =~ %r{^([^:]+)\s(\d+):(.*)$}
|
||||
blame.add_line($3.rstrip, Revision.new(:identifier => $2.to_i, :author => $1.strip))
|
||||
end
|
||||
end
|
||||
return nil if $? && $?.exitstatus != 0
|
||||
blame
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
@@ -0,0 +1,232 @@
|
||||
# redMine - project management software
|
||||
# Copyright (C) 2006-2007 Jean-Philippe Lang
|
||||
#
|
||||
# This program is free software; you can redistribute it and/or
|
||||
# modify it under the terms of the GNU General Public License
|
||||
# as published by the Free Software Foundation; either version 2
|
||||
# of the License, or (at your option) any later version.
|
||||
#
|
||||
# This program is distributed in the hope that it will be useful,
|
||||
# but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
# GNU General Public License for more details.
|
||||
#
|
||||
# You should have received a copy of the GNU General Public License
|
||||
# along with this program; if not, write to the Free Software
|
||||
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
|
||||
|
||||
require 'redmine/scm/adapters/abstract_adapter'
|
||||
require 'rexml/document'
|
||||
require 'uri'
|
||||
|
||||
module Redmine
|
||||
module Scm
|
||||
module Adapters
|
||||
class SubversionAdapter < AbstractAdapter
|
||||
|
||||
# SVN executable name
|
||||
SVN_BIN = "svn"
|
||||
|
||||
class << self
|
||||
def client_version
|
||||
@@client_version ||= (svn_binary_version || [])
|
||||
end
|
||||
|
||||
def svn_binary_version
|
||||
cmd = "#{SVN_BIN} --version"
|
||||
version = nil
|
||||
shellout(cmd) do |io|
|
||||
# Read svn version in first returned line
|
||||
if m = io.gets.match(%r{((\d+\.)+\d+)})
|
||||
version = m[0].scan(%r{\d+}).collect(&:to_i)
|
||||
end
|
||||
end
|
||||
return nil if $? && $?.exitstatus != 0
|
||||
version
|
||||
end
|
||||
end
|
||||
|
||||
# Get info about the svn repository
|
||||
def info
|
||||
cmd = "#{SVN_BIN} info --xml #{target('')}"
|
||||
cmd << credentials_string
|
||||
info = nil
|
||||
shellout(cmd) do |io|
|
||||
begin
|
||||
doc = REXML::Document.new(io)
|
||||
#root_url = doc.elements["info/entry/repository/root"].text
|
||||
info = Info.new({:root_url => doc.elements["info/entry/repository/root"].text,
|
||||
:lastrev => Revision.new({
|
||||
:identifier => doc.elements["info/entry/commit"].attributes['revision'],
|
||||
:time => Time.parse(doc.elements["info/entry/commit/date"].text).localtime,
|
||||
:author => (doc.elements["info/entry/commit/author"] ? doc.elements["info/entry/commit/author"].text : "")
|
||||
})
|
||||
})
|
||||
rescue
|
||||
end
|
||||
end
|
||||
return nil if $? && $?.exitstatus != 0
|
||||
info
|
||||
rescue CommandFailed
|
||||
return nil
|
||||
end
|
||||
|
||||
# Returns an Entries collection
|
||||
# or nil if the given path doesn't exist in the repository
|
||||
def entries(path=nil, identifier=nil)
|
||||
path ||= ''
|
||||
identifier = (identifier and identifier.to_i > 0) ? identifier.to_i : "HEAD"
|
||||
entries = Entries.new
|
||||
cmd = "#{SVN_BIN} list --xml #{target(URI.escape(path))}@#{identifier}"
|
||||
cmd << credentials_string
|
||||
shellout(cmd) do |io|
|
||||
output = io.read
|
||||
begin
|
||||
doc = REXML::Document.new(output)
|
||||
doc.elements.each("lists/list/entry") do |entry|
|
||||
commit = entry.elements['commit']
|
||||
commit_date = commit.elements['date']
|
||||
# Skip directory if there is no commit date (usually that
|
||||
# means that we don't have read access to it)
|
||||
next if entry.attributes['kind'] == 'dir' && commit_date.nil?
|
||||
name = entry.elements['name'].text
|
||||
entries << Entry.new({:name => URI.unescape(name),
|
||||
:path => ((path.empty? ? "" : "#{path}/") + name),
|
||||
:kind => entry.attributes['kind'],
|
||||
:size => ((s = entry.elements['size']) ? s.text.to_i : nil),
|
||||
:lastrev => Revision.new({
|
||||
:identifier => commit.attributes['revision'],
|
||||
:time => Time.parse(commit_date.text).localtime,
|
||||
:author => ((a = commit.elements['author']) ? a.text : nil)
|
||||
})
|
||||
})
|
||||
end
|
||||
rescue Exception => e
|
||||
logger.error("Error parsing svn output: #{e.message}")
|
||||
logger.error("Output was:\n #{output}")
|
||||
end
|
||||
end
|
||||
return nil if $? && $?.exitstatus != 0
|
||||
logger.debug("Found #{entries.size} entries in the repository for #{target(path)}") if logger && logger.debug?
|
||||
entries.sort_by_name
|
||||
end
|
||||
|
||||
def properties(path, identifier=nil)
|
||||
# proplist xml output supported in svn 1.5.0 and higher
|
||||
return nil unless self.class.client_version_above?([1, 5, 0])
|
||||
|
||||
identifier = (identifier and identifier.to_i > 0) ? identifier.to_i : "HEAD"
|
||||
cmd = "#{SVN_BIN} proplist --verbose --xml #{target(URI.escape(path))}@#{identifier}"
|
||||
cmd << credentials_string
|
||||
properties = {}
|
||||
shellout(cmd) do |io|
|
||||
output = io.read
|
||||
begin
|
||||
doc = REXML::Document.new(output)
|
||||
doc.elements.each("properties/target/property") do |property|
|
||||
properties[ property.attributes['name'] ] = property.text
|
||||
end
|
||||
rescue
|
||||
end
|
||||
end
|
||||
return nil if $? && $?.exitstatus != 0
|
||||
properties
|
||||
end
|
||||
|
||||
def revisions(path=nil, identifier_from=nil, identifier_to=nil, options={})
|
||||
path ||= ''
|
||||
identifier_from = (identifier_from and identifier_from.to_i > 0) ? identifier_from.to_i : "HEAD"
|
||||
identifier_to = (identifier_to and identifier_to.to_i > 0) ? identifier_to.to_i : 1
|
||||
revisions = Revisions.new
|
||||
cmd = "#{SVN_BIN} log --xml -r #{identifier_from}:#{identifier_to}"
|
||||
cmd << credentials_string
|
||||
cmd << " --verbose " if options[:with_paths]
|
||||
cmd << ' ' + target(URI.escape(path))
|
||||
shellout(cmd) do |io|
|
||||
begin
|
||||
doc = REXML::Document.new(io)
|
||||
doc.elements.each("log/logentry") do |logentry|
|
||||
paths = []
|
||||
logentry.elements.each("paths/path") do |path|
|
||||
paths << {:action => path.attributes['action'],
|
||||
:path => path.text,
|
||||
:from_path => path.attributes['copyfrom-path'],
|
||||
:from_revision => path.attributes['copyfrom-rev']
|
||||
}
|
||||
end
|
||||
paths.sort! { |x,y| x[:path] <=> y[:path] }
|
||||
|
||||
revisions << Revision.new({:identifier => logentry.attributes['revision'],
|
||||
:author => (logentry.elements['author'] ? logentry.elements['author'].text : ""),
|
||||
:time => Time.parse(logentry.elements['date'].text).localtime,
|
||||
:message => logentry.elements['msg'].text,
|
||||
:paths => paths
|
||||
})
|
||||
end
|
||||
rescue
|
||||
end
|
||||
end
|
||||
return nil if $? && $?.exitstatus != 0
|
||||
revisions
|
||||
end
|
||||
|
||||
def diff(path, identifier_from, identifier_to=nil, type="inline")
|
||||
path ||= ''
|
||||
identifier_from = (identifier_from and identifier_from.to_i > 0) ? identifier_from.to_i : ''
|
||||
identifier_to = (identifier_to and identifier_to.to_i > 0) ? identifier_to.to_i : (identifier_from.to_i - 1)
|
||||
|
||||
cmd = "#{SVN_BIN} diff -r "
|
||||
cmd << "#{identifier_to}:"
|
||||
cmd << "#{identifier_from}"
|
||||
cmd << " #{target(URI.escape(path))}@#{identifier_from}"
|
||||
cmd << credentials_string
|
||||
diff = []
|
||||
shellout(cmd) do |io|
|
||||
io.each_line do |line|
|
||||
diff << line
|
||||
end
|
||||
end
|
||||
return nil if $? && $?.exitstatus != 0
|
||||
diff
|
||||
end
|
||||
|
||||
def cat(path, identifier=nil)
|
||||
identifier = (identifier and identifier.to_i > 0) ? identifier.to_i : "HEAD"
|
||||
cmd = "#{SVN_BIN} cat #{target(URI.escape(path))}@#{identifier}"
|
||||
cmd << credentials_string
|
||||
cat = nil
|
||||
shellout(cmd) do |io|
|
||||
io.binmode
|
||||
cat = io.read
|
||||
end
|
||||
return nil if $? && $?.exitstatus != 0
|
||||
cat
|
||||
end
|
||||
|
||||
def annotate(path, identifier=nil)
|
||||
identifier = (identifier and identifier.to_i > 0) ? identifier.to_i : "HEAD"
|
||||
cmd = "#{SVN_BIN} blame #{target(URI.escape(path))}@#{identifier}"
|
||||
cmd << credentials_string
|
||||
blame = Annotate.new
|
||||
shellout(cmd) do |io|
|
||||
io.each_line do |line|
|
||||
next unless line =~ %r{^\s*(\d+)\s*(\S+)\s(.*)$}
|
||||
blame.add_line($3.rstrip, Revision.new(:identifier => $1.to_i, :author => $2.strip))
|
||||
end
|
||||
end
|
||||
return nil if $? && $?.exitstatus != 0
|
||||
blame
|
||||
end
|
||||
|
||||
private
|
||||
|
||||
def credentials_string
|
||||
str = ''
|
||||
str << " --username #{shell_quote(@login)}" unless @login.blank?
|
||||
str << " --password #{shell_quote(@password)}" unless @login.blank? || @password.blank?
|
||||
str
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
@@ -0,0 +1,76 @@
|
||||
# redMine - project management software
|
||||
# Copyright (C) 2006-2007 Jean-Philippe Lang
|
||||
#
|
||||
# This program is free software; you can redistribute it and/or
|
||||
# modify it under the terms of the GNU General Public License
|
||||
# as published by the Free Software Foundation; either version 2
|
||||
# of the License, or (at your option) any later version.
|
||||
#
|
||||
# This program is distributed in the hope that it will be useful,
|
||||
# but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
# GNU General Public License for more details.
|
||||
#
|
||||
# You should have received a copy of the GNU General Public License
|
||||
# along with this program; if not, write to the Free Software
|
||||
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
|
||||
|
||||
module Redmine
|
||||
module Themes
|
||||
|
||||
# Return an array of installed themes
|
||||
def self.themes
|
||||
@@installed_themes ||= scan_themes
|
||||
end
|
||||
|
||||
# Rescan themes directory
|
||||
def self.rescan
|
||||
@@installed_themes = scan_themes
|
||||
end
|
||||
|
||||
# Return theme for given id, or nil if it's not found
|
||||
def self.theme(id)
|
||||
themes.find {|t| t.id == id}
|
||||
end
|
||||
|
||||
# Class used to represent a theme
|
||||
class Theme
|
||||
attr_reader :name, :dir, :stylesheets
|
||||
|
||||
def initialize(path)
|
||||
@dir = File.basename(path)
|
||||
@name = @dir.humanize
|
||||
@stylesheets = Dir.glob("#{path}/stylesheets/*.css").collect {|f| File.basename(f).gsub(/\.css$/, '')}
|
||||
end
|
||||
|
||||
# Directory name used as the theme id
|
||||
def id; dir end
|
||||
|
||||
def <=>(theme)
|
||||
name <=> theme.name
|
||||
end
|
||||
end
|
||||
|
||||
private
|
||||
|
||||
def self.scan_themes
|
||||
dirs = Dir.glob("#{RAILS_ROOT}/public/themes/*").select do |f|
|
||||
# A theme should at least override application.css
|
||||
File.directory?(f) && File.exist?("#{f}/stylesheets/application.css")
|
||||
end
|
||||
dirs.collect {|dir| Theme.new(dir)}.sort
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
module ApplicationHelper
|
||||
def stylesheet_path(source)
|
||||
@current_theme ||= Redmine::Themes.theme(Setting.ui_theme)
|
||||
super((@current_theme && @current_theme.stylesheets.include?(source)) ?
|
||||
"/themes/#{@current_theme.dir}/stylesheets/#{source}" : source)
|
||||
end
|
||||
|
||||
def path_to_stylesheet(source)
|
||||
stylesheet_path source
|
||||
end
|
||||
end
|
||||
@@ -0,0 +1,190 @@
|
||||
# redMine - project management software
|
||||
# Copyright (C) 2006-2008 Jean-Philippe Lang
|
||||
#
|
||||
# This program is free software; you can redistribute it and/or
|
||||
# modify it under the terms of the GNU General Public License
|
||||
# as published by the Free Software Foundation; either version 2
|
||||
# of the License, or (at your option) any later version.
|
||||
#
|
||||
# This program is distributed in the hope that it will be useful,
|
||||
# but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
# GNU General Public License for more details.
|
||||
#
|
||||
# You should have received a copy of the GNU General Public License
|
||||
# along with this program; if not, write to the Free Software
|
||||
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
|
||||
|
||||
module Redmine
|
||||
# Class used to parse unified diffs
|
||||
class UnifiedDiff < Array
|
||||
def initialize(diff, options={})
|
||||
options.assert_valid_keys(:type, :max_lines)
|
||||
diff_type = options[:type] || 'inline'
|
||||
|
||||
lines = 0
|
||||
@truncated = false
|
||||
diff_table = DiffTable.new(diff_type)
|
||||
diff.each do |line|
|
||||
if line =~ /^(---|\+\+\+) (.*)$/
|
||||
self << diff_table if diff_table.length > 1
|
||||
diff_table = DiffTable.new(diff_type)
|
||||
end
|
||||
diff_table.add_line line
|
||||
lines += 1
|
||||
if options[:max_lines] && lines > options[:max_lines]
|
||||
@truncated = true
|
||||
break
|
||||
end
|
||||
end
|
||||
self << diff_table unless diff_table.empty?
|
||||
self
|
||||
end
|
||||
|
||||
def truncated?; @truncated; end
|
||||
end
|
||||
|
||||
# Class that represents a file diff
|
||||
class DiffTable < Hash
|
||||
attr_reader :file_name, :line_num_l, :line_num_r
|
||||
|
||||
# Initialize with a Diff file and the type of Diff View
|
||||
# The type view must be inline or sbs (side_by_side)
|
||||
def initialize(type="inline")
|
||||
@parsing = false
|
||||
@nb_line = 1
|
||||
@start = false
|
||||
@before = 'same'
|
||||
@second = true
|
||||
@type = type
|
||||
end
|
||||
|
||||
# Function for add a line of this Diff
|
||||
def add_line(line)
|
||||
unless @parsing
|
||||
if line =~ /^(---|\+\+\+) (.*)$/
|
||||
@file_name = $2
|
||||
return false
|
||||
elsif line =~ /^@@ (\+|\-)(\d+)(,\d+)? (\+|\-)(\d+)(,\d+)? @@/
|
||||
@line_num_l = $2.to_i
|
||||
@line_num_r = $5.to_i
|
||||
@parsing = true
|
||||
end
|
||||
else
|
||||
if line =~ /^[^\+\-\s@\\]/
|
||||
@parsing = false
|
||||
return false
|
||||
elsif line =~ /^@@ (\+|\-)(\d+)(,\d+)? (\+|\-)(\d+)(,\d+)? @@/
|
||||
@line_num_l = $2.to_i
|
||||
@line_num_r = $5.to_i
|
||||
else
|
||||
@nb_line += 1 if parse_line(line, @type)
|
||||
end
|
||||
end
|
||||
return true
|
||||
end
|
||||
|
||||
def inspect
|
||||
puts '### DIFF TABLE ###'
|
||||
puts "file : #{file_name}"
|
||||
self.each do |d|
|
||||
d.inspect
|
||||
end
|
||||
end
|
||||
|
||||
private
|
||||
# Test if is a Side By Side type
|
||||
def sbs?(type, func)
|
||||
if @start and type == "sbs"
|
||||
if @before == func and @second
|
||||
tmp_nb_line = @nb_line
|
||||
self[tmp_nb_line] = Diff.new
|
||||
else
|
||||
@second = false
|
||||
tmp_nb_line = @start
|
||||
@start += 1
|
||||
@nb_line -= 1
|
||||
end
|
||||
else
|
||||
tmp_nb_line = @nb_line
|
||||
@start = @nb_line
|
||||
self[tmp_nb_line] = Diff.new
|
||||
@second = true
|
||||
end
|
||||
unless self[tmp_nb_line]
|
||||
@nb_line += 1
|
||||
self[tmp_nb_line] = Diff.new
|
||||
else
|
||||
self[tmp_nb_line]
|
||||
end
|
||||
end
|
||||
|
||||
# Escape the HTML for the diff
|
||||
def escapeHTML(line)
|
||||
CGI.escapeHTML(line)
|
||||
end
|
||||
|
||||
def parse_line(line, type="inline")
|
||||
if line[0, 1] == "+"
|
||||
diff = sbs? type, 'add'
|
||||
@before = 'add'
|
||||
diff.line_right = escapeHTML line[1..-1]
|
||||
diff.nb_line_right = @line_num_r
|
||||
diff.type_diff_right = 'diff_in'
|
||||
@line_num_r += 1
|
||||
true
|
||||
elsif line[0, 1] == "-"
|
||||
diff = sbs? type, 'remove'
|
||||
@before = 'remove'
|
||||
diff.line_left = escapeHTML line[1..-1]
|
||||
diff.nb_line_left = @line_num_l
|
||||
diff.type_diff_left = 'diff_out'
|
||||
@line_num_l += 1
|
||||
true
|
||||
elsif line[0, 1] =~ /\s/
|
||||
@before = 'same'
|
||||
@start = false
|
||||
diff = Diff.new
|
||||
diff.line_right = escapeHTML line[1..-1]
|
||||
diff.nb_line_right = @line_num_r
|
||||
diff.line_left = escapeHTML line[1..-1]
|
||||
diff.nb_line_left = @line_num_l
|
||||
self[@nb_line] = diff
|
||||
@line_num_l += 1
|
||||
@line_num_r += 1
|
||||
true
|
||||
elsif line[0, 1] = "\\"
|
||||
true
|
||||
else
|
||||
false
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
# A line of diff
|
||||
class Diff
|
||||
attr_accessor :nb_line_left
|
||||
attr_accessor :line_left
|
||||
attr_accessor :nb_line_right
|
||||
attr_accessor :line_right
|
||||
attr_accessor :type_diff_right
|
||||
attr_accessor :type_diff_left
|
||||
|
||||
def initialize()
|
||||
self.nb_line_left = ''
|
||||
self.nb_line_right = ''
|
||||
self.line_left = ''
|
||||
self.line_right = ''
|
||||
self.type_diff_right = ''
|
||||
self.type_diff_left = ''
|
||||
end
|
||||
|
||||
def inspect
|
||||
puts '### Start Line Diff ###'
|
||||
puts self.nb_line_left
|
||||
puts self.line_left
|
||||
puts self.nb_line_right
|
||||
puts self.line_right
|
||||
end
|
||||
end
|
||||
end
|
||||
@@ -0,0 +1,43 @@
|
||||
require 'rexml/document'
|
||||
|
||||
module Redmine
|
||||
module VERSION #:nodoc:
|
||||
MAJOR = 0
|
||||
MINOR = 8
|
||||
TINY = 0
|
||||
|
||||
# Branch values:
|
||||
# * official release: nil
|
||||
# * stable branch: stable
|
||||
# * trunk: devel
|
||||
BRANCH = 'devel'
|
||||
|
||||
def self.revision
|
||||
revision = nil
|
||||
entries_path = "#{RAILS_ROOT}/.svn/entries"
|
||||
if File.readable?(entries_path)
|
||||
begin
|
||||
f = File.open(entries_path, 'r')
|
||||
entries = f.read
|
||||
f.close
|
||||
if entries.match(%r{^\d+})
|
||||
revision = $1.to_i if entries.match(%r{^\d+\s+dir\s+(\d+)\s})
|
||||
else
|
||||
xml = REXML::Document.new(entries)
|
||||
revision = xml.elements['wc-entries'].elements[1].attributes['revision'].to_i
|
||||
end
|
||||
rescue
|
||||
# Could not find the current revision
|
||||
end
|
||||
end
|
||||
revision
|
||||
end
|
||||
|
||||
REVISION = self.revision
|
||||
ARRAY = [MAJOR, MINOR, TINY, BRANCH, REVISION].compact
|
||||
STRING = ARRAY.join('.')
|
||||
|
||||
def self.to_a; ARRAY end
|
||||
def self.to_s; STRING end
|
||||
end
|
||||
end
|
||||
@@ -0,0 +1,79 @@
|
||||
# Redmine - project management software
|
||||
# Copyright (C) 2006-2008 Jean-Philippe Lang
|
||||
#
|
||||
# This program is free software; you can redistribute it and/or
|
||||
# modify it under the terms of the GNU General Public License
|
||||
# as published by the Free Software Foundation; either version 2
|
||||
# of the License, or (at your option) any later version.
|
||||
#
|
||||
# This program is distributed in the hope that it will be useful,
|
||||
# but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
# GNU General Public License for more details.
|
||||
#
|
||||
# You should have received a copy of the GNU General Public License
|
||||
# along with this program; if not, write to the Free Software
|
||||
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
|
||||
|
||||
module Redmine
|
||||
module WikiFormatting
|
||||
@@formatters = {}
|
||||
|
||||
class << self
|
||||
def map
|
||||
yield self
|
||||
end
|
||||
|
||||
def register(name, formatter, helper)
|
||||
raise ArgumentError, "format name '#{name}' is already taken" if @@formatters[name]
|
||||
@@formatters[name.to_sym] = {:formatter => formatter, :helper => helper}
|
||||
end
|
||||
|
||||
def formatter_for(name)
|
||||
entry = @@formatters[name.to_sym]
|
||||
(entry && entry[:formatter]) || Redmine::WikiFormatting::NullFormatter::Formatter
|
||||
end
|
||||
|
||||
def helper_for(name)
|
||||
entry = @@formatters[name.to_sym]
|
||||
(entry && entry[:helper]) || Redmine::WikiFormatting::NullFormatter::Helper
|
||||
end
|
||||
|
||||
def format_names
|
||||
@@formatters.keys.map
|
||||
end
|
||||
|
||||
def to_html(format, text, options = {}, &block)
|
||||
formatter_for(format).new(text).to_html(&block)
|
||||
end
|
||||
end
|
||||
|
||||
# Default formatter module
|
||||
module NullFormatter
|
||||
class Formatter
|
||||
include ActionView::Helpers::TagHelper
|
||||
include ActionView::Helpers::TextHelper
|
||||
|
||||
def initialize(text)
|
||||
@text = text
|
||||
end
|
||||
|
||||
def to_html(*args)
|
||||
simple_format(auto_link(CGI::escapeHTML(@text)))
|
||||
end
|
||||
end
|
||||
|
||||
module Helper
|
||||
def wikitoolbar_for(field_id)
|
||||
end
|
||||
|
||||
def heads_for_wiki_formatter
|
||||
end
|
||||
|
||||
def initial_page_content(page)
|
||||
page.pretty_title.to_s
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
@@ -0,0 +1,121 @@
|
||||
# redMine - project management software
|
||||
# Copyright (C) 2006-2007 Jean-Philippe Lang
|
||||
#
|
||||
# This program is free software; you can redistribute it and/or
|
||||
# modify it under the terms of the GNU General Public License
|
||||
# as published by the Free Software Foundation; either version 2
|
||||
# of the License, or (at your option) any later version.
|
||||
#
|
||||
# This program is distributed in the hope that it will be useful,
|
||||
# but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
# GNU General Public License for more details.
|
||||
#
|
||||
# You should have received a copy of the GNU General Public License
|
||||
# along with this program; if not, write to the Free Software
|
||||
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
|
||||
|
||||
module Redmine
|
||||
module WikiFormatting
|
||||
module Macros
|
||||
module Definitions
|
||||
def exec_macro(name, obj, args)
|
||||
method_name = "macro_#{name}"
|
||||
send(method_name, obj, args) if respond_to?(method_name)
|
||||
end
|
||||
|
||||
def extract_macro_options(args, *keys)
|
||||
options = {}
|
||||
while args.last.to_s.strip =~ %r{^(.+)\=(.+)$} && keys.include?($1.downcase.to_sym)
|
||||
options[$1.downcase.to_sym] = $2
|
||||
args.pop
|
||||
end
|
||||
return [args, options]
|
||||
end
|
||||
end
|
||||
|
||||
@@available_macros = {}
|
||||
|
||||
class << self
|
||||
# Called with a block to define additional macros.
|
||||
# Macro blocks accept 2 arguments:
|
||||
# * obj: the object that is rendered
|
||||
# * args: macro arguments
|
||||
#
|
||||
# Plugins can use this method to define new macros:
|
||||
#
|
||||
# Redmine::WikiFormatting::Macros.register do
|
||||
# desc "This is my macro"
|
||||
# macro :my_macro do |obj, args|
|
||||
# "My macro output"
|
||||
# end
|
||||
# end
|
||||
def register(&block)
|
||||
class_eval(&block) if block_given?
|
||||
end
|
||||
|
||||
private
|
||||
# Defines a new macro with the given name and block.
|
||||
def macro(name, &block)
|
||||
name = name.to_sym if name.is_a?(String)
|
||||
@@available_macros[name] = @@desc || ''
|
||||
@@desc = nil
|
||||
raise "Can not create a macro without a block!" unless block_given?
|
||||
Definitions.send :define_method, "macro_#{name}".downcase, &block
|
||||
end
|
||||
|
||||
# Sets description for the next macro to be defined
|
||||
def desc(txt)
|
||||
@@desc = txt
|
||||
end
|
||||
end
|
||||
|
||||
# Builtin macros
|
||||
desc "Sample macro."
|
||||
macro :hello_world do |obj, args|
|
||||
"Hello world! Object: #{obj.class.name}, " + (args.empty? ? "Called with no argument." : "Arguments: #{args.join(', ')}")
|
||||
end
|
||||
|
||||
desc "Displays a list of all available macros, including description if available."
|
||||
macro :macro_list do
|
||||
out = ''
|
||||
@@available_macros.keys.collect(&:to_s).sort.each do |macro|
|
||||
out << content_tag('dt', content_tag('code', macro))
|
||||
out << content_tag('dd', textilizable(@@available_macros[macro.to_sym]))
|
||||
end
|
||||
content_tag('dl', out)
|
||||
end
|
||||
|
||||
desc "Displays a list of child pages. With no argument, it displays the child pages of the current wiki page. Examples:\n\n" +
|
||||
" !{{child_pages}} -- can be used from a wiki page only\n" +
|
||||
" !{{child_pages(Foo)}} -- lists all children of page Foo\n" +
|
||||
" !{{child_pages(Foo, parent=1)}} -- same as above with a link to page Foo"
|
||||
macro :child_pages do |obj, args|
|
||||
args, options = extract_macro_options(args, :parent)
|
||||
page = nil
|
||||
if args.size > 0
|
||||
page = Wiki.find_page(args.first.to_s, :project => @project)
|
||||
elsif obj.is_a?(WikiContent)
|
||||
page = obj.page
|
||||
else
|
||||
raise 'With no argument, this macro can be called from wiki pages only.'
|
||||
end
|
||||
raise 'Page not found' if page.nil? || !User.current.allowed_to?(:view_wiki_pages, page.wiki.project)
|
||||
pages = ([page] + page.descendants).group_by(&:parent_id)
|
||||
render_page_hierarchy(pages, options[:parent] ? page.parent_id : page.id)
|
||||
end
|
||||
|
||||
desc "Include a wiki page. Example:\n\n !{{include(Foo)}}\n\nor to include a page of a specific project wiki:\n\n !{{include(projectname:Foo)}}"
|
||||
macro :include do |obj, args|
|
||||
page = Wiki.find_page(args.first.to_s, :project => @project)
|
||||
raise 'Page not found' if page.nil? || !User.current.allowed_to?(:view_wiki_pages, page.wiki.project)
|
||||
@included_wiki_pages ||= []
|
||||
raise 'Circular inclusion detected' if @included_wiki_pages.include?(page.title)
|
||||
@included_wiki_pages << page.title
|
||||
out = textilizable(page.content, :text, :attachments => page.attachments)
|
||||
@included_wiki_pages.pop
|
||||
out
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
@@ -0,0 +1,183 @@
|
||||
# Redmine - project management software
|
||||
# Copyright (C) 2006-2008 Jean-Philippe Lang
|
||||
#
|
||||
# This program is free software; you can redistribute it and/or
|
||||
# modify it under the terms of the GNU General Public License
|
||||
# as published by the Free Software Foundation; either version 2
|
||||
# of the License, or (at your option) any later version.
|
||||
#
|
||||
# This program is distributed in the hope that it will be useful,
|
||||
# but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
# GNU General Public License for more details.
|
||||
#
|
||||
# You should have received a copy of the GNU General Public License
|
||||
# along with this program; if not, write to the Free Software
|
||||
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
|
||||
|
||||
require 'redcloth3'
|
||||
require 'coderay'
|
||||
|
||||
module Redmine
|
||||
module WikiFormatting
|
||||
module Textile
|
||||
class Formatter < RedCloth3
|
||||
|
||||
# auto_link rule after textile rules so that it doesn't break !image_url! tags
|
||||
RULES = [:textile, :block_markdown_rule, :inline_auto_link, :inline_auto_mailto, :inline_toc, :inline_macros]
|
||||
|
||||
def initialize(*args)
|
||||
super
|
||||
self.hard_breaks=true
|
||||
self.no_span_caps=true
|
||||
end
|
||||
|
||||
def to_html(*rules, &block)
|
||||
@toc = []
|
||||
@macros_runner = block
|
||||
super(*RULES).to_s
|
||||
end
|
||||
|
||||
private
|
||||
|
||||
# Patch for RedCloth. Fixed in RedCloth r128 but _why hasn't released it yet.
|
||||
# <a href="http://code.whytheluckystiff.net/redcloth/changeset/128">http://code.whytheluckystiff.net/redcloth/changeset/128</a>
|
||||
def hard_break( text )
|
||||
text.gsub!( /(.)\n(?!\n|\Z|>| *(>? *[#*=]+(\s|$)|[{|]))/, "\\1<br />\n" ) if hard_breaks
|
||||
end
|
||||
|
||||
# Patch to add code highlighting support to RedCloth
|
||||
def smooth_offtags( text )
|
||||
unless @pre_list.empty?
|
||||
## replace <pre> content
|
||||
text.gsub!(/<redpre#(\d+)>/) do
|
||||
content = @pre_list[$1.to_i]
|
||||
if content.match(/<code\s+class="(\w+)">\s?(.+)/m)
|
||||
content = "<code class=\"#{$1} CodeRay\">" +
|
||||
CodeRay.scan($2, $1.downcase).html(:escape => false, :line_numbers => :inline)
|
||||
end
|
||||
content
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
# Patch to add 'table of content' support to RedCloth
|
||||
def textile_p_withtoc(tag, atts, cite, content)
|
||||
# removes wiki links from the item
|
||||
toc_item = content.gsub(/(\[\[|\]\])/, '')
|
||||
# removes styles
|
||||
# eg. %{color:red}Triggers% => Triggers
|
||||
toc_item.gsub! %r[%\{[^\}]*\}([^%]+)%], '\\1'
|
||||
|
||||
# replaces non word caracters by dashes
|
||||
anchor = toc_item.gsub(%r{[^\w\s\-]}, '').gsub(%r{\s+(\-+\s*)?}, '-')
|
||||
|
||||
unless anchor.blank?
|
||||
if tag =~ /^h(\d)$/
|
||||
@toc << [$1.to_i, anchor, toc_item]
|
||||
end
|
||||
atts << " id=\"#{anchor}\""
|
||||
content = content + "<a href=\"##{anchor}\" class=\"wiki-anchor\">¶</a>"
|
||||
end
|
||||
textile_p(tag, atts, cite, content)
|
||||
end
|
||||
|
||||
alias :textile_h1 :textile_p_withtoc
|
||||
alias :textile_h2 :textile_p_withtoc
|
||||
alias :textile_h3 :textile_p_withtoc
|
||||
|
||||
def inline_toc(text)
|
||||
text.gsub!(/<p>\{\{([<>]?)toc\}\}<\/p>/i) do
|
||||
div_class = 'toc'
|
||||
div_class << ' right' if $1 == '>'
|
||||
div_class << ' left' if $1 == '<'
|
||||
out = "<ul class=\"#{div_class}\">"
|
||||
@toc.each do |heading|
|
||||
level, anchor, toc_item = heading
|
||||
out << "<li class=\"heading#{level}\"><a href=\"##{anchor}\">#{toc_item}</a></li>\n"
|
||||
end
|
||||
out << '</ul>'
|
||||
out
|
||||
end
|
||||
end
|
||||
|
||||
MACROS_RE = /
|
||||
(!)? # escaping
|
||||
(
|
||||
\{\{ # opening tag
|
||||
([\w]+) # macro name
|
||||
(\(([^\}]*)\))? # optional arguments
|
||||
\}\} # closing tag
|
||||
)
|
||||
/x unless const_defined?(:MACROS_RE)
|
||||
|
||||
def inline_macros(text)
|
||||
text.gsub!(MACROS_RE) do
|
||||
esc, all, macro = $1, $2, $3.downcase
|
||||
args = ($5 || '').split(',').each(&:strip)
|
||||
if esc.nil?
|
||||
begin
|
||||
@macros_runner.call(macro, args)
|
||||
rescue => e
|
||||
"<div class=\"flash error\">Error executing the <strong>#{macro}</strong> macro (#{e})</div>"
|
||||
end || all
|
||||
else
|
||||
all
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
AUTO_LINK_RE = %r{
|
||||
( # leading text
|
||||
<\w+.*?>| # leading HTML tag, or
|
||||
[^=<>!:'"/]| # leading punctuation, or
|
||||
^ # beginning of line
|
||||
)
|
||||
(
|
||||
(?:https?://)| # protocol spec, or
|
||||
(?:s?ftps?://)|
|
||||
(?:www\.) # www.*
|
||||
)
|
||||
(
|
||||
(\S+?) # url
|
||||
(\/)? # slash
|
||||
)
|
||||
([^\w\=\/;\(\)]*?) # post
|
||||
(?=<|\s|$)
|
||||
}x unless const_defined?(:AUTO_LINK_RE)
|
||||
|
||||
# Turns all urls into clickable links (code from Rails).
|
||||
def inline_auto_link(text)
|
||||
text.gsub!(AUTO_LINK_RE) do
|
||||
all, leading, proto, url, post = $&, $1, $2, $3, $6
|
||||
if leading =~ /<a\s/i || leading =~ /![<>=]?/
|
||||
# don't replace URL's that are already linked
|
||||
# and URL's prefixed with ! !> !< != (textile images)
|
||||
all
|
||||
else
|
||||
# Idea below : an URL with unbalanced parethesis and
|
||||
# ending by ')' is put into external parenthesis
|
||||
if ( url[-1]==?) and ((url.count("(") - url.count(")")) < 0 ) )
|
||||
url=url[0..-2] # discard closing parenth from url
|
||||
post = ")"+post # add closing parenth to post
|
||||
end
|
||||
%(#{leading}<a class="external" href="#{proto=="www."?"http://www.":proto}#{url}">#{proto + url}</a>#{post})
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
# Turns all email addresses into clickable links (code from Rails).
|
||||
def inline_auto_mailto(text)
|
||||
text.gsub!(/([\w\.!#\$%\-+.]+@[A-Za-z0-9\-]+(\.[A-Za-z0-9\-]+)+)/) do
|
||||
mail = $1
|
||||
if text.match(/<a\b[^>]*>(.*)(#{Regexp.escape(mail)})(.*)<\/a>/)
|
||||
mail
|
||||
else
|
||||
%{<a href="mailto:#{mail}" class="email">#{mail}</a>}
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
@@ -0,0 +1,43 @@
|
||||
# Redmine - project management software
|
||||
# Copyright (C) 2006-2008 Jean-Philippe Lang
|
||||
#
|
||||
# This program is free software; you can redistribute it and/or
|
||||
# modify it under the terms of the GNU General Public License
|
||||
# as published by the Free Software Foundation; either version 2
|
||||
# of the License, or (at your option) any later version.
|
||||
#
|
||||
# This program is distributed in the hope that it will be useful,
|
||||
# but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
# GNU General Public License for more details.
|
||||
#
|
||||
# You should have received a copy of the GNU General Public License
|
||||
# along with this program; if not, write to the Free Software
|
||||
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
|
||||
|
||||
module Redmine
|
||||
module WikiFormatting
|
||||
module Textile
|
||||
module Helper
|
||||
def wikitoolbar_for(field_id)
|
||||
help_link = l(:setting_text_formatting) + ': ' +
|
||||
link_to(l(:label_help), compute_public_path('wiki_syntax', 'help', 'html'),
|
||||
:onclick => "window.open(\"#{ compute_public_path('wiki_syntax', 'help', 'html') }\", \"\", \"resizable=yes, location=no, width=300, height=640, menubar=no, status=no, scrollbars=yes\"); return false;")
|
||||
|
||||
javascript_include_tag('jstoolbar/jstoolbar') +
|
||||
javascript_include_tag('jstoolbar/textile') +
|
||||
javascript_include_tag("jstoolbar/lang/jstoolbar-#{current_language}") +
|
||||
javascript_tag("var toolbar = new jsToolBar($('#{field_id}')); toolbar.setHelpLink('#{help_link}'); toolbar.draw();")
|
||||
end
|
||||
|
||||
def initial_page_content(page)
|
||||
"h1. #{@page.pretty_title}"
|
||||
end
|
||||
|
||||
def heads_for_wiki_formatter
|
||||
stylesheet_link_tag 'jstoolbar'
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
@@ -0,0 +1,51 @@
|
||||
# redMine - project management software
|
||||
# Copyright (C) 2006-2007 Jean-Philippe Lang
|
||||
#
|
||||
# This program is free software; you can redistribute it and/or
|
||||
# modify it under the terms of the GNU General Public License
|
||||
# as published by the Free Software Foundation; either version 2
|
||||
# of the License, or (at your option) any later version.
|
||||
#
|
||||
# This program is distributed in the hope that it will be useful,
|
||||
# but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
# GNU General Public License for more details.
|
||||
#
|
||||
# You should have received a copy of the GNU General Public License
|
||||
# along with this program; if not, write to the Free Software
|
||||
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
|
||||
|
||||
require 'action_view/helpers/form_helper'
|
||||
|
||||
class TabularFormBuilder < ActionView::Helpers::FormBuilder
|
||||
include GLoc
|
||||
|
||||
def initialize(object_name, object, template, options, proc)
|
||||
set_language_if_valid options.delete(:lang)
|
||||
super
|
||||
end
|
||||
|
||||
(field_helpers - %w(radio_button hidden_field) + %w(date_select)).each do |selector|
|
||||
src = <<-END_SRC
|
||||
def #{selector}(field, options = {})
|
||||
return super if options.delete :no_label
|
||||
label_text = l(options[:label]) if options[:label]
|
||||
label_text ||= l(("field_"+field.to_s.gsub(/\_id$/, "")).to_sym)
|
||||
label_text << @template.content_tag("span", " *", :class => "required") if options.delete(:required)
|
||||
label = @template.content_tag("label", label_text,
|
||||
:class => (@object && @object.errors[field] ? "error" : nil),
|
||||
:for => (@object_name.to_s + "_" + field.to_s))
|
||||
label + super
|
||||
end
|
||||
END_SRC
|
||||
class_eval src, __FILE__, __LINE__
|
||||
end
|
||||
|
||||
def select(field, choices, options = {}, html_options = {})
|
||||
label_text = l(("field_"+field.to_s.gsub(/\_id$/, "")).to_sym) + (options.delete(:required) ? @template.content_tag("span", " *", :class => "required"): "")
|
||||
label = @template.content_tag("label", label_text,
|
||||
:class => (@object && @object.errors[field] ? "error" : nil),
|
||||
:for => (@object_name.to_s + "_" + field.to_s))
|
||||
label + super
|
||||
end
|
||||
end
|
||||
@@ -0,0 +1,9 @@
|
||||
def deprecated_task(name, new_name)
|
||||
task name=>new_name do
|
||||
$stderr.puts "\nNote: The rake task #{name} has been deprecated, please use the replacement version #{new_name}"
|
||||
end
|
||||
end
|
||||
|
||||
deprecated_task :load_default_data, "redmine:load_default_data"
|
||||
deprecated_task :migrate_from_mantis, "redmine:migrate_from_mantis"
|
||||
deprecated_task :migrate_from_trac, "redmine:migrate_from_trac"
|
||||
@@ -0,0 +1,107 @@
|
||||
# redMine - project management software
|
||||
# Copyright (C) 2006-2008 Jean-Philippe Lang
|
||||
#
|
||||
# This program is free software; you can redistribute it and/or
|
||||
# modify it under the terms of the GNU General Public License
|
||||
# as published by the Free Software Foundation; either version 2
|
||||
# of the License, or (at your option) any later version.
|
||||
#
|
||||
# This program is distributed in the hope that it will be useful,
|
||||
# but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
# GNU General Public License for more details.
|
||||
#
|
||||
# You should have received a copy of the GNU General Public License
|
||||
# along with this program; if not, write to the Free Software
|
||||
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
|
||||
|
||||
namespace :redmine do
|
||||
namespace :email do
|
||||
|
||||
desc <<-END_DESC
|
||||
Read an email from standard input.
|
||||
|
||||
Issue attributes control options:
|
||||
project=PROJECT identifier of the target project
|
||||
status=STATUS name of the target status
|
||||
tracker=TRACKER name of the target tracker
|
||||
category=CATEGORY name of the target category
|
||||
priority=PRIORITY name of the target priority
|
||||
allow_override=ATTRS allow email content to override attributes
|
||||
specified by previous options
|
||||
ATTRS is a comma separated list of attributes
|
||||
|
||||
Examples:
|
||||
# No project specified. Emails MUST contain the 'Project' keyword:
|
||||
rake redmine:email:read RAILS_ENV="production" < raw_email
|
||||
|
||||
# Fixed project and default tracker specified, but emails can override
|
||||
# both tracker and priority attributes:
|
||||
rake redmine:email:read RAILS_ENV="production" \\
|
||||
project=foo \\
|
||||
tracker=bug \\
|
||||
allow_override=tracker,priority < raw_email
|
||||
END_DESC
|
||||
|
||||
task :read => :environment do
|
||||
options = { :issue => {} }
|
||||
%w(project status tracker category priority).each { |a| options[:issue][a.to_sym] = ENV[a] if ENV[a] }
|
||||
options[:allow_override] = ENV['allow_override'] if ENV['allow_override']
|
||||
|
||||
MailHandler.receive(STDIN.read, options)
|
||||
end
|
||||
|
||||
desc <<-END_DESC
|
||||
Read emails from an IMAP server.
|
||||
|
||||
Available IMAP options:
|
||||
host=HOST IMAP server host (default: 127.0.0.1)
|
||||
port=PORT IMAP server port (default: 143)
|
||||
ssl=SSL Use SSL? (default: false)
|
||||
username=USERNAME IMAP account
|
||||
password=PASSWORD IMAP password
|
||||
folder=FOLDER IMAP folder to read (default: INBOX)
|
||||
|
||||
Issue attributes control options:
|
||||
project=PROJECT identifier of the target project
|
||||
status=STATUS name of the target status
|
||||
tracker=TRACKER name of the target tracker
|
||||
category=CATEGORY name of the target category
|
||||
priority=PRIORITY name of the target priority
|
||||
allow_override=ATTRS allow email content to override attributes
|
||||
specified by previous options
|
||||
ATTRS is a comma separated list of attributes
|
||||
|
||||
Examples:
|
||||
# No project specified. Emails MUST contain the 'Project' keyword:
|
||||
|
||||
rake redmine:email:receive_iamp RAILS_ENV="production" \\
|
||||
host=imap.foo.bar username=redmine@example.net password=xxx
|
||||
|
||||
|
||||
# Fixed project and default tracker specified, but emails can override
|
||||
# both tracker and priority attributes:
|
||||
|
||||
rake redmine:email:receive_iamp RAILS_ENV="production" \\
|
||||
host=imap.foo.bar username=redmine@example.net password=xxx ssl=1 \\
|
||||
project=foo \\
|
||||
tracker=bug \\
|
||||
allow_override=tracker,priority
|
||||
END_DESC
|
||||
|
||||
task :receive_imap => :environment do
|
||||
imap_options = {:host => ENV['host'],
|
||||
:port => ENV['port'],
|
||||
:ssl => ENV['ssl'],
|
||||
:username => ENV['username'],
|
||||
:password => ENV['password'],
|
||||
:folder => ENV['folder']}
|
||||
|
||||
options = { :issue => {} }
|
||||
%w(project status tracker category priority).each { |a| options[:issue][a.to_sym] = ENV[a] if ENV[a] }
|
||||
options[:allow_override] = ENV['allow_override'] if ENV['allow_override']
|
||||
|
||||
Redmine::IMAP.check(imap_options, options)
|
||||
end
|
||||
end
|
||||
end
|
||||
@@ -0,0 +1,24 @@
|
||||
desc 'Create YAML test fixtures from data in an existing database.
|
||||
Defaults to development database. Set RAILS_ENV to override.'
|
||||
|
||||
task :extract_fixtures => :environment do
|
||||
sql = "SELECT * FROM %s"
|
||||
skip_tables = ["schema_info"]
|
||||
ActiveRecord::Base.establish_connection
|
||||
(ActiveRecord::Base.connection.tables - skip_tables).each do |table_name|
|
||||
i = "000"
|
||||
File.open("#{RAILS_ROOT}/#{table_name}.yml", 'w' ) do |file|
|
||||
data = ActiveRecord::Base.connection.select_all(sql % table_name)
|
||||
file.write data.inject({}) { |hash, record|
|
||||
|
||||
# cast extracted values
|
||||
ActiveRecord::Base.connection.columns(table_name).each { |col|
|
||||
record[col.name] = col.type_cast(record[col.name]) if record[col.name]
|
||||
}
|
||||
|
||||
hash["#{table_name}_#{i.succ!}"] = record
|
||||
hash
|
||||
}.to_yaml
|
||||
end
|
||||
end
|
||||
end
|
||||
@@ -0,0 +1,24 @@
|
||||
# redMine - project management software
|
||||
# Copyright (C) 2006-2008 Jean-Philippe Lang
|
||||
#
|
||||
# This program is free software; you can redistribute it and/or
|
||||
# modify it under the terms of the GNU General Public License
|
||||
# as published by the Free Software Foundation; either version 2
|
||||
# of the License, or (at your option) any later version.
|
||||
#
|
||||
# This program is distributed in the hope that it will be useful,
|
||||
# but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
# GNU General Public License for more details.
|
||||
#
|
||||
# You should have received a copy of the GNU General Public License
|
||||
# along with this program; if not, write to the Free Software
|
||||
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
|
||||
|
||||
desc 'Fetch changesets from the repositories'
|
||||
|
||||
namespace :redmine do
|
||||
task :fetch_changesets => :environment do
|
||||
Repository.fetch_changesets
|
||||
end
|
||||
end
|
||||
@@ -0,0 +1,29 @@
|
||||
desc 'Load Redmine default configuration data'
|
||||
|
||||
namespace :redmine do
|
||||
task :load_default_data => :environment do
|
||||
include GLoc
|
||||
set_language_if_valid('en')
|
||||
puts
|
||||
|
||||
while true
|
||||
print "Select language: "
|
||||
print GLoc.valid_languages.sort {|x,y| x.to_s <=> y.to_s }.join(", ")
|
||||
print " [#{GLoc.current_language}] "
|
||||
lang = STDIN.gets.chomp!
|
||||
break if lang.empty?
|
||||
break if set_language_if_valid(lang)
|
||||
puts "Unknown language!"
|
||||
end
|
||||
|
||||
puts "===================================="
|
||||
|
||||
begin
|
||||
Redmine::DefaultData::Loader.load(current_language)
|
||||
puts "Default configuration data loaded."
|
||||
rescue => error
|
||||
puts "Error: " + error
|
||||
puts "Default configuration data was not loaded."
|
||||
end
|
||||
end
|
||||
end
|
||||
@@ -0,0 +1,505 @@
|
||||
# redMine - project management software
|
||||
# Copyright (C) 2006-2007 Jean-Philippe Lang
|
||||
#
|
||||
# This program is free software; you can redistribute it and/or
|
||||
# modify it under the terms of the GNU General Public License
|
||||
# as published by the Free Software Foundation; either version 2
|
||||
# of the License, or (at your option) any later version.
|
||||
#
|
||||
# This program is distributed in the hope that it will be useful,
|
||||
# but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
# GNU General Public License for more details.
|
||||
#
|
||||
# You should have received a copy of the GNU General Public License
|
||||
# along with this program; if not, write to the Free Software
|
||||
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
|
||||
|
||||
desc 'Mantis migration script'
|
||||
|
||||
require 'active_record'
|
||||
require 'iconv'
|
||||
require 'pp'
|
||||
|
||||
namespace :redmine do
|
||||
task :migrate_from_mantis => :environment do
|
||||
|
||||
module MantisMigrate
|
||||
|
||||
DEFAULT_STATUS = IssueStatus.default
|
||||
assigned_status = IssueStatus.find_by_position(2)
|
||||
resolved_status = IssueStatus.find_by_position(3)
|
||||
feedback_status = IssueStatus.find_by_position(4)
|
||||
closed_status = IssueStatus.find :first, :conditions => { :is_closed => true }
|
||||
STATUS_MAPPING = {10 => DEFAULT_STATUS, # new
|
||||
20 => feedback_status, # feedback
|
||||
30 => DEFAULT_STATUS, # acknowledged
|
||||
40 => DEFAULT_STATUS, # confirmed
|
||||
50 => assigned_status, # assigned
|
||||
80 => resolved_status, # resolved
|
||||
90 => closed_status # closed
|
||||
}
|
||||
|
||||
priorities = Enumeration.get_values('IPRI')
|
||||
DEFAULT_PRIORITY = priorities[2]
|
||||
PRIORITY_MAPPING = {10 => priorities[1], # none
|
||||
20 => priorities[1], # low
|
||||
30 => priorities[2], # normal
|
||||
40 => priorities[3], # high
|
||||
50 => priorities[4], # urgent
|
||||
60 => priorities[5] # immediate
|
||||
}
|
||||
|
||||
TRACKER_BUG = Tracker.find_by_position(1)
|
||||
TRACKER_FEATURE = Tracker.find_by_position(2)
|
||||
|
||||
roles = Role.find(:all, :conditions => {:builtin => 0}, :order => 'position ASC')
|
||||
manager_role = roles[0]
|
||||
developer_role = roles[1]
|
||||
DEFAULT_ROLE = roles.last
|
||||
ROLE_MAPPING = {10 => DEFAULT_ROLE, # viewer
|
||||
25 => DEFAULT_ROLE, # reporter
|
||||
40 => DEFAULT_ROLE, # updater
|
||||
55 => developer_role, # developer
|
||||
70 => manager_role, # manager
|
||||
90 => manager_role # administrator
|
||||
}
|
||||
|
||||
CUSTOM_FIELD_TYPE_MAPPING = {0 => 'string', # String
|
||||
1 => 'int', # Numeric
|
||||
2 => 'int', # Float
|
||||
3 => 'list', # Enumeration
|
||||
4 => 'string', # Email
|
||||
5 => 'bool', # Checkbox
|
||||
6 => 'list', # List
|
||||
7 => 'list', # Multiselection list
|
||||
8 => 'date', # Date
|
||||
}
|
||||
|
||||
RELATION_TYPE_MAPPING = {1 => IssueRelation::TYPE_RELATES, # related to
|
||||
2 => IssueRelation::TYPE_RELATES, # parent of
|
||||
3 => IssueRelation::TYPE_RELATES, # child of
|
||||
0 => IssueRelation::TYPE_DUPLICATES, # duplicate of
|
||||
4 => IssueRelation::TYPE_DUPLICATES # has duplicate
|
||||
}
|
||||
|
||||
class MantisUser < ActiveRecord::Base
|
||||
set_table_name :mantis_user_table
|
||||
|
||||
def firstname
|
||||
@firstname = realname.blank? ? username : realname.split.first[0..29]
|
||||
@firstname.gsub!(/[^\w\s\'\-]/i, '')
|
||||
@firstname
|
||||
end
|
||||
|
||||
def lastname
|
||||
@lastname = realname.blank? ? '-' : realname.split[1..-1].join(' ')[0..29]
|
||||
@lastname.gsub!(/[^\w\s\'\-]/i, '')
|
||||
@lastname = '-' if @lastname.blank?
|
||||
@lastname
|
||||
end
|
||||
|
||||
def email
|
||||
if read_attribute(:email).match(/^([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})$/i) &&
|
||||
!User.find_by_mail(read_attribute(:email))
|
||||
@email = read_attribute(:email)
|
||||
else
|
||||
@email = "#{username}@foo.bar"
|
||||
end
|
||||
end
|
||||
|
||||
def username
|
||||
read_attribute(:username)[0..29].gsub(/[^a-zA-Z0-9_\-@\.]/, '-')
|
||||
end
|
||||
end
|
||||
|
||||
class MantisProject < ActiveRecord::Base
|
||||
set_table_name :mantis_project_table
|
||||
has_many :versions, :class_name => "MantisVersion", :foreign_key => :project_id
|
||||
has_many :categories, :class_name => "MantisCategory", :foreign_key => :project_id
|
||||
has_many :news, :class_name => "MantisNews", :foreign_key => :project_id
|
||||
has_many :members, :class_name => "MantisProjectUser", :foreign_key => :project_id
|
||||
|
||||
def name
|
||||
read_attribute(:name)[0..29]
|
||||
end
|
||||
|
||||
def identifier
|
||||
read_attribute(:name).underscore[0..19].gsub(/[^a-z0-9\-]/, '-')
|
||||
end
|
||||
end
|
||||
|
||||
class MantisVersion < ActiveRecord::Base
|
||||
set_table_name :mantis_project_version_table
|
||||
|
||||
def version
|
||||
read_attribute(:version)[0..29]
|
||||
end
|
||||
|
||||
def description
|
||||
read_attribute(:description)[0..254]
|
||||
end
|
||||
end
|
||||
|
||||
class MantisCategory < ActiveRecord::Base
|
||||
set_table_name :mantis_project_category_table
|
||||
end
|
||||
|
||||
class MantisProjectUser < ActiveRecord::Base
|
||||
set_table_name :mantis_project_user_list_table
|
||||
end
|
||||
|
||||
class MantisBug < ActiveRecord::Base
|
||||
set_table_name :mantis_bug_table
|
||||
belongs_to :bug_text, :class_name => "MantisBugText", :foreign_key => :bug_text_id
|
||||
has_many :bug_notes, :class_name => "MantisBugNote", :foreign_key => :bug_id
|
||||
has_many :bug_files, :class_name => "MantisBugFile", :foreign_key => :bug_id
|
||||
has_many :bug_monitors, :class_name => "MantisBugMonitor", :foreign_key => :bug_id
|
||||
end
|
||||
|
||||
class MantisBugText < ActiveRecord::Base
|
||||
set_table_name :mantis_bug_text_table
|
||||
|
||||
# Adds Mantis steps_to_reproduce and additional_information fields
|
||||
# to description if any
|
||||
def full_description
|
||||
full_description = description
|
||||
full_description += "\n\n*Steps to reproduce:*\n\n#{steps_to_reproduce}" unless steps_to_reproduce.blank?
|
||||
full_description += "\n\n*Additional information:*\n\n#{additional_information}" unless additional_information.blank?
|
||||
full_description
|
||||
end
|
||||
end
|
||||
|
||||
class MantisBugNote < ActiveRecord::Base
|
||||
set_table_name :mantis_bugnote_table
|
||||
belongs_to :bug, :class_name => "MantisBug", :foreign_key => :bug_id
|
||||
belongs_to :bug_note_text, :class_name => "MantisBugNoteText", :foreign_key => :bugnote_text_id
|
||||
end
|
||||
|
||||
class MantisBugNoteText < ActiveRecord::Base
|
||||
set_table_name :mantis_bugnote_text_table
|
||||
end
|
||||
|
||||
class MantisBugFile < ActiveRecord::Base
|
||||
set_table_name :mantis_bug_file_table
|
||||
|
||||
def size
|
||||
filesize
|
||||
end
|
||||
|
||||
def original_filename
|
||||
MantisMigrate.encode(filename)
|
||||
end
|
||||
|
||||
def content_type
|
||||
file_type
|
||||
end
|
||||
|
||||
def read
|
||||
content
|
||||
end
|
||||
end
|
||||
|
||||
class MantisBugRelationship < ActiveRecord::Base
|
||||
set_table_name :mantis_bug_relationship_table
|
||||
end
|
||||
|
||||
class MantisBugMonitor < ActiveRecord::Base
|
||||
set_table_name :mantis_bug_monitor_table
|
||||
end
|
||||
|
||||
class MantisNews < ActiveRecord::Base
|
||||
set_table_name :mantis_news_table
|
||||
end
|
||||
|
||||
class MantisCustomField < ActiveRecord::Base
|
||||
set_table_name :mantis_custom_field_table
|
||||
set_inheritance_column :none
|
||||
has_many :values, :class_name => "MantisCustomFieldString", :foreign_key => :field_id
|
||||
has_many :projects, :class_name => "MantisCustomFieldProject", :foreign_key => :field_id
|
||||
|
||||
def format
|
||||
read_attribute :type
|
||||
end
|
||||
|
||||
def name
|
||||
read_attribute(:name)[0..29].gsub(/[^\w\s\'\-]/, '-')
|
||||
end
|
||||
end
|
||||
|
||||
class MantisCustomFieldProject < ActiveRecord::Base
|
||||
set_table_name :mantis_custom_field_project_table
|
||||
end
|
||||
|
||||
class MantisCustomFieldString < ActiveRecord::Base
|
||||
set_table_name :mantis_custom_field_string_table
|
||||
end
|
||||
|
||||
|
||||
def self.migrate
|
||||
|
||||
# Users
|
||||
print "Migrating users"
|
||||
User.delete_all "login <> 'admin'"
|
||||
users_map = {}
|
||||
users_migrated = 0
|
||||
MantisUser.find(:all).each do |user|
|
||||
u = User.new :firstname => encode(user.firstname),
|
||||
:lastname => encode(user.lastname),
|
||||
:mail => user.email,
|
||||
:last_login_on => user.last_visit
|
||||
u.login = user.username
|
||||
u.password = 'mantis'
|
||||
u.status = User::STATUS_LOCKED if user.enabled != 1
|
||||
u.admin = true if user.access_level == 90
|
||||
next unless u.save!
|
||||
users_migrated += 1
|
||||
users_map[user.id] = u.id
|
||||
print '.'
|
||||
end
|
||||
puts
|
||||
|
||||
# Projects
|
||||
print "Migrating projects"
|
||||
Project.destroy_all
|
||||
projects_map = {}
|
||||
versions_map = {}
|
||||
categories_map = {}
|
||||
MantisProject.find(:all).each do |project|
|
||||
p = Project.new :name => encode(project.name),
|
||||
:description => encode(project.description)
|
||||
p.identifier = project.identifier
|
||||
next unless p.save
|
||||
projects_map[project.id] = p.id
|
||||
p.enabled_module_names = ['issue_tracking', 'news', 'wiki']
|
||||
p.trackers << TRACKER_BUG
|
||||
p.trackers << TRACKER_FEATURE
|
||||
print '.'
|
||||
|
||||
# Project members
|
||||
project.members.each do |member|
|
||||
m = Member.new :user => User.find_by_id(users_map[member.user_id]),
|
||||
:role => ROLE_MAPPING[member.access_level] || DEFAULT_ROLE
|
||||
m.project = p
|
||||
m.save
|
||||
end
|
||||
|
||||
# Project versions
|
||||
project.versions.each do |version|
|
||||
v = Version.new :name => encode(version.version),
|
||||
:description => encode(version.description),
|
||||
:effective_date => version.date_order.to_date
|
||||
v.project = p
|
||||
v.save
|
||||
versions_map[version.id] = v.id
|
||||
end
|
||||
|
||||
# Project categories
|
||||
project.categories.each do |category|
|
||||
g = IssueCategory.new :name => category.category[0,30]
|
||||
g.project = p
|
||||
g.save
|
||||
categories_map[category.category] = g.id
|
||||
end
|
||||
end
|
||||
puts
|
||||
|
||||
# Bugs
|
||||
print "Migrating bugs"
|
||||
Issue.destroy_all
|
||||
issues_map = {}
|
||||
keep_bug_ids = (Issue.count == 0)
|
||||
MantisBug.find(:all, :order => 'id ASC').each do |bug|
|
||||
next unless projects_map[bug.project_id] && users_map[bug.reporter_id]
|
||||
i = Issue.new :project_id => projects_map[bug.project_id],
|
||||
:subject => encode(bug.summary),
|
||||
:description => encode(bug.bug_text.full_description),
|
||||
:priority => PRIORITY_MAPPING[bug.priority] || DEFAULT_PRIORITY,
|
||||
:created_on => bug.date_submitted,
|
||||
:updated_on => bug.last_updated
|
||||
i.author = User.find_by_id(users_map[bug.reporter_id])
|
||||
i.category = IssueCategory.find_by_project_id_and_name(i.project_id, bug.category[0,30]) unless bug.category.blank?
|
||||
i.fixed_version = Version.find_by_project_id_and_name(i.project_id, bug.fixed_in_version) unless bug.fixed_in_version.blank?
|
||||
i.status = STATUS_MAPPING[bug.status] || DEFAULT_STATUS
|
||||
i.tracker = (bug.severity == 10 ? TRACKER_FEATURE : TRACKER_BUG)
|
||||
i.id = bug.id if keep_bug_ids
|
||||
next unless i.save
|
||||
issues_map[bug.id] = i.id
|
||||
print '.'
|
||||
|
||||
# Assignee
|
||||
# Redmine checks that the assignee is a project member
|
||||
if (bug.handler_id && users_map[bug.handler_id])
|
||||
i.assigned_to = User.find_by_id(users_map[bug.handler_id])
|
||||
i.save_with_validation(false)
|
||||
end
|
||||
|
||||
# Bug notes
|
||||
bug.bug_notes.each do |note|
|
||||
next unless users_map[note.reporter_id]
|
||||
n = Journal.new :notes => encode(note.bug_note_text.note),
|
||||
:created_on => note.date_submitted
|
||||
n.user = User.find_by_id(users_map[note.reporter_id])
|
||||
n.journalized = i
|
||||
n.save
|
||||
end
|
||||
|
||||
# Bug files
|
||||
bug.bug_files.each do |file|
|
||||
a = Attachment.new :created_on => file.date_added
|
||||
a.file = file
|
||||
a.author = User.find :first
|
||||
a.container = i
|
||||
a.save
|
||||
end
|
||||
|
||||
# Bug monitors
|
||||
bug.bug_monitors.each do |monitor|
|
||||
next unless users_map[monitor.user_id]
|
||||
i.add_watcher(User.find_by_id(users_map[monitor.user_id]))
|
||||
end
|
||||
end
|
||||
|
||||
# update issue id sequence if needed (postgresql)
|
||||
Issue.connection.reset_pk_sequence!(Issue.table_name) if Issue.connection.respond_to?('reset_pk_sequence!')
|
||||
puts
|
||||
|
||||
# Bug relationships
|
||||
print "Migrating bug relations"
|
||||
MantisBugRelationship.find(:all).each do |relation|
|
||||
next unless issues_map[relation.source_bug_id] && issues_map[relation.destination_bug_id]
|
||||
r = IssueRelation.new :relation_type => RELATION_TYPE_MAPPING[relation.relationship_type]
|
||||
r.issue_from = Issue.find_by_id(issues_map[relation.source_bug_id])
|
||||
r.issue_to = Issue.find_by_id(issues_map[relation.destination_bug_id])
|
||||
pp r unless r.save
|
||||
print '.'
|
||||
end
|
||||
puts
|
||||
|
||||
# News
|
||||
print "Migrating news"
|
||||
News.destroy_all
|
||||
MantisNews.find(:all, :conditions => 'project_id > 0').each do |news|
|
||||
next unless projects_map[news.project_id]
|
||||
n = News.new :project_id => projects_map[news.project_id],
|
||||
:title => encode(news.headline[0..59]),
|
||||
:description => encode(news.body),
|
||||
:created_on => news.date_posted
|
||||
n.author = User.find_by_id(users_map[news.poster_id])
|
||||
n.save
|
||||
print '.'
|
||||
end
|
||||
puts
|
||||
|
||||
# Custom fields
|
||||
print "Migrating custom fields"
|
||||
IssueCustomField.destroy_all
|
||||
MantisCustomField.find(:all).each do |field|
|
||||
f = IssueCustomField.new :name => field.name[0..29],
|
||||
:field_format => CUSTOM_FIELD_TYPE_MAPPING[field.format],
|
||||
:min_length => field.length_min,
|
||||
:max_length => field.length_max,
|
||||
:regexp => field.valid_regexp,
|
||||
:possible_values => field.possible_values.split('|'),
|
||||
:is_required => field.require_report?
|
||||
next unless f.save
|
||||
print '.'
|
||||
|
||||
# Trackers association
|
||||
f.trackers = Tracker.find :all
|
||||
|
||||
# Projects association
|
||||
field.projects.each do |project|
|
||||
f.projects << Project.find_by_id(projects_map[project.project_id]) if projects_map[project.project_id]
|
||||
end
|
||||
|
||||
# Values
|
||||
field.values.each do |value|
|
||||
v = CustomValue.new :custom_field_id => f.id,
|
||||
:value => value.value
|
||||
v.customized = Issue.find_by_id(issues_map[value.bug_id]) if issues_map[value.bug_id]
|
||||
v.save
|
||||
end unless f.new_record?
|
||||
end
|
||||
puts
|
||||
|
||||
puts
|
||||
puts "Users: #{users_migrated}/#{MantisUser.count}"
|
||||
puts "Projects: #{Project.count}/#{MantisProject.count}"
|
||||
puts "Memberships: #{Member.count}/#{MantisProjectUser.count}"
|
||||
puts "Versions: #{Version.count}/#{MantisVersion.count}"
|
||||
puts "Categories: #{IssueCategory.count}/#{MantisCategory.count}"
|
||||
puts "Bugs: #{Issue.count}/#{MantisBug.count}"
|
||||
puts "Bug notes: #{Journal.count}/#{MantisBugNote.count}"
|
||||
puts "Bug files: #{Attachment.count}/#{MantisBugFile.count}"
|
||||
puts "Bug relations: #{IssueRelation.count}/#{MantisBugRelationship.count}"
|
||||
puts "Bug monitors: #{Watcher.count}/#{MantisBugMonitor.count}"
|
||||
puts "News: #{News.count}/#{MantisNews.count}"
|
||||
puts "Custom fields: #{IssueCustomField.count}/#{MantisCustomField.count}"
|
||||
end
|
||||
|
||||
def self.encoding(charset)
|
||||
@ic = Iconv.new('UTF-8', charset)
|
||||
rescue Iconv::InvalidEncoding
|
||||
return false
|
||||
end
|
||||
|
||||
def self.establish_connection(params)
|
||||
constants.each do |const|
|
||||
klass = const_get(const)
|
||||
next unless klass.respond_to? 'establish_connection'
|
||||
klass.establish_connection params
|
||||
end
|
||||
end
|
||||
|
||||
def self.encode(text)
|
||||
@ic.iconv text
|
||||
rescue
|
||||
text
|
||||
end
|
||||
end
|
||||
|
||||
puts
|
||||
if Redmine::DefaultData::Loader.no_data?
|
||||
puts "Redmine configuration need to be loaded before importing data."
|
||||
puts "Please, run this first:"
|
||||
puts
|
||||
puts " rake redmine:load_default_data RAILS_ENV=\"#{ENV['RAILS_ENV']}\""
|
||||
exit
|
||||
end
|
||||
|
||||
puts "WARNING: Your Redmine data will be deleted during this process."
|
||||
print "Are you sure you want to continue ? [y/N] "
|
||||
break unless STDIN.gets.match(/^y$/i)
|
||||
|
||||
# Default Mantis database settings
|
||||
db_params = {:adapter => 'mysql',
|
||||
:database => 'bugtracker',
|
||||
:host => 'localhost',
|
||||
:username => 'root',
|
||||
:password => '' }
|
||||
|
||||
puts
|
||||
puts "Please enter settings for your Mantis database"
|
||||
[:adapter, :host, :database, :username, :password].each do |param|
|
||||
print "#{param} [#{db_params[param]}]: "
|
||||
value = STDIN.gets.chomp!
|
||||
db_params[param] = value unless value.blank?
|
||||
end
|
||||
|
||||
while true
|
||||
print "encoding [UTF-8]: "
|
||||
encoding = STDIN.gets.chomp!
|
||||
encoding = 'UTF-8' if encoding.blank?
|
||||
break if MantisMigrate.encoding encoding
|
||||
puts "Invalid encoding!"
|
||||
end
|
||||
puts
|
||||
|
||||
# Make sure bugs can refer bugs in other projects
|
||||
Setting.cross_project_issue_relations = 1 if Setting.respond_to? 'cross_project_issue_relations'
|
||||
|
||||
MantisMigrate.establish_connection db_params
|
||||
MantisMigrate.migrate
|
||||
end
|
||||
end
|
||||
@@ -0,0 +1,747 @@
|
||||
# redMine - project management software
|
||||
# Copyright (C) 2006-2007 Jean-Philippe Lang
|
||||
#
|
||||
# This program is free software; you can redistribute it and/or
|
||||
# modify it under the terms of the GNU General Public License
|
||||
# as published by the Free Software Foundation; either version 2
|
||||
# of the License, or (at your option) any later version.
|
||||
#
|
||||
# This program is distributed in the hope that it will be useful,
|
||||
# but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
# GNU General Public License for more details.
|
||||
#
|
||||
# You should have received a copy of the GNU General Public License
|
||||
# along with this program; if not, write to the Free Software
|
||||
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
|
||||
|
||||
require 'active_record'
|
||||
require 'iconv'
|
||||
require 'pp'
|
||||
|
||||
namespace :redmine do
|
||||
desc 'Trac migration script'
|
||||
task :migrate_from_trac => :environment do
|
||||
|
||||
module TracMigrate
|
||||
TICKET_MAP = []
|
||||
|
||||
DEFAULT_STATUS = IssueStatus.default
|
||||
assigned_status = IssueStatus.find_by_position(2)
|
||||
resolved_status = IssueStatus.find_by_position(3)
|
||||
feedback_status = IssueStatus.find_by_position(4)
|
||||
closed_status = IssueStatus.find :first, :conditions => { :is_closed => true }
|
||||
STATUS_MAPPING = {'new' => DEFAULT_STATUS,
|
||||
'reopened' => feedback_status,
|
||||
'assigned' => assigned_status,
|
||||
'closed' => closed_status
|
||||
}
|
||||
|
||||
priorities = Enumeration.get_values('IPRI')
|
||||
DEFAULT_PRIORITY = priorities[0]
|
||||
PRIORITY_MAPPING = {'lowest' => priorities[0],
|
||||
'low' => priorities[0],
|
||||
'normal' => priorities[1],
|
||||
'high' => priorities[2],
|
||||
'highest' => priorities[3],
|
||||
# ---
|
||||
'trivial' => priorities[0],
|
||||
'minor' => priorities[1],
|
||||
'major' => priorities[2],
|
||||
'critical' => priorities[3],
|
||||
'blocker' => priorities[4]
|
||||
}
|
||||
|
||||
TRACKER_BUG = Tracker.find_by_position(1)
|
||||
TRACKER_FEATURE = Tracker.find_by_position(2)
|
||||
DEFAULT_TRACKER = TRACKER_BUG
|
||||
TRACKER_MAPPING = {'defect' => TRACKER_BUG,
|
||||
'enhancement' => TRACKER_FEATURE,
|
||||
'task' => TRACKER_FEATURE,
|
||||
'patch' =>TRACKER_FEATURE
|
||||
}
|
||||
|
||||
roles = Role.find(:all, :conditions => {:builtin => 0}, :order => 'position ASC')
|
||||
manager_role = roles[0]
|
||||
developer_role = roles[1]
|
||||
DEFAULT_ROLE = roles.last
|
||||
ROLE_MAPPING = {'admin' => manager_role,
|
||||
'developer' => developer_role
|
||||
}
|
||||
|
||||
class ::Time
|
||||
class << self
|
||||
alias :real_now :now
|
||||
def now
|
||||
real_now - @fake_diff.to_i
|
||||
end
|
||||
def fake(time)
|
||||
@fake_diff = real_now - time
|
||||
res = yield
|
||||
@fake_diff = 0
|
||||
res
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
class TracComponent < ActiveRecord::Base
|
||||
set_table_name :component
|
||||
end
|
||||
|
||||
class TracMilestone < ActiveRecord::Base
|
||||
set_table_name :milestone
|
||||
# If this attribute is set a milestone has a defined target timepoint
|
||||
def due
|
||||
if read_attribute(:due) && read_attribute(:due) > 0
|
||||
Time.at(read_attribute(:due)).to_date
|
||||
else
|
||||
nil
|
||||
end
|
||||
end
|
||||
# This is the real timepoint at which the milestone has finished.
|
||||
def completed
|
||||
if read_attribute(:completed) && read_attribute(:completed) > 0
|
||||
Time.at(read_attribute(:completed)).to_date
|
||||
else
|
||||
nil
|
||||
end
|
||||
end
|
||||
|
||||
def description
|
||||
# Attribute is named descr in Trac v0.8.x
|
||||
has_attribute?(:descr) ? read_attribute(:descr) : read_attribute(:description)
|
||||
end
|
||||
end
|
||||
|
||||
class TracTicketCustom < ActiveRecord::Base
|
||||
set_table_name :ticket_custom
|
||||
end
|
||||
|
||||
class TracAttachment < ActiveRecord::Base
|
||||
set_table_name :attachment
|
||||
set_inheritance_column :none
|
||||
|
||||
def time; Time.at(read_attribute(:time)) end
|
||||
|
||||
def original_filename
|
||||
filename
|
||||
end
|
||||
|
||||
def content_type
|
||||
Redmine::MimeType.of(filename) || ''
|
||||
end
|
||||
|
||||
def exist?
|
||||
File.file? trac_fullpath
|
||||
end
|
||||
|
||||
def read
|
||||
File.open("#{trac_fullpath}", 'rb').read
|
||||
end
|
||||
|
||||
def description
|
||||
read_attribute(:description).to_s.slice(0,255)
|
||||
end
|
||||
|
||||
private
|
||||
def trac_fullpath
|
||||
attachment_type = read_attribute(:type)
|
||||
trac_file = filename.gsub( /[^a-zA-Z0-9\-_\.!~*']/n ) {|x| sprintf('%%%02x', x[0]) }
|
||||
"#{TracMigrate.trac_attachments_directory}/#{attachment_type}/#{id}/#{trac_file}"
|
||||
end
|
||||
end
|
||||
|
||||
class TracTicket < ActiveRecord::Base
|
||||
set_table_name :ticket
|
||||
set_inheritance_column :none
|
||||
|
||||
# ticket changes: only migrate status changes and comments
|
||||
has_many :changes, :class_name => "TracTicketChange", :foreign_key => :ticket
|
||||
has_many :attachments, :class_name => "TracAttachment",
|
||||
:finder_sql => "SELECT DISTINCT attachment.* FROM #{TracMigrate::TracAttachment.table_name}" +
|
||||
" WHERE #{TracMigrate::TracAttachment.table_name}.type = 'ticket'" +
|
||||
' AND #{TracMigrate::TracAttachment.table_name}.id = \'#{id}\''
|
||||
has_many :customs, :class_name => "TracTicketCustom", :foreign_key => :ticket
|
||||
|
||||
def ticket_type
|
||||
read_attribute(:type)
|
||||
end
|
||||
|
||||
def summary
|
||||
read_attribute(:summary).blank? ? "(no subject)" : read_attribute(:summary)
|
||||
end
|
||||
|
||||
def description
|
||||
read_attribute(:description).blank? ? summary : read_attribute(:description)
|
||||
end
|
||||
|
||||
def time; Time.at(read_attribute(:time)) end
|
||||
def changetime; Time.at(read_attribute(:changetime)) end
|
||||
end
|
||||
|
||||
class TracTicketChange < ActiveRecord::Base
|
||||
set_table_name :ticket_change
|
||||
|
||||
def time; Time.at(read_attribute(:time)) end
|
||||
end
|
||||
|
||||
TRAC_WIKI_PAGES = %w(InterMapTxt InterTrac InterWiki RecentChanges SandBox TracAccessibility TracAdmin TracBackup TracBrowser TracCgi TracChangeset \
|
||||
TracEnvironment TracFastCgi TracGuide TracImport TracIni TracInstall TracInterfaceCustomization \
|
||||
TracLinks TracLogging TracModPython TracNotification TracPermissions TracPlugins TracQuery \
|
||||
TracReports TracRevisionLog TracRoadmap TracRss TracSearch TracStandalone TracSupport TracSyntaxColoring TracTickets \
|
||||
TracTicketsCustomFields TracTimeline TracUnicode TracUpgrade TracWiki WikiDeletePage WikiFormatting \
|
||||
WikiHtml WikiMacros WikiNewPage WikiPageNames WikiProcessors WikiRestructuredText WikiRestructuredTextLinks \
|
||||
CamelCase TitleIndex)
|
||||
|
||||
class TracWikiPage < ActiveRecord::Base
|
||||
set_table_name :wiki
|
||||
set_primary_key :name
|
||||
|
||||
has_many :attachments, :class_name => "TracAttachment",
|
||||
:finder_sql => "SELECT DISTINCT attachment.* FROM #{TracMigrate::TracAttachment.table_name}" +
|
||||
" WHERE #{TracMigrate::TracAttachment.table_name}.type = 'wiki'" +
|
||||
' AND #{TracMigrate::TracAttachment.table_name}.id = \'#{id}\''
|
||||
|
||||
def self.columns
|
||||
# Hides readonly Trac field to prevent clash with AR readonly? method (Rails 2.0)
|
||||
super.select {|column| column.name.to_s != 'readonly'}
|
||||
end
|
||||
|
||||
def time; Time.at(read_attribute(:time)) end
|
||||
end
|
||||
|
||||
class TracPermission < ActiveRecord::Base
|
||||
set_table_name :permission
|
||||
end
|
||||
|
||||
class TracSessionAttribute < ActiveRecord::Base
|
||||
set_table_name :session_attribute
|
||||
end
|
||||
|
||||
def self.find_or_create_user(username, project_member = false)
|
||||
return User.anonymous if username.blank?
|
||||
|
||||
u = User.find_by_login(username)
|
||||
if !u
|
||||
# Create a new user if not found
|
||||
mail = username[0,limit_for(User, 'mail')]
|
||||
if mail_attr = TracSessionAttribute.find_by_sid_and_name(username, 'email')
|
||||
mail = mail_attr.value
|
||||
end
|
||||
mail = "#{mail}@foo.bar" unless mail.include?("@")
|
||||
|
||||
name = username
|
||||
if name_attr = TracSessionAttribute.find_by_sid_and_name(username, 'name')
|
||||
name = name_attr.value
|
||||
end
|
||||
name =~ (/(.*)(\s+\w+)?/)
|
||||
fn = $1.strip
|
||||
ln = ($2 || '-').strip
|
||||
|
||||
u = User.new :mail => mail.gsub(/[^-@a-z0-9\.]/i, '-'),
|
||||
:firstname => fn[0, limit_for(User, 'firstname')].gsub(/[^\w\s\'\-]/i, '-'),
|
||||
:lastname => ln[0, limit_for(User, 'lastname')].gsub(/[^\w\s\'\-]/i, '-')
|
||||
|
||||
u.login = username[0,limit_for(User, 'login')].gsub(/[^a-z0-9_\-@\.]/i, '-')
|
||||
u.password = 'trac'
|
||||
u.admin = true if TracPermission.find_by_username_and_action(username, 'admin')
|
||||
# finally, a default user is used if the new user is not valid
|
||||
u = User.find(:first) unless u.save
|
||||
end
|
||||
# Make sure he is a member of the project
|
||||
if project_member && !u.member_of?(@target_project)
|
||||
role = DEFAULT_ROLE
|
||||
if u.admin
|
||||
role = ROLE_MAPPING['admin']
|
||||
elsif TracPermission.find_by_username_and_action(username, 'developer')
|
||||
role = ROLE_MAPPING['developer']
|
||||
end
|
||||
Member.create(:user => u, :project => @target_project, :role => role)
|
||||
u.reload
|
||||
end
|
||||
u
|
||||
end
|
||||
|
||||
# Basic wiki syntax conversion
|
||||
def self.convert_wiki_text(text)
|
||||
# Titles
|
||||
text = text.gsub(/^(\=+)\s(.+)\s(\=+)/) {|s| "\nh#{$1.length}. #{$2}\n"}
|
||||
# External Links
|
||||
text = text.gsub(/\[(http[^\s]+)\s+([^\]]+)\]/) {|s| "\"#{$2}\":#{$1}"}
|
||||
# Ticket links:
|
||||
# [ticket:234 Text],[ticket:234 This is a test]
|
||||
text = text.gsub(/\[ticket\:([^\ ]+)\ (.+?)\]/, '"\2":/issues/show/\1')
|
||||
# ticket:1234
|
||||
# #1 is working cause Redmine uses the same syntax.
|
||||
text = text.gsub(/ticket\:([^\ ]+)/, '#\1')
|
||||
# Milestone links:
|
||||
# [milestone:"0.1.0 Mercury" Milestone 0.1.0 (Mercury)]
|
||||
# The text "Milestone 0.1.0 (Mercury)" is not converted,
|
||||
# cause Redmine's wiki does not support this.
|
||||
text = text.gsub(/\[milestone\:\"([^\"]+)\"\ (.+?)\]/, 'version:"\1"')
|
||||
# [milestone:"0.1.0 Mercury"]
|
||||
text = text.gsub(/\[milestone\:\"([^\"]+)\"\]/, 'version:"\1"')
|
||||
text = text.gsub(/milestone\:\"([^\"]+)\"/, 'version:"\1"')
|
||||
# milestone:0.1.0
|
||||
text = text.gsub(/\[milestone\:([^\ ]+)\]/, 'version:\1')
|
||||
text = text.gsub(/milestone\:([^\ ]+)/, 'version:\1')
|
||||
# Internal Links
|
||||
text = text.gsub(/\[\[BR\]\]/, "\n") # This has to go before the rules below
|
||||
text = text.gsub(/\[\"(.+)\".*\]/) {|s| "[[#{$1.delete(',./?;|:')}]]"}
|
||||
text = text.gsub(/\[wiki:\"(.+)\".*\]/) {|s| "[[#{$1.delete(',./?;|:')}]]"}
|
||||
text = text.gsub(/\[wiki:\"(.+)\".*\]/) {|s| "[[#{$1.delete(',./?;|:')}]]"}
|
||||
text = text.gsub(/\[wiki:([^\s\]]+)\]/) {|s| "[[#{$1.delete(',./?;|:')}]]"}
|
||||
text = text.gsub(/\[wiki:([^\s\]]+)\s(.*)\]/) {|s| "[[#{$1.delete(',./?;|:')}|#{$2.delete(',./?;|:')}]]"}
|
||||
|
||||
# Links to pages UsingJustWikiCaps
|
||||
text = text.gsub(/([^!]|^)(^| )([A-Z][a-z]+[A-Z][a-zA-Z]+)/, '\\1\\2[[\3]]')
|
||||
# Normalize things that were supposed to not be links
|
||||
# like !NotALink
|
||||
text = text.gsub(/(^| )!([A-Z][A-Za-z]+)/, '\1\2')
|
||||
# Revisions links
|
||||
text = text.gsub(/\[(\d+)\]/, 'r\1')
|
||||
# Ticket number re-writing
|
||||
text = text.gsub(/#(\d+)/) do |s|
|
||||
if $1.length < 10
|
||||
TICKET_MAP[$1.to_i] ||= $1
|
||||
"\##{TICKET_MAP[$1.to_i] || $1}"
|
||||
else
|
||||
s
|
||||
end
|
||||
end
|
||||
# We would like to convert the Code highlighting too
|
||||
# This will go into the next line.
|
||||
shebang_line = false
|
||||
# Reguar expression for start of code
|
||||
pre_re = /\{\{\{/
|
||||
# Code hightlighing...
|
||||
shebang_re = /^\#\!([a-z]+)/
|
||||
# Regular expression for end of code
|
||||
pre_end_re = /\}\}\}/
|
||||
|
||||
# Go through the whole text..extract it line by line
|
||||
text = text.gsub(/^(.*)$/) do |line|
|
||||
m_pre = pre_re.match(line)
|
||||
if m_pre
|
||||
line = '<pre>'
|
||||
else
|
||||
m_sl = shebang_re.match(line)
|
||||
if m_sl
|
||||
shebang_line = true
|
||||
line = '<code class="' + m_sl[1] + '">'
|
||||
end
|
||||
m_pre_end = pre_end_re.match(line)
|
||||
if m_pre_end
|
||||
line = '</pre>'
|
||||
if shebang_line
|
||||
line = '</code>' + line
|
||||
end
|
||||
end
|
||||
end
|
||||
line
|
||||
end
|
||||
|
||||
# Highlighting
|
||||
text = text.gsub(/'''''([^\s])/, '_*\1')
|
||||
text = text.gsub(/([^\s])'''''/, '\1*_')
|
||||
text = text.gsub(/'''/, '*')
|
||||
text = text.gsub(/''/, '_')
|
||||
text = text.gsub(/__/, '+')
|
||||
text = text.gsub(/~~/, '-')
|
||||
text = text.gsub(/`/, '@')
|
||||
text = text.gsub(/,,/, '~')
|
||||
# Lists
|
||||
text = text.gsub(/^([ ]+)\* /) {|s| '*' * $1.length + " "}
|
||||
|
||||
text
|
||||
end
|
||||
|
||||
def self.migrate
|
||||
establish_connection
|
||||
|
||||
# Quick database test
|
||||
TracComponent.count
|
||||
|
||||
migrated_components = 0
|
||||
migrated_milestones = 0
|
||||
migrated_tickets = 0
|
||||
migrated_custom_values = 0
|
||||
migrated_ticket_attachments = 0
|
||||
migrated_wiki_edits = 0
|
||||
migrated_wiki_attachments = 0
|
||||
|
||||
#Wiki system initializing...
|
||||
@target_project.wiki.destroy if @target_project.wiki
|
||||
@target_project.reload
|
||||
wiki = Wiki.new(:project => @target_project, :start_page => 'WikiStart')
|
||||
wiki_edit_count = 0
|
||||
|
||||
# Components
|
||||
print "Migrating components"
|
||||
issues_category_map = {}
|
||||
TracComponent.find(:all).each do |component|
|
||||
print '.'
|
||||
STDOUT.flush
|
||||
c = IssueCategory.new :project => @target_project,
|
||||
:name => encode(component.name[0, limit_for(IssueCategory, 'name')])
|
||||
next unless c.save
|
||||
issues_category_map[component.name] = c
|
||||
migrated_components += 1
|
||||
end
|
||||
puts
|
||||
|
||||
# Milestones
|
||||
print "Migrating milestones"
|
||||
version_map = {}
|
||||
TracMilestone.find(:all).each do |milestone|
|
||||
print '.'
|
||||
STDOUT.flush
|
||||
# First we try to find the wiki page...
|
||||
p = wiki.find_or_new_page(milestone.name.to_s)
|
||||
p.content = WikiContent.new(:page => p) if p.new_record?
|
||||
p.content.text = milestone.description.to_s
|
||||
p.content.author = find_or_create_user('trac')
|
||||
p.content.comments = 'Milestone'
|
||||
p.save
|
||||
|
||||
v = Version.new :project => @target_project,
|
||||
:name => encode(milestone.name[0, limit_for(Version, 'name')]),
|
||||
:description => nil,
|
||||
:wiki_page_title => milestone.name.to_s,
|
||||
:effective_date => milestone.completed
|
||||
|
||||
next unless v.save
|
||||
version_map[milestone.name] = v
|
||||
migrated_milestones += 1
|
||||
end
|
||||
puts
|
||||
|
||||
# Custom fields
|
||||
# TODO: read trac.ini instead
|
||||
print "Migrating custom fields"
|
||||
custom_field_map = {}
|
||||
TracTicketCustom.find_by_sql("SELECT DISTINCT name FROM #{TracTicketCustom.table_name}").each do |field|
|
||||
print '.'
|
||||
STDOUT.flush
|
||||
# Redmine custom field name
|
||||
field_name = encode(field.name[0, limit_for(IssueCustomField, 'name')]).humanize
|
||||
# Find if the custom already exists in Redmine
|
||||
f = IssueCustomField.find_by_name(field_name)
|
||||
# Or create a new one
|
||||
f ||= IssueCustomField.create(:name => encode(field.name[0, limit_for(IssueCustomField, 'name')]).humanize,
|
||||
:field_format => 'string')
|
||||
|
||||
next if f.new_record?
|
||||
f.trackers = Tracker.find(:all)
|
||||
f.projects << @target_project
|
||||
custom_field_map[field.name] = f
|
||||
end
|
||||
puts
|
||||
|
||||
# Trac 'resolution' field as a Redmine custom field
|
||||
r = IssueCustomField.find(:first, :conditions => { :name => "Resolution" })
|
||||
r = IssueCustomField.new(:name => 'Resolution',
|
||||
:field_format => 'list',
|
||||
:is_filter => true) if r.nil?
|
||||
r.trackers = Tracker.find(:all)
|
||||
r.projects << @target_project
|
||||
r.possible_values = (r.possible_values + %w(fixed invalid wontfix duplicate worksforme)).flatten.compact.uniq
|
||||
r.save!
|
||||
custom_field_map['resolution'] = r
|
||||
|
||||
# Tickets
|
||||
print "Migrating tickets"
|
||||
TracTicket.find(:all, :order => 'id ASC').each do |ticket|
|
||||
print '.'
|
||||
STDOUT.flush
|
||||
i = Issue.new :project => @target_project,
|
||||
:subject => encode(ticket.summary[0, limit_for(Issue, 'subject')]),
|
||||
:description => convert_wiki_text(encode(ticket.description)),
|
||||
:priority => PRIORITY_MAPPING[ticket.priority] || DEFAULT_PRIORITY,
|
||||
:created_on => ticket.time
|
||||
i.author = find_or_create_user(ticket.reporter)
|
||||
i.category = issues_category_map[ticket.component] unless ticket.component.blank?
|
||||
i.fixed_version = version_map[ticket.milestone] unless ticket.milestone.blank?
|
||||
i.status = STATUS_MAPPING[ticket.status] || DEFAULT_STATUS
|
||||
i.tracker = TRACKER_MAPPING[ticket.ticket_type] || DEFAULT_TRACKER
|
||||
i.custom_values << CustomValue.new(:custom_field => custom_field_map['resolution'], :value => ticket.resolution) unless ticket.resolution.blank?
|
||||
i.id = ticket.id unless Issue.exists?(ticket.id)
|
||||
next unless Time.fake(ticket.changetime) { i.save }
|
||||
TICKET_MAP[ticket.id] = i.id
|
||||
migrated_tickets += 1
|
||||
|
||||
# Owner
|
||||
unless ticket.owner.blank?
|
||||
i.assigned_to = find_or_create_user(ticket.owner, true)
|
||||
Time.fake(ticket.changetime) { i.save }
|
||||
end
|
||||
|
||||
# Comments and status/resolution changes
|
||||
ticket.changes.group_by(&:time).each do |time, changeset|
|
||||
status_change = changeset.select {|change| change.field == 'status'}.first
|
||||
resolution_change = changeset.select {|change| change.field == 'resolution'}.first
|
||||
comment_change = changeset.select {|change| change.field == 'comment'}.first
|
||||
|
||||
n = Journal.new :notes => (comment_change ? convert_wiki_text(encode(comment_change.newvalue)) : ''),
|
||||
:created_on => time
|
||||
n.user = find_or_create_user(changeset.first.author)
|
||||
n.journalized = i
|
||||
if status_change &&
|
||||
STATUS_MAPPING[status_change.oldvalue] &&
|
||||
STATUS_MAPPING[status_change.newvalue] &&
|
||||
(STATUS_MAPPING[status_change.oldvalue] != STATUS_MAPPING[status_change.newvalue])
|
||||
n.details << JournalDetail.new(:property => 'attr',
|
||||
:prop_key => 'status_id',
|
||||
:old_value => STATUS_MAPPING[status_change.oldvalue].id,
|
||||
:value => STATUS_MAPPING[status_change.newvalue].id)
|
||||
end
|
||||
if resolution_change
|
||||
n.details << JournalDetail.new(:property => 'cf',
|
||||
:prop_key => custom_field_map['resolution'].id,
|
||||
:old_value => resolution_change.oldvalue,
|
||||
:value => resolution_change.newvalue)
|
||||
end
|
||||
n.save unless n.details.empty? && n.notes.blank?
|
||||
end
|
||||
|
||||
# Attachments
|
||||
ticket.attachments.each do |attachment|
|
||||
next unless attachment.exist?
|
||||
a = Attachment.new :created_on => attachment.time
|
||||
a.file = attachment
|
||||
a.author = find_or_create_user(attachment.author)
|
||||
a.container = i
|
||||
a.description = attachment.description
|
||||
migrated_ticket_attachments += 1 if a.save
|
||||
end
|
||||
|
||||
# Custom fields
|
||||
ticket.customs.each do |custom|
|
||||
next if custom_field_map[custom.name].nil?
|
||||
v = CustomValue.new :custom_field => custom_field_map[custom.name],
|
||||
:value => custom.value
|
||||
v.customized = i
|
||||
next unless v.save
|
||||
migrated_custom_values += 1
|
||||
end
|
||||
end
|
||||
|
||||
# update issue id sequence if needed (postgresql)
|
||||
Issue.connection.reset_pk_sequence!(Issue.table_name) if Issue.connection.respond_to?('reset_pk_sequence!')
|
||||
puts
|
||||
|
||||
# Wiki
|
||||
print "Migrating wiki"
|
||||
if wiki.save
|
||||
TracWikiPage.find(:all, :order => 'name, version').each do |page|
|
||||
# Do not migrate Trac manual wiki pages
|
||||
next if TRAC_WIKI_PAGES.include?(page.name)
|
||||
wiki_edit_count += 1
|
||||
print '.'
|
||||
STDOUT.flush
|
||||
p = wiki.find_or_new_page(page.name)
|
||||
p.content = WikiContent.new(:page => p) if p.new_record?
|
||||
p.content.text = page.text
|
||||
p.content.author = find_or_create_user(page.author) unless page.author.blank? || page.author == 'trac'
|
||||
p.content.comments = page.comment
|
||||
Time.fake(page.time) { p.new_record? ? p.save : p.content.save }
|
||||
|
||||
next if p.content.new_record?
|
||||
migrated_wiki_edits += 1
|
||||
|
||||
# Attachments
|
||||
page.attachments.each do |attachment|
|
||||
next unless attachment.exist?
|
||||
next if p.attachments.find_by_filename(attachment.filename.gsub(/^.*(\\|\/)/, '').gsub(/[^\w\.\-]/,'_')) #add only once per page
|
||||
a = Attachment.new :created_on => attachment.time
|
||||
a.file = attachment
|
||||
a.author = find_or_create_user(attachment.author)
|
||||
a.description = attachment.description
|
||||
a.container = p
|
||||
migrated_wiki_attachments += 1 if a.save
|
||||
end
|
||||
end
|
||||
|
||||
wiki.reload
|
||||
wiki.pages.each do |page|
|
||||
page.content.text = convert_wiki_text(page.content.text)
|
||||
Time.fake(page.content.updated_on) { page.content.save }
|
||||
end
|
||||
end
|
||||
puts
|
||||
|
||||
puts
|
||||
puts "Components: #{migrated_components}/#{TracComponent.count}"
|
||||
puts "Milestones: #{migrated_milestones}/#{TracMilestone.count}"
|
||||
puts "Tickets: #{migrated_tickets}/#{TracTicket.count}"
|
||||
puts "Ticket files: #{migrated_ticket_attachments}/" + TracAttachment.count(:conditions => {:type => 'ticket'}).to_s
|
||||
puts "Custom values: #{migrated_custom_values}/#{TracTicketCustom.count}"
|
||||
puts "Wiki edits: #{migrated_wiki_edits}/#{wiki_edit_count}"
|
||||
puts "Wiki files: #{migrated_wiki_attachments}/" + TracAttachment.count(:conditions => {:type => 'wiki'}).to_s
|
||||
end
|
||||
|
||||
def self.limit_for(klass, attribute)
|
||||
klass.columns_hash[attribute.to_s].limit
|
||||
end
|
||||
|
||||
def self.encoding(charset)
|
||||
@ic = Iconv.new('UTF-8', charset)
|
||||
rescue Iconv::InvalidEncoding
|
||||
puts "Invalid encoding!"
|
||||
return false
|
||||
end
|
||||
|
||||
def self.set_trac_directory(path)
|
||||
@@trac_directory = path
|
||||
raise "This directory doesn't exist!" unless File.directory?(path)
|
||||
raise "#{trac_attachments_directory} doesn't exist!" unless File.directory?(trac_attachments_directory)
|
||||
@@trac_directory
|
||||
rescue Exception => e
|
||||
puts e
|
||||
return false
|
||||
end
|
||||
|
||||
def self.trac_directory
|
||||
@@trac_directory
|
||||
end
|
||||
|
||||
def self.set_trac_adapter(adapter)
|
||||
return false if adapter.blank?
|
||||
raise "Unknown adapter: #{adapter}!" unless %w(sqlite sqlite3 mysql postgresql).include?(adapter)
|
||||
# If adapter is sqlite or sqlite3, make sure that trac.db exists
|
||||
raise "#{trac_db_path} doesn't exist!" if %w(sqlite sqlite3).include?(adapter) && !File.exist?(trac_db_path)
|
||||
@@trac_adapter = adapter
|
||||
rescue Exception => e
|
||||
puts e
|
||||
return false
|
||||
end
|
||||
|
||||
def self.set_trac_db_host(host)
|
||||
return nil if host.blank?
|
||||
@@trac_db_host = host
|
||||
end
|
||||
|
||||
def self.set_trac_db_port(port)
|
||||
return nil if port.to_i == 0
|
||||
@@trac_db_port = port.to_i
|
||||
end
|
||||
|
||||
def self.set_trac_db_name(name)
|
||||
return nil if name.blank?
|
||||
@@trac_db_name = name
|
||||
end
|
||||
|
||||
def self.set_trac_db_username(username)
|
||||
@@trac_db_username = username
|
||||
end
|
||||
|
||||
def self.set_trac_db_password(password)
|
||||
@@trac_db_password = password
|
||||
end
|
||||
|
||||
def self.set_trac_db_schema(schema)
|
||||
@@trac_db_schema = schema
|
||||
end
|
||||
|
||||
mattr_reader :trac_directory, :trac_adapter, :trac_db_host, :trac_db_port, :trac_db_name, :trac_db_schema, :trac_db_username, :trac_db_password
|
||||
|
||||
def self.trac_db_path; "#{trac_directory}/db/trac.db" end
|
||||
def self.trac_attachments_directory; "#{trac_directory}/attachments" end
|
||||
|
||||
def self.target_project_identifier(identifier)
|
||||
project = Project.find_by_identifier(identifier)
|
||||
if !project
|
||||
# create the target project
|
||||
project = Project.new :name => identifier.humanize,
|
||||
:description => ''
|
||||
project.identifier = identifier
|
||||
puts "Unable to create a project with identifier '#{identifier}'!" unless project.save
|
||||
# enable issues and wiki for the created project
|
||||
project.enabled_module_names = ['issue_tracking', 'wiki']
|
||||
else
|
||||
puts
|
||||
puts "This project already exists in your Redmine database."
|
||||
print "Are you sure you want to append data to this project ? [Y/n] "
|
||||
exit if STDIN.gets.match(/^n$/i)
|
||||
end
|
||||
project.trackers << TRACKER_BUG unless project.trackers.include?(TRACKER_BUG)
|
||||
project.trackers << TRACKER_FEATURE unless project.trackers.include?(TRACKER_FEATURE)
|
||||
@target_project = project.new_record? ? nil : project
|
||||
end
|
||||
|
||||
def self.connection_params
|
||||
if %w(sqlite sqlite3).include?(trac_adapter)
|
||||
{:adapter => trac_adapter,
|
||||
:database => trac_db_path}
|
||||
else
|
||||
{:adapter => trac_adapter,
|
||||
:database => trac_db_name,
|
||||
:host => trac_db_host,
|
||||
:port => trac_db_port,
|
||||
:username => trac_db_username,
|
||||
:password => trac_db_password,
|
||||
:schema_search_path => trac_db_schema
|
||||
}
|
||||
end
|
||||
end
|
||||
|
||||
def self.establish_connection
|
||||
constants.each do |const|
|
||||
klass = const_get(const)
|
||||
next unless klass.respond_to? 'establish_connection'
|
||||
klass.establish_connection connection_params
|
||||
end
|
||||
end
|
||||
|
||||
private
|
||||
def self.encode(text)
|
||||
@ic.iconv text
|
||||
rescue
|
||||
text
|
||||
end
|
||||
end
|
||||
|
||||
puts
|
||||
if Redmine::DefaultData::Loader.no_data?
|
||||
puts "Redmine configuration need to be loaded before importing data."
|
||||
puts "Please, run this first:"
|
||||
puts
|
||||
puts " rake redmine:load_default_data RAILS_ENV=\"#{ENV['RAILS_ENV']}\""
|
||||
exit
|
||||
end
|
||||
|
||||
puts "WARNING: a new project will be added to Redmine during this process."
|
||||
print "Are you sure you want to continue ? [y/N] "
|
||||
break unless STDIN.gets.match(/^y$/i)
|
||||
puts
|
||||
|
||||
def prompt(text, options = {}, &block)
|
||||
default = options[:default] || ''
|
||||
while true
|
||||
print "#{text} [#{default}]: "
|
||||
value = STDIN.gets.chomp!
|
||||
value = default if value.blank?
|
||||
break if yield value
|
||||
end
|
||||
end
|
||||
|
||||
DEFAULT_PORTS = {'mysql' => 3306, 'postgresql' => 5432}
|
||||
|
||||
prompt('Trac directory') {|directory| TracMigrate.set_trac_directory directory.strip}
|
||||
prompt('Trac database adapter (sqlite, sqlite3, mysql, postgresql)', :default => 'sqlite') {|adapter| TracMigrate.set_trac_adapter adapter}
|
||||
unless %w(sqlite sqlite3).include?(TracMigrate.trac_adapter)
|
||||
prompt('Trac database host', :default => 'localhost') {|host| TracMigrate.set_trac_db_host host}
|
||||
prompt('Trac database port', :default => DEFAULT_PORTS[TracMigrate.trac_adapter]) {|port| TracMigrate.set_trac_db_port port}
|
||||
prompt('Trac database name') {|name| TracMigrate.set_trac_db_name name}
|
||||
prompt('Trac database schema', :default => 'public') {|schema| TracMigrate.set_trac_db_schema schema}
|
||||
prompt('Trac database username') {|username| TracMigrate.set_trac_db_username username}
|
||||
prompt('Trac database password') {|password| TracMigrate.set_trac_db_password password}
|
||||
end
|
||||
prompt('Trac database encoding', :default => 'UTF-8') {|encoding| TracMigrate.encoding encoding}
|
||||
prompt('Target project identifier') {|identifier| TracMigrate.target_project_identifier identifier}
|
||||
puts
|
||||
|
||||
TracMigrate.migrate
|
||||
end
|
||||
end
|
||||
|
||||
@@ -0,0 +1,15 @@
|
||||
namespace :db do
|
||||
desc 'Migrates installed plugins.'
|
||||
task :migrate_plugins => :environment do
|
||||
if Rails.respond_to?('plugins')
|
||||
Rails.plugins.each do |plugin|
|
||||
next unless plugin.respond_to?('migrate')
|
||||
puts "Migrating #{plugin.name}..."
|
||||
plugin.migrate
|
||||
end
|
||||
else
|
||||
puts "Undefined method plugins for Rails!"
|
||||
puts "Make sure engines plugin is installed."
|
||||
end
|
||||
end
|
||||
end
|
||||
@@ -0,0 +1,38 @@
|
||||
require 'source_annotation_extractor'
|
||||
|
||||
# Modified version of the SourceAnnotationExtractor in railties
|
||||
# Will search for runable code that uses <tt>call_hook</tt>
|
||||
class PluginSourceAnnotationExtractor < SourceAnnotationExtractor
|
||||
# Returns a hash that maps filenames under +dir+ (recursively) to arrays
|
||||
# with their annotations. Only files with annotations are included, and only
|
||||
# those with extension +.builder+, +.rb+, +.rxml+, +.rjs+, +.rhtml+, and +.erb+
|
||||
# are taken into account.
|
||||
def find_in(dir)
|
||||
results = {}
|
||||
|
||||
Dir.glob("#{dir}/*") do |item|
|
||||
next if File.basename(item)[0] == ?.
|
||||
|
||||
if File.directory?(item)
|
||||
results.update(find_in(item))
|
||||
elsif item =~ /(hook|test)\.rb/
|
||||
# skip
|
||||
elsif item =~ /\.(builder|(r(?:b|xml|js)))$/
|
||||
results.update(extract_annotations_from(item, /\s*(#{tag})\(?\s*(.*)$/))
|
||||
elsif item =~ /\.(rhtml|erb)$/
|
||||
results.update(extract_annotations_from(item, /<%=\s*\s*(#{tag})\(?\s*(.*?)\s*%>/))
|
||||
end
|
||||
end
|
||||
|
||||
results
|
||||
end
|
||||
end
|
||||
|
||||
namespace :redmine do
|
||||
namespace :plugins do
|
||||
desc "Enumerate all Redmine plugin hooks and their context parameters"
|
||||
task :hook_list do
|
||||
PluginSourceAnnotationExtractor.enumerate 'call_hook'
|
||||
end
|
||||
end
|
||||
end
|
||||
@@ -0,0 +1,39 @@
|
||||
# redMine - project management software
|
||||
# Copyright (C) 2008 Jean-Philippe Lang
|
||||
#
|
||||
# This program is free software; you can redistribute it and/or
|
||||
# modify it under the terms of the GNU General Public License
|
||||
# as published by the Free Software Foundation; either version 2
|
||||
# of the License, or (at your option) any later version.
|
||||
#
|
||||
# This program is distributed in the hope that it will be useful,
|
||||
# but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
# GNU General Public License for more details.
|
||||
#
|
||||
# You should have received a copy of the GNU General Public License
|
||||
# along with this program; if not, write to the Free Software
|
||||
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
|
||||
|
||||
desc <<-END_DESC
|
||||
Send reminders about issues due in the next days.
|
||||
|
||||
Available options:
|
||||
* days => number of days to remind about (defaults to 7)
|
||||
* tracker => id of tracker (defaults to all trackers)
|
||||
* project => id or identifier of project (defaults to all projects)
|
||||
|
||||
Example:
|
||||
rake redmine:send_reminders days=7 RAILS_ENV="production"
|
||||
END_DESC
|
||||
|
||||
namespace :redmine do
|
||||
task :send_reminders => :environment do
|
||||
options = {}
|
||||
options[:days] = ENV['days'].to_i if ENV['days']
|
||||
options[:project] = ENV['project'] if ENV['project']
|
||||
options[:tracker] = ENV['tracker'].to_i if ENV['tracker']
|
||||
|
||||
Mailer.reminders(options)
|
||||
end
|
||||
end
|
||||
@@ -0,0 +1,46 @@
|
||||
### From http://svn.geekdaily.org/public/rails/plugins/generally_useful/tasks/coverage_via_rcov.rake
|
||||
|
||||
### Inspired by http://blog.labratz.net/articles/2006/12/2/a-rake-task-for-rcov
|
||||
begin
|
||||
require 'rcov/rcovtask'
|
||||
|
||||
rcov_options = "--rails --aggregate test/coverage.data --exclude '/gems/'"
|
||||
|
||||
namespace :test do
|
||||
desc "Aggregate code coverage for all tests"
|
||||
Rcov::RcovTask.new('coverage') do |t|
|
||||
t.libs << 'test'
|
||||
t.test_files = FileList['test/{unit,integration,functional}/*_test.rb']
|
||||
t.verbose = true
|
||||
t.rcov_opts << rcov_options
|
||||
end
|
||||
|
||||
namespace :coverage do
|
||||
desc "Delete coverage test data"
|
||||
task :clean do
|
||||
rm_f "test/coverage.data"
|
||||
rm_rf "test/coverage"
|
||||
end
|
||||
|
||||
desc "Aggregate code coverage for all tests with HTML output"
|
||||
Rcov::RcovTask.new('html') do |t|
|
||||
t.libs << 'test'
|
||||
t.test_files = FileList['test/{unit,integration,functional}/*_test.rb']
|
||||
t.output_dir = "test/coverage"
|
||||
t.verbose = true
|
||||
t.rcov_opts << rcov_options
|
||||
end
|
||||
|
||||
desc "Open the HTML coverage report"
|
||||
task :show_results do
|
||||
system "open test/coverage/index.html"
|
||||
end
|
||||
|
||||
task :full => "test:coverage:clean"
|
||||
task :full => "test:coverage:html"
|
||||
task :full => "test:coverage:show_results"
|
||||
end
|
||||
end
|
||||
rescue LoadError
|
||||
# rcov not available
|
||||
end
|
||||
Reference in New Issue
Block a user