GNU GENERAL PUBLIC LICENSE
Version 2, June 1991
Version 3, 29 June 2007
Copyright (C) 1989, 1991 Free Software Foundation, Inc.
59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The GNU General Public License is a free, copyleft license for
software and other kinds of works.
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
The licenses for most software and other practical works are designed
to take away your freedom to share and change the works. By contrast,
the GNU General Public License is intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users. We, the Free Software Foundation, use the
GNU General Public License for most of our software; it applies also to
any other work released this way by its authors. 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.
them 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.
To protect your rights, we need to prevent others from denying you
these rights or asking you to surrender the rights. Therefore, you have
certain responsibilities if you distribute copies of the software, or if
you modify it: responsibilities to respect the freedom of others.
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.
gratis or for a fee, you must pass on to the recipients the same
freedoms that you received. 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.
Developers that use the GNU GPL protect your rights with two steps:
(1) assert copyright on the software, and (2) offer you this License
giving you legal permission to copy, distribute and/or modify it.
For the developers' and authors' protection, the GPL clearly explains
that there is no warranty for this free software. For both users' and
authors' sake, the GPL requires that modified versions be marked as
changed, so that their problems will not be attributed erroneously to
authors of previous versions.
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.
Some devices are designed to deny users access to install or run
modified versions of the software inside them, although the manufacturer
can do so. This is fundamentally incompatible with the aim of
protecting users' freedom to change the software. The systematic
pattern of such abuse occurs in the area of products for individuals to
use, which is precisely where it is most unacceptable. Therefore, we
have designed this version of the GPL to prohibit the practice for those
products. If such problems arise substantially in other domains, we
stand ready to extend this provision to those domains in future versions
of the GPL, as needed to protect the freedom of users.
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.
Finally, every program is threatened constantly by software patents.
States should not allow patents to restrict development and use of
software on general-purpose computers, but in those that do, we wish to
avoid the special danger that patents applied to a free program could
make it effectively proprietary. To prevent this, the GPL assures that
patents cannot be used to render the program non-free.
The precise terms and conditions for copying, distribution and
modification follow.
TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
TERMS AND CONDITIONS
0. Definitions.
"This License" refers to version 3 of the GNU General Public License.
"Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.
"The Program" refers to any copyrightable work licensed under this
License. Each licensee is addressed as "you". "Licensees" and
"recipients" may be individuals or organizations.
To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of an
exact copy. The resulting work is called a "modified version" of the
earlier work or a work "based on" the earlier work.
A "covered work" means either the unmodified Program or a work based
on the Program.
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".
To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy. Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.
To "convey" a work means any kind of propagation that enables other
parties to make or receive copies. Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.
An interactive user interface displays "Appropriate Legal Notices"
to the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License. If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.
1. Source Code.
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.
The "source code" for a work means the preferred form of the work
for making modifications to it. "Object code" means any non-source
form of a work.
A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.
The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form. A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.
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.
The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities. However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work. For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.
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.
The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.
The Corresponding Source for a work in source code form is that
same work.
2. Basic Permissions.
All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met. This License explicitly affirms your unlimited
permission to run the unmodified Program. The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work. This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.
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:
You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains
in force. You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you
with facilities for running those works, provided that you comply with
the terms of this License in conveying all material for which you do
not control copyright. Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely under
the conditions stated below. Sublicensing is not allowed; section 10
makes it unnecessary.
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.
a) You must cause the modified files to carry prominent notices
stating that you changed the files and the date of any change.
When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of
technological measures.
4. Conveying Verbatim Copies.
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.
You may convey 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;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.
5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these conditions:
a) The work must carry prominent notices stating that you modified
it, and giving a relevant date.
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.)
b) The work must carry prominent notices stating that it is
released under this License and any conditions added under section
7. This requirement modifies the requirement in section 4 to
"keep intact all notices".
c) You must license the entire work, as a whole, under this
License to anyone who comes into possession of a copy. This
License will therefore apply, along with any applicable section 7
additional terms, to the whole of the work, and all its parts,
regardless of how they are packaged. This License gives no
permission to license the work in any other way, but it does not
invalidate such permission if you have separately received it.
d) If the work has interactive user interfaces, each must display
Appropriate Legal Notices; however, if the Program has interactive
interfaces that do not display Appropriate Legal Notices, your
work need not make them do so.
A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit. Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.
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.
6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:
a) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by the
Corresponding Source fixed on a durable physical medium
customarily used for software interchange.
b) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by a
written offer, valid for at least three years and valid for as
long as you offer spare parts or customer support for that product
model, to give anyone who possesses the object code either (1) a
copy of the Corresponding Source for all the software in the
product that is covered by this License, on a durable physical
medium customarily used for software interchange, for a price no
more than your reasonable cost of physically performing this
conveying of source, or (2) access to copy the
Corresponding Source from a network server at no charge.
c) Convey individual copies of the object code with a copy of the
written offer to provide the Corresponding Source. This
alternative is allowed only occasionally and noncommercially, and
only if you received the object code with such an offer, in accord
with subsection 6b.
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.
d) Convey the object code by offering access from a designated
place (gratis or for a charge), and offer equivalent access to the
Corresponding Source in the same way through the same place at no
further charge. You need not require recipients to copy the
Corresponding Source along with the object code. If the place to
copy the object code is a network server, the Corresponding Source
may be on a different server (operated by you or a third party)
that supports equivalent copying facilities, provided you maintain
clear directions next to the object code saying where to find the
Corresponding Source. Regardless of what server hosts the
Corresponding Source, you remain obligated to ensure that it is
available for as long as needed to satisfy these requirements.
e) Convey the object code using peer-to-peer transmission, provided
you inform other peers where the object code and Corresponding
Source of the work are being offered to the general public at no
charge under subsection 6d.
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.
A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.
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 "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for incorporation
into a dwelling. In determining whether a product is a consumer product,
doubtful cases shall be resolved in favor of coverage. For a particular
product received by a particular user, "normally used" refers to a
typical or common use of that class of product, regardless of the status
of the particular user or of the way in which the particular user
actually uses, or expects or is expected to use, the product. A product
is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.
"Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to install
and execute modified versions of a covered work in that User Product from
a modified version of its Corresponding Source. The information must
suffice to ensure that the continued functioning of the modified object
code is in no case prevented or interfered with solely because
modification has been made.
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,
If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information. But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).
The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for
the User Product in which it has been modified or installed. Access to a
network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and
protocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.
7. Additional Terms.
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,
"Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law. If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it. (Additional permissions may be written to require their own
removal in certain cases when you modify the work.) You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.
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.)
Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:
a) Disclaiming warranty or limiting liability differently from the
terms of sections 15 and 16 of this License; or
b) Requiring preservation of specified reasonable legal notices or
author attributions in that material or in the Appropriate Legal
Notices displayed by works containing it; or
c) Prohibiting misrepresentation of the origin of that material, or
requiring that modified versions of such material be marked in
reasonable ways as different from the original version; or
d) Limiting the use for publicity purposes of names of licensors or
authors of the material; or
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.
e) Declining to grant rights under trademark law for use of some
trade names, trademarks, or service marks; or
f) Requiring indemnification of licensors and authors of that
material by anyone who conveys the material (or modified versions of
it) with contractual assumptions of liability to the recipient, for
any liability that these contractual assumptions directly impose on
those licensors and authors.
All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10. If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term. If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.
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.
Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions;
the above requirements apply either way.
8. Termination.
You may not propagate or modify a covered work except as expressly
provided under this License. Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).
However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated (a)
provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and (b) permanently, if the copyright
holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.
Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.
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.
Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License. If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.
9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive or
run a copy of the Program. Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance. However,
nothing other than this License grants you permission to propagate or
modify any covered work. These actions infringe copyright if you do
not accept this License. Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.
10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License. You are not responsible
for enforcing compliance by third parties with this License.
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.
An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations. If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.
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
You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License. For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.
11. Patents.
A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based. The
work thus licensed is called the contributor's "contributor version".
A contributor's "essential patent claims" are all patent claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version. For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
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.
Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.
In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement). To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.
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.
If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients. "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.
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.
A patent license is "discriminatory" if it does not include within
the scope of its coverage, prohibits the exercise of, or is
conditioned on the non-exercise of one or more of the rights that are
specifically granted under this License. You may not convey a covered
work if you are a party to an arrangement with a third party that is
in the business of distributing software, under which you make payment
to the third party based on the extent of your activity of conveying
the work, and under which the third party grants, to any of the
parties who would receive the covered work from you, a discriminatory
patent license (a) in connection with copies of the covered work
conveyed by you (or copies made from those copies), or (b) primarily
for and in connection with specific products or compilations that
contain the covered work, unless you entered into that arrangement,
or that patent license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.
12. No Surrender of Others' Freedom.
This section is intended to make thoroughly clear what is believed to
be a consequence of the rest of this License.
If conditions are imposed on you (whether by court order, agreement or
excuse you from the conditions of this License. If you cannot convey a
covered work so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you may
not convey it at all. For example, if you agree to terms that obligate you
to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.
13. Use with the GNU Affero General Public 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.
Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU Affero General Public License into a single
combined work, and to convey the resulting work. The terms of this
License will continue to apply to the part which is the covered work,
but the special requirements of the GNU Affero General Public License,
section 13, concerning interaction through a network will apply to the
combination as such.
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
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of
the GNU 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.
Each version is given a distinguishing version number. If the
Program specifies that a certain numbered version of the GNU General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation. If the Program does not specify a version number of the
GNU General Public 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.
If the Program specifies that a proxy can decide which future
versions of the GNU General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.
NO WARRANTY
Later license versions may give you additional or different
permissions. However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.
15. Disclaimer of 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.
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.
16. Limitation of Liability.
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.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
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
17. Interpretation of Sections 15 and 16.
How to Apply These Terms to Your New Programs
If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.
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
state 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
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
the Free Software Foundation, either version 3 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
along with this program. If not, see <http://www.gnu.org/licenses/>.
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:
If the program does terminal interaction, 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'.
<program> Copyright (C) <year> <name of author>
This program 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:
parts of the General Public License. Of course, your program's commands
might be different; for a GUI interface, you would use an "about box".
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
You should also get your employer (if you work as a programmer) or school,
if any, to sign a "copyright disclaimer" for the program, if necessary.
For more information on this, and how to apply and follow the GNU GPL, see
<http://www.gnu.org/licenses/>.
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.
The GNU 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 Lesser General
Public License instead of this License. But first, please read
<http://www.gnu.org/philosophy/why-not-lgpl.html>.
=================================================
Welcome to RhodeCode (RhodiumCode) documentation!
``RhodeCode`` (formerly hg-app) is a Pylons framework based Mercurial repository
browser/management tool with a built in push/pull server and full text search.
It works on http/https and has a built in permission/authentication system with
the ability to authenticate via LDAP.
RhodeCode is similar in some respects to github or bitbucket_,
however RhodeCode can be run as standalone hosted application on your own server.
It is open source and donation ware and focuses more on providing a customized,
self administered interface for Mercurial(and soon GIT) repositories.
RhodeCode is powered by a vcs_ library that Lukasz Balcerzak and I created to
handle multiple different version control systems.
RhodeCode uses `Semantic Versioning <http://semver.org/>`_
RhodeCode demo
--------------
http://demo.rhodecode.org
The default access is anonymous but you can login to an administrative account
using the following credentials:
- username: demo
- password: demo
Source code
-----------
The latest sources can be obtained from official RhodeCode instance
https://hg.rhodecode.org
MIRRORS:
Issue tracker and sources at bitbucket_
http://bitbucket.org/marcinkuzminski/rhodecode
Sources at github_
https://github.com/marcinkuzminski/rhodecode
Installation
------------
Please visit http://packages.python.org/RhodeCode/installation.html
RhodeCode Features
------------------
- Has it's own middleware to handle mercurial_ protocol requests.
Each request can be logged and authenticated.
- Runs on threads unlike hgweb. You can make multiple pulls/pushes simultaneous.
Supports http/https and LDAP
- Full permissions (private/read/write/admin) and authentication per project.
One account for web interface and mercurial_ push/pull/clone operations.
- Have built in users groups for easier permission management
- Users can fork other users repo. RhodeCode have also compare view to see
combined changeset for all changeset made within single push.
- Mako templates let's you customize the look and feel of the application.
- Beautiful diffs, annotations and source code browsing all colored by pygments.
Raw diffs are made in git-diff format, including git_ binary-patches
- Mercurial_ branch graph and yui-flot powered graphs with zooming and statistics
- Admin interface with user/permission management. Admin activity journal, logs
pulls, pushes, forks, registrations and other actions made by all users.
- Server side forks. It is possible to fork a project and modify it freely
without breaking the main repository. You can even write Your own hooks
and install them
- Full text search powered by Whoosh on the source files, and file names.
Build in indexing daemons, with optional incremental index build
(no external search servers required all in one application)
- Setup project descriptions and info inside built in db for easy, non
file-system operations
- Intelligent cache with invalidation after push or project change, provides
high performance and always up to date data.
- Rss / atom feeds, gravatar support, download sources as zip/tar/gz
- Async tasks for speed and performance using celery_ (works without them too)
- Backup scripts can do backup of whole app and send it over scp to desired
location
- Based on pylons / sqlalchemy / sqlite / whoosh / vcs
.. include:: ./docs/screenshots.rst
Incoming / Plans
----------------
- Project grouping
- Server side tagging
- Server side code edit
- Finer granular permissions (per branch or subrepo)
- SSH based authentication with server side key management
- Code review (probably based on hg-review)
- Full git_ support, with push/pull server (currently in beta tests)
- Redmine integration
- Commit based built in wiki system
- More statistics and graph (global annotation + some more statistics)
- Other advancements as development continues (or you can of course make
additions and or requests)
License
-------
``RhodeCode`` is released under the GPL_ license.
``RhodeCode`` is released under the GPLv3 license.
Mailing group Q&A
-----------------
Join the `Google group <http://groups.google.com/group/rhodecode>`_
Open an issue at `issue tracker <http://bitbucket.org/marcinkuzminski/rhodecode/issues>`_
Join #rhodecode on FreeNode (irc.freenode.net)
or use http://webchat.freenode.net/?channels=rhodecode for web access to irc.
Online documentation
--------------------
Online documentation for the current version of RhodeCode is available at
http://packages.python.org/RhodeCode/.
You may also build the documentation for yourself - go into ``docs/`` and run::
make html
(You need to have sphinx_ installed to build the documentation. If you don't
have sphinx_ installed you can install it via the command:
``easy_install sphinx``)
.. _virtualenv: http://pypi.python.org/pypi/virtualenv
.. _python: http://www.python.org/
.. _sphinx: http://sphinx.pocoo.org/
.. _mercurial: http://mercurial.selenic.com/
.. _bitbucket: http://bitbucket.org/
.. _github: http://github.com/
.. _subversion: http://subversion.tigris.org/
.. _git: http://git-scm.com/
.. _celery: http://celeryproject.org/
.. _Sphinx: http://sphinx.pocoo.org/
.. _GPL: http://www.gnu.org/licenses/gpl.html
.. _vcs: http://pypi.python.org/pypi/vcs
\ No newline at end of file
.. _index:
.. include:: ./../README.rst
Documentation
-------------
**Installation:**
.. toctree::
:maxdepth: 1
installation
setup
upgrade
**Usage**
usage/general
usage/enable_git
usage/statistics
usage/backup
usage/api_key_access
**Develop**
contributing
changelog
**API**
:maxdepth: 2
api/index
Other topics
* :ref:`genindex`
* :ref:`search`
.. _django: http://www.djangoproject.com/
# -*- coding: utf-8 -*-
"""
rhodecode.__init__
~~~~~~~~~~~~~~~~~~
RhodeCode, a web based repository management based on pylons
versioning implementation: http://semver.org/
:created_on: Apr 9, 2010
:author: marcink
:copyright: (C) 2009-2011 Marcin Kuzminski <marcin@python-works.com>
:license: GPLv3, see COPYING for more details.
# 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; version 2
# of the License or (at your opinion) any later version of the license.
# 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 3 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.
# along with this program. If not, see <http://www.gnu.org/licenses/>.
import platform
VERSION = (1, 2, 0, 'beta')
__version__ = '.'.join((str(each) for each in VERSION[:4]))
__dbversion__ = 3 #defines current db version for migrations
__platform__ = platform.system()
__license__ = 'GPLv3'
PLATFORM_WIN = ('Windows')
PLATFORM_OTHERS = ('Linux', 'Darwin', 'FreeBSD')
try:
from rhodecode.lib.utils import get_current_revision
_rev = get_current_revision()
except ImportError:
#this is needed when doing some setup.py operations
_rev = False
if len(VERSION) > 3 and _rev:
__version__ += ' [rev:%s]' % _rev[0]
def get_version():
"""Returns shorter version (digit parts only) as string."""
return '.'.join((str(each) for each in VERSION[:3]))
BACKENDS = {
'hg': 'Mercurial repository',
#'git': 'Git repository',
}
rhodecode.controllers.admin.admin
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Controller for Admin panel of Rhodecode
:created_on: Apr 7, 2010
import logging
from pylons import request, tmpl_context as c
from sqlalchemy.orm import joinedload
from webhelpers.paginate import Page
from rhodecode.lib.auth import LoginRequired, HasPermissionAllDecorator
from rhodecode.lib.base import BaseController, render
from rhodecode.model.db import UserLog
log = logging.getLogger(__name__)
class AdminController(BaseController):
@LoginRequired()
def __before__(self):
super(AdminController, self).__before__()
@HasPermissionAllDecorator('hg.admin')
def index(self):
users_log = self.sa.query(UserLog)\
.options(joinedload(UserLog.user))\
.options(joinedload(UserLog.repository))\
.order_by(UserLog.action_date.desc())
p = int(request.params.get('page', 1))
c.users_log = Page(users_log, page=p, items_per_page=10)
c.log_data = render('admin/admin_log.html')
if request.params.get('partial'):
return c.log_data
return render('admin/admin.html')
rhodecode.controllers.admin.ldap_settings
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
ldap controller for RhodeCode
:created_on: Nov 26, 2010
import formencode
import traceback
from formencode import htmlfill
from pylons import request, response, session, tmpl_context as c, url
from pylons.controllers.util import abort, redirect
from pylons.i18n.translation import _
from rhodecode.lib import helpers as h
from rhodecode.lib.auth_ldap import LdapImportError
from rhodecode.model.settings import SettingsModel
from rhodecode.model.forms import LdapSettingsForm
from sqlalchemy.exc import DatabaseError
class LdapSettingsController(BaseController):
search_scope_choices = [('BASE', _('BASE'),),
('ONELEVEL', _('ONELEVEL'),),
('SUBTREE', _('SUBTREE'),),
]
search_scope_default = 'SUBTREE'
tls_reqcert_choices = [('NEVER', _('NEVER'),),
('ALLOW', _('ALLOW'),),
('TRY', _('TRY'),),
('DEMAND', _('DEMAND'),),
('HARD', _('HARD'),),
tls_reqcert_default = 'DEMAND'
c.admin_user = session.get('admin_user')
c.admin_username = session.get('admin_username')
c.search_scope_choices = self.search_scope_choices
c.tls_reqcert_choices = self.tls_reqcert_choices
super(LdapSettingsController, self).__before__()
defaults = SettingsModel().get_ldap_settings()
c.search_scope_cur = defaults.get('ldap_search_scope')
c.tls_reqcert_cur = defaults.get('ldap_tls_reqcert')
return htmlfill.render(
render('admin/ldap/ldap.html'),
defaults=defaults,
encoding="UTF-8",
force_defaults=True,)
def ldap_settings(self):
"""POST ldap create and store ldap settings"""
settings_model = SettingsModel()
_form = LdapSettingsForm([x[0] for x in self.tls_reqcert_choices],
[x[0] for x in self.search_scope_choices])()
form_result = _form.to_python(dict(request.POST))
for k, v in form_result.items():
if k.startswith('ldap_'):
setting = settings_model.get(k)
setting.app_settings_value = v
self.sa.add(setting)
self.sa.commit()
h.flash(_('Ldap settings updated successfully'),
category='success')
except (DatabaseError,):
raise
except LdapImportError:
h.flash(_('Unable to activate ldap. The "python-ldap" library '
'is missing.'), category='warning')
except formencode.Invalid, errors:
c.search_scope_cur = self.search_scope_default
c.tls_reqcert_cur = self.search_scope_default
defaults=errors.value,
errors=errors.error_dict or {},
prefix_error=False,
encoding="UTF-8")
except Exception:
log.error(traceback.format_exc())
h.flash(_('error occurred during update of ldap settings'),
category='error')
return redirect(url('ldap_home'))
rhodecode.controllers.admin.permissions
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
permissions controller for Rhodecode
:created_on: Apr 27, 2010
from pylons import request, session, tmpl_context as c, url
from rhodecode.model.forms import LdapSettingsForm, DefaultPermissionsForm
from rhodecode.model.permission import PermissionModel
from rhodecode.model.user import UserModel
class PermissionsController(BaseController):
"""REST Controller styled on the Atom Publishing Protocol"""
# To properly map this controller, ensure your config/routing.py
# file has a resource setup:
# map.resource('permission', 'permissions')
super(PermissionsController, self).__before__()
self.perms_choices = [('repository.none', _('None'),),
('repository.read', _('Read'),),
('repository.write', _('Write'),),
('repository.admin', _('Admin'),)]
self.register_choices = [
('hg.register.none',
_('disabled')),
('hg.register.manual_activate',
_('allowed with manual account activation')),
('hg.register.auto_activate',
_('allowed with automatic account activation')), ]
self.create_choices = [('hg.create.none', _('Disabled')),
('hg.create.repository', _('Enabled'))]
def index(self, format='html'):
"""GET /permissions: All items in the collection"""
# url('permissions')
def create(self):
"""POST /permissions: Create a new item"""
def new(self, format='html'):
"""GET /permissions/new: Form to create a new item"""
# url('new_permission')
def update(self, id):
"""PUT /permissions/id: Update an existing item"""
# Forms posted to this method should contain a hidden field:
# <input type="hidden" name="_method" value="PUT" />
# Or using helpers:
# h.form(url('permission', id=ID),
# method='put')
# url('permission', id=ID)
permission_model = PermissionModel()
_form = DefaultPermissionsForm([x[0] for x in self.perms_choices],
[x[0] for x in self.register_choices],
[x[0] for x in self.create_choices])()
form_result.update({'perm_user_name':id})
permission_model.update(form_result)
h.flash(_('Default permissions updated successfully'),
c.perms_choices = self.perms_choices
c.register_choices = self.register_choices
c.create_choices = self.create_choices
defaults = errors.value
render('admin/permissions/permissions.html'),
h.flash(_('error occurred during update of permissions'),
return redirect(url('edit_permission', id=id))
def delete(self, id):
"""DELETE /permissions/id: Delete an existing item"""
# <input type="hidden" name="_method" value="DELETE" />
# method='delete')
def show(self, id, format='html'):
"""GET /permissions/id: Show a specific item"""
def edit(self, id, format='html'):
"""GET /permissions/id/edit: Form to edit an existing item"""
#url('edit_permission', id=ID)
if id == 'default':
default_user = UserModel().get_by_username('default')
defaults = {'_method':'put',
'anonymous':default_user.active}
for p in default_user.user_perms:
if p.permission.permission_name.startswith('repository.'):
defaults['default_perm'] = p.permission.permission_name
if p.permission.permission_name.startswith('hg.register.'):
defaults['default_register'] = p.permission.permission_name
if p.permission.permission_name.startswith('hg.create.'):
defaults['default_create'] = p.permission.permission_name
else:
return redirect(url('admin_home'))
rhodecode.controllers.admin.repos
Admin controller for RhodeCode
from operator import itemgetter
from paste.httpexceptions import HTTPInternalServerError
from rhodecode.lib.auth import LoginRequired, HasPermissionAllDecorator, \
HasPermissionAnyDecorator
from rhodecode.lib.utils import invalidate_cache, action_logger, repo_name_slug
from rhodecode.lib.helpers import get_token
from rhodecode.model.db import User, Repository, UserFollowing, Group
from rhodecode.model.forms import RepoForm
from rhodecode.model.scm import ScmModel
from rhodecode.model.repo import RepoModel
class ReposController(BaseController):
REST Controller styled on the Atom Publishing Protocol"""
# map.resource('repo', 'repos')
@HasPermissionAnyDecorator('hg.admin', 'hg.create.repository')
super(ReposController, self).__before__()
def __load_defaults(self):
repo_model = RepoModel()
c.repo_groups = [('', '')]
parents_link = lambda k:h.literal('»'.join(
map(lambda k:k.group_name,
k.parents + [k])
)
c.repo_groups.extend([(x.group_id, parents_link(x)) for \
x in self.sa.query(Group).all()])
c.repo_groups_choices = map(lambda k: unicode(k[0]), c.repo_groups)
c.users_array = repo_model.get_users_js()
c.users_groups_array = repo_model.get_users_groups_js()
def __load_data(self, repo_name=None):
Load defaults settings for edit, and update
:param repo_name:
self.__load_defaults()
repo, dbrepo = ScmModel().get(repo_name, retval='repo')
c.repo_info = repo_model.get_by_repo_name(repo_name)
if c.repo_info is None:
h.flash(_('%s repository is not mapped to db perhaps'
' it was created or renamed from the filesystem'
' please run the application again'
' in order to rescan repositories') % repo_name,
return redirect(url('repos'))
c.default_user_id = User.by_username('default').user_id
c.in_public_journal = self.sa.query(UserFollowing)\
.filter(UserFollowing.user_id == c.default_user_id)\
.filter(UserFollowing.follows_repository == c.repo_info).scalar()
if c.repo_info.stats:
last_rev = c.repo_info.stats.stat_on_revision
last_rev = 0
c.stats_revision = last_rev
c.repo_last_rev = repo.count() - 1 if repo.revisions else 0
if last_rev == 0 or c.repo_last_rev == 0:
c.stats_percentage = 0
c.stats_percentage = '%.2f' % ((float((last_rev)) /
c.repo_last_rev) * 100)
defaults = c.repo_info.get_dict()
group, repo_name = c.repo_info.groups_and_repo
defaults['repo_name'] = repo_name
defaults['repo_group'] = getattr(group[-1] if group else None,
'group_id', None)
#fill owner
if c.repo_info.user:
defaults.update({'user':c.repo_info.user.username})
replacement_user = self.sa.query(User)\
.filter(User.admin == True).first().username
defaults.update({'user':replacement_user})
#fill repository users
for p in c.repo_info.repo_to_perm:
defaults.update({'u_perm_%s' % p.user.username:
p.permission.permission_name})
#fill repository groups
for p in c.repo_info.users_group_to_perm:
defaults.update({'g_perm_%s' % p.users_group.users_group_name:
return defaults
"""GET /repos: All items in the collection"""
# url('repos')
cached_repo_list = ScmModel().get_repos()
c.repos_list = sorted(cached_repo_list, key=itemgetter('name_sort'))
return render('admin/repos/repos.html')
POST /repos: Create a new item"""
form_result = {}
form_result = RepoForm(repo_groups=c.repo_groups_choices)()\
.to_python(dict(request.POST))
repo_model.create(form_result, self.rhodecode_user)
if form_result['clone_uri']:
h.flash(_('created repository %s from %s') \
% (form_result['repo_name'], form_result['clone_uri']),
h.flash(_('created repository %s') % form_result['repo_name'],
if request.POST.get('user_created'):
action_logger(self.rhodecode_user, 'user_created_repo',
form_result['repo_name'], '', self.sa)
action_logger(self.rhodecode_user, 'admin_created_repo',
c.new_repo = errors.value['repo_name']
r = render('admin/repos/repo_add_create_repository.html')
r = render('admin/repos/repo_add.html')
r,
msg = _('error occurred during creation of repository %s') \
% form_result.get('repo_name')
h.flash(msg, category='error')
return redirect(url('home'))
"""GET /repos/new: Form to create a new item"""
rhodecode.controllers.admin.settings
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
settings controller for rhodecode admin
:created_on: Jul 14, 2010
from sqlalchemy import func
from pylons import request, session, tmpl_context as c, url, config
HasPermissionAnyDecorator, NotAnonymous
from rhodecode.lib.celerylib import tasks, run_task
from rhodecode.lib.utils import repo2db_mapper, invalidate_cache, \
set_rhodecode_config, repo_name_slug
from rhodecode.model.db import RhodeCodeUi, Repository, Group
from rhodecode.model.forms import UserForm, ApplicationSettingsForm, \
ApplicationUiSettingsForm
class SettingsController(BaseController):
# map.resource('setting', 'settings', controller='admin/settings',
# path_prefix='/admin', name_prefix='admin_')
super(SettingsController, self).__before__()
"""GET /admin/settings: All items in the collection"""
# url('admin_settings')
defaults = SettingsModel().get_app_settings()
defaults.update(self.get_hg_ui_settings())
render('admin/settings/settings.html'),
force_defaults=False
"""POST /admin/settings: Create a new item"""
"""GET /admin/settings/new: Form to create a new item"""
# url('admin_new_setting')
def update(self, setting_id):
"""PUT /admin/settings/setting_id: Update an existing item"""
# h.form(url('admin_setting', setting_id=ID),
# url('admin_setting', setting_id=ID)
if setting_id == 'mapping':
rm_obsolete = request.POST.get('destroy', False)
log.debug('Rescanning directories with destroy=%s', rm_obsolete)
initial = ScmModel().repo_scan()
log.debug('invalidating all repositories')
for repo_name in initial.keys():
invalidate_cache('get_repo_cached_%s' % repo_name)
added, removed = repo2db_mapper(initial, rm_obsolete)
h.flash(_('Repositories successfully'
' rescanned added: %s,removed: %s') % (added, removed)
, category='success')
if setting_id == 'whoosh':
repo_location = self.get_hg_ui_settings()['paths_root_path']
full_index = request.POST.get('full_index', False)
run_task(tasks.whoosh_index, repo_location, full_index)
h.flash(_('Whoosh reindex task scheduled'), category='success')
if setting_id == 'global':
application_form = ApplicationSettingsForm()()
form_result = application_form.to_python(dict(request.POST))
hgsettings1 = settings_model.get('title')
hgsettings1.app_settings_value = form_result['rhodecode_title']
hgsettings2 = settings_model.get('realm')
hgsettings2.app_settings_value = form_result['rhodecode_realm']
hgsettings3 = settings_model.get('ga_code')
hgsettings3.app_settings_value = form_result['rhodecode_ga_code']
self.sa.add(hgsettings1)
self.sa.add(hgsettings2)
self.sa.add(hgsettings3)
set_rhodecode_config(config)
h.flash(_('Updated application settings'),
h.flash(_('error occurred during updating application settings'),
self.sa.rollback()
if setting_id == 'mercurial':
application_form = ApplicationUiSettingsForm()()
hgsettings1 = self.sa.query(RhodeCodeUi)\
.filter(RhodeCodeUi.ui_key == 'push_ssl').one()
hgsettings1.ui_value = form_result['web_push_ssl']
hgsettings2 = self.sa.query(RhodeCodeUi)\
.filter(RhodeCodeUi.ui_key == '/').one()
hgsettings2.ui_value = form_result['paths_root_path']
#HOOKS
hgsettings3 = self.sa.query(RhodeCodeUi)\
.filter(RhodeCodeUi.ui_key == 'changegroup.update').one()
hgsettings3.ui_active = bool(form_result['hooks_changegroup_update'])
hgsettings4 = self.sa.query(RhodeCodeUi)\
.filter(RhodeCodeUi.ui_key == 'changegroup.repo_size').one()
hgsettings4.ui_active = bool(form_result['hooks_changegroup_repo_size'])
hgsettings5 = self.sa.query(RhodeCodeUi)\
.filter(RhodeCodeUi.ui_key == 'pretxnchangegroup.push_logger').one()
hgsettings5.ui_active = bool(form_result['hooks_pretxnchangegroup_push_logger'])
hgsettings6 = self.sa.query(RhodeCodeUi)\
.filter(RhodeCodeUi.ui_key == 'preoutgoing.pull_logger').one()
hgsettings6.ui_active = bool(form_result['hooks_preoutgoing_pull_logger'])
self.sa.add(hgsettings4)
self.sa.add(hgsettings5)
self.sa.add(hgsettings6)
h.flash(_('Updated mercurial settings'),
except:
rhodecode.controllers.admin.users
Users crud controller for pylons
:created_on: Apr 4, 2010
from rhodecode.lib.exceptions import DefaultUserException, UserOwnsReposException
from rhodecode.model.db import User
from rhodecode.model.forms import UserForm
class UsersController(BaseController):
# map.resource('user', 'users')
super(UsersController, self).__before__()
c.available_permissions = config['available_permissions']
"""GET /users: All items in the collection"""
# url('users')
c.users_list = self.sa.query(User).all()
return render('admin/users/users.html')
"""POST /users: Create a new item"""
user_model = UserModel()
login_form = UserForm()()
form_result = login_form.to_python(dict(request.POST))
user_model.create(form_result)
h.flash(_('created user %s') % form_result['username'],
#action_logger(self.rhodecode_user, 'new_user', '', '', self.sa)
render('admin/users/user_add.html'),
h.flash(_('error occurred during creation of user %s') \
% request.POST.get('username'), category='error')
return redirect(url('users'))
"""GET /users/new: Form to create a new item"""
# url('new_user')
return render('admin/users/user_add.html')
"""PUT /users/id: Update an existing item"""
# h.form(url('user', id=ID),
# url('user', id=ID)
c.user = user_model.get(id)
_form = UserForm(edit=True, old_data={'user_id':id,
'email':c.user.email})()
user_model.update(id, form_result)
h.flash(_('User updated succesfully'), category='success')
render('admin/users/user_edit.html'),
h.flash(_('error occurred during update of user %s') \
% form_result.get('username'), category='error')
"""DELETE /users/id: Delete an existing item"""
user_model.delete(id)
h.flash(_('successfully deleted user'), category='success')
except (UserOwnsReposException, DefaultUserException), e:
h.flash(str(e), category='warning')
h.flash(_('An error occurred during deletion of user'),
"""GET /users/id: Show a specific item"""
"""GET /users/id/edit: Form to edit an existing item"""
# url('edit_user', id=ID)
if not c.user:
if c.user.username == 'default':
h.flash(_("You can't edit this user"), category='warning')
c.user.permissions = {}
c.granted_permissions = user_model.fill_perms(c.user).permissions['global']
defaults = c.user.get_dict()
rhodecode.controllers.admin.users_groups
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Users Groups crud controller for pylons
:created_on: Jan 25, 2011
from rhodecode.model.db import User, UsersGroup
from rhodecode.model.forms import UserForm, UsersGroupForm
from rhodecode.model.users_group import UsersGroupModel
class UsersGroupsController(BaseController):
# map.resource('users_group', 'users_groups')
super(UsersGroupsController, self).__before__()
"""GET /users_groups: All items in the collection"""
# url('users_groups')
c.users_groups_list = self.sa.query(UsersGroup).all()
return render('admin/users_groups/users_groups.html')
"""POST /users_groups: Create a new item"""
users_group_model = UsersGroupModel()
users_group_form = UsersGroupForm()()
form_result = users_group_form.to_python(dict(request.POST))
users_group_model.create(form_result)
h.flash(_('created users group %s') % form_result['users_group_name'],
render('admin/users_groups/users_group_add.html'),
h.flash(_('error occurred during creation of users group %s') \
% request.POST.get('users_group_name'), category='error')
return redirect(url('users_groups'))
"""GET /users_groups/new: Form to create a new item"""
# url('new_users_group')
return render('admin/users_groups/users_group_add.html')
"""PUT /users_groups/id: Update an existing item"""
# h.form(url('users_group', id=ID),
# url('users_group', id=ID)
c.users_group = users_group_model.get(id)
c.group_members = [(x.user_id, x.user.username) for x in
c.users_group.members]
c.available_members = [(x.user_id, x.username) for x in
self.sa.query(User).all()]
users_group_form = UsersGroupForm(edit=True,
old_data=c.users_group.get_dict(),
available_members=[str(x[0]) for x
in c.available_members])()
form_result = users_group_form.to_python(request.POST)
users_group_model.update(id, form_result)
h.flash(_('updated users group %s') % form_result['users_group_name'],
render('admin/users_groups/users_group_edit.html'),
h.flash(_('error occurred during update of users group %s') \
"""DELETE /users_groups/id: Delete an existing item"""
users_group_model.delete(id)
h.flash(_('successfully deleted users group'), category='success')
h.flash(_('An error occurred during deletion of users group'),
"""GET /users_groups/id: Show a specific item"""
"""GET /users_groups/id/edit: Form to edit an existing item"""
# url('edit_users_group', id=ID)
c.users_group = self.sa.query(UsersGroup).get(id)
if not c.users_group:
c.users_group.permissions = {}
defaults = c.users_group.get_dict()
rhodecode.controllers.branches
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
branches controller for rhodecode
:created_on: Apr 21, 2010
from pylons import tmpl_context as c
from rhodecode.lib.auth import LoginRequired, HasRepoPermissionAnyDecorator
from rhodecode.lib.base import BaseRepoController, render
from rhodecode.lib.utils import OrderedDict
class BranchesController(BaseRepoController):
@HasRepoPermissionAnyDecorator('repository.read', 'repository.write',
'repository.admin')
super(BranchesController, self).__before__()
c.repo_branches = OrderedDict()
for name, hash_ in c.rhodecode_repo.branches.items():
c.repo_branches[name] = c.rhodecode_repo.get_changeset(hash_)
return render('branches/branches.html')
rhodecode.controllers.changelog
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
changelog controller for rhodecode
import json
#python 2.5 compatibility
import simplejson as json
from mercurial.graphmod import colored, CHANGESET, revisions as graph_rev
from pylons import request, session, tmpl_context as c
from rhodecode.lib.helpers import RepoPage
class ChangelogController(BaseRepoController):
super(ChangelogController, self).__before__()
c.affected_files_cut_off = 60
limit = 100
default = 20
if request.params.get('size'):
int_size = int(request.params.get('size'))
except ValueError:
int_size = default
int_size = int_size if int_size <= limit else limit
c.size = int_size
session['changelog_size'] = c.size
session.save()
c.size = int(session.get('changelog_size', default))
branch_name = request.params.get('branch', None)
c.total_cs = len(c.rhodecode_repo)
c.pagination = RepoPage(c.rhodecode_repo, page=p, item_count=c.total_cs,
items_per_page=c.size, branch_name=branch_name)
self._graph(c.rhodecode_repo, c.total_cs, c.size, p)
return render('changelog/changelog.html')
def _graph(self, repo, repo_size, size, p):
Generates a DAG graph for mercurial
:param repo: repo instance
:param size: number of commits to show
:param p: page number
if not repo.revisions or repo.alias == 'git':
c.jsdata = json.dumps([])
return
revcount = min(repo_size, size)
offset = 1 if p == 1 else ((p - 1) * revcount + 1)
rev_start = repo.revisions.index(repo.revisions[(-1 * offset)])
rev_end = max(0, rev_start - revcount)
dag = graph_rev(repo._repo, rev_start, rev_end)
c.dag = tree = list(colored(dag))
data = []
for (id, type, ctx, vtx, edges) in tree:
if type != CHANGESET:
continue
data.append(('', vtx, edges))
c.jsdata = json.dumps(data)
rhodecode.controllers.changeset
changeset controller for pylons showoing changes beetween
revisions
:created_on: Apr 25, 2010
from pylons import tmpl_context as c, url, request, response
from pylons.controllers.util import redirect
import rhodecode.lib.helpers as h
from rhodecode.lib.utils import EmptyChangeset
from vcs.exceptions import RepositoryError, ChangesetError, \
ChangesetDoesNotExistError
from vcs.nodes import FileNode
from vcs.utils import diffs as differ
from vcs.utils.ordered_dict import OrderedDict
class ChangesetController(BaseRepoController):
super(ChangesetController, self).__before__()
def index(self, revision):
def wrap_to_table(str):
return '''<table class="code-difftable">
<tr class="line">
<td class="lineno new"></td>
<td class="code"><pre>%s</pre></td>
</tr>
</table>''' % str
#get ranges of revisions if preset
rev_range = revision.split('...')[:2]
if len(rev_range) == 2:
rev_start = rev_range[0]
rev_end = rev_range[1]
rev_ranges = c.rhodecode_repo.get_changesets(start=rev_start,
end=rev_end)
rev_ranges = [c.rhodecode_repo.get_changeset(revision)]
c.cs_ranges = list(rev_ranges)
except (RepositoryError, ChangesetDoesNotExistError, Exception), e:
c.changes = OrderedDict()
c.sum_added = 0
c.sum_removed = 0
c.cut_off = False
for changeset in c.cs_ranges:
c.changes[changeset.raw_id] = []
changeset_parent = changeset.parents[0]
except IndexError:
changeset_parent = None
#==================================================================
# ADDED FILES
for node in changeset.added:
filenode_old = FileNode(node.path, '', EmptyChangeset())
if filenode_old.is_binary or node.is_binary:
diff = wrap_to_table(_('binary file'))
c.sum_added += node.size
if c.sum_added < self.cut_off_limit:
f_gitdiff = differ.get_gitdiff(filenode_old, node)
diff = differ.DiffProcessor(f_gitdiff, format='gitdiff').as_html()
diff = wrap_to_table(_('Changeset is to big and was cut'
' off, see raw changeset instead'))
c.cut_off = True
break
cs1 = None
cs2 = node.last_changeset.raw_id
c.changes[changeset.raw_id].append(('added', node, diff, cs1, cs2))
# CHANGED FILES
if not c.cut_off:
for node in changeset.changed:
filenode_old = changeset_parent.get_node(node.path)
except ChangesetError:
if c.sum_removed < self.cut_off_limit:
if diff:
c.sum_removed += len(diff)
cs1 = filenode_old.last_changeset.raw_id
c.changes[changeset.raw_id].append(('changed', node, diff, cs1, cs2))
# REMOVED FILES
for node in changeset.removed:
c.changes[changeset.raw_id].append(('removed', node, None, None, None))
if len(c.cs_ranges) == 1:
c.changeset = c.cs_ranges[0]
c.changes = c.changes[c.changeset.raw_id]
return render('changeset/changeset.html')
return render('changeset/changeset_range.html')
def raw_changeset(self, revision):
method = request.GET.get('diff', 'show')
c.scm_type = c.rhodecode_repo.alias
c.changeset = c.rhodecode_repo.get_changeset(revision)
except RepositoryError:
c.changeset_parent = c.changeset.parents[0]
c.changeset_parent = None
c.changes = []
for node in c.changeset.added:
filenode_old = FileNode(node.path, '')
diff = _('binary file') + '\n'
diff = differ.DiffProcessor(f_gitdiff, format='gitdiff').raw_diff()
c.changes.append(('added', node, diff, cs1, cs2))
for node in c.changeset.changed:
filenode_old = c.changeset_parent.get_node(node.path)
diff = _('binary file')
c.changes.append(('changed', node, diff, cs1, cs2))
response.content_type = 'text/plain'
if method == 'download':
response.content_disposition = 'attachment; filename=%s.patch' % revision
parent = True if len(c.changeset.parents) > 0 else False
c.parent_tmpl = 'Parent %s' % c.changeset.parents[0].raw_id if parent else ''
c.diffs = ''
for x in c.changes:
c.diffs += x[2]
return render('changeset/raw_changeset.html')
rhodecode.controllers.error
~~~~~~~~~~~~~~~~~~~~~~~~~~~
RhodeCode error controller
:created_on: Dec 8, 2010
import os
import cgi
import paste.fileapp
from pylons import tmpl_context as c, request, config
from pylons.middleware import media_path
class ErrorController(BaseController):
"""Generates error documents as and when they are required.
The ErrorDocuments middleware forwards to ErrorController when error
related status codes are returned from the application.
This behavior can be altered by changing the parameters to the
ErrorDocuments middleware in your config/middleware.py file.
pass#disable all base actions since we don't need them here
def document(self):
resp = request.environ.get('pylons.original_response')
c.rhodecode_name = config.get('rhodecode_title')
log.debug('### %s ###', resp.status)
e = request.environ
c.serv_p = r'%(protocol)s://%(host)s/' % {
'protocol': e.get('wsgi.url_scheme'),
'host':e.get('HTTP_HOST'),
c.error_message = cgi.escape(request.GET.get('code', str(resp.status)))
c.error_explanation = self.get_error_explanation(resp.status_int)
#redirect to when error with given seconds
c.redirect_time = 0
c.redirect_module = _('Home page')# name to what your going to be redirected
c.url_redirect = "/"
return render('/errors/error_document.html')
def img(self, id):
"""Serve Pylons' stock images"""
return self._serve_file(os.path.join(media_path, 'img', id))
def style(self, id):
"""Serve Pylons' stock stylesheets"""
return self._serve_file(os.path.join(media_path, 'style', id))
def _serve_file(self, path):
"""Call Paste's FileApp (a WSGI application) to serve the file
at the specified path
fapp = paste.fileapp.FileApp(path)
return fapp(request.environ, self.start_response)
def get_error_explanation(self, code):
''' get the error explanations of int codes
[400, 401, 403, 404, 500]'''
code = int(code)
code = 500
if code == 400:
return _('The request could not be understood by the server due to malformed syntax.')
if code == 401:
return _('Unauthorized access to resource')
if code == 403:
return _("You don't have permission to view this page")
if code == 404:
return _('The resource could not be found')
if code == 500:
return _('The server encountered an unexpected condition which prevented it from fulfilling the request.')
rhodecode.controllers.feed
~~~~~~~~~~~~~~~~~~~~~~~~~~
Feed controller for rhodecode
:created_on: Apr 23, 2010
from pylons import url, response, tmpl_context as c
from rhodecode.lib.base import BaseRepoController
from webhelpers.feedgenerator import Atom1Feed, Rss201rev2Feed
class FeedController(BaseRepoController):
@LoginRequired(api_access=True)
super(FeedController, self).__before__()
#common values for feeds
self.description = _('Changes on %s repository')
self.title = self.title = _('%s %s feed') % (c.rhodecode_name, '%s')
self.language = 'en-us'
self.ttl = "5"
self.feed_nr = 10
def __changes(self, cs):
changes = ''
a = [n.path for n in cs.added]
if a:
changes += '\nA ' + '\nA '.join(a)
m = [n.path for n in cs.changed]
if m:
changes += '\nM ' + '\nM '.join(m)
d = [n.path for n in cs.removed]
if d:
changes += '\nD ' + '\nD '.join(d)
changes += '</pre>'
return changes
def atom(self, repo_name):
"""Produce an atom-1.0 feed via feedgenerator module"""
feed = Atom1Feed(title=self.title % repo_name,
link=url('summary_home', repo_name=repo_name, qualified=True),
description=self.description % repo_name,
language=self.language,
ttl=self.ttl)
for cs in reversed(list(c.rhodecode_repo[-self.feed_nr:])):
desc = '%s - %s<br/><pre>' % (cs.author, cs.date)
desc += self.__changes(cs)
feed.add_item(title=cs.message,
link=url('changeset_home', repo_name=repo_name,
revision=cs.raw_id, qualified=True),
author_name=cs.author,
description=desc)
response.content_type = feed.mime_type
return feed.writeString('utf-8')
def rss(self, repo_name):
"""Produce an rss2 feed via feedgenerator module"""
feed = Rss201rev2Feed(title=self.title % repo_name,
description=desc,
rhodecode.controllers.files
Files controller for RhodeCode
from vcs.backends import ARCHIVE_SPECS
from vcs.exceptions import RepositoryError, ChangesetDoesNotExistError, \
EmptyRepositoryError, ImproperArchiveTypeError, VCSError
from vcs.nodes import FileNode, NodeKind
class FilesController(BaseRepoController):
super(FilesController, self).__before__()
c.cut_off_limit = self.cut_off_limit
def __get_cs_or_redirect(self, rev, repo_name):
Safe way to get changeset if error occur it redirects to tip with
proper message
:param rev: revision to fetch
:param repo_name: repo name to redirect after
return c.rhodecode_repo.get_changeset(rev)
except EmptyRepositoryError, e:
h.flash(_('There are no files yet'), category='warning')
redirect(h.url('summary_home', repo_name=repo_name))
except RepositoryError, e:
redirect(h.url('files_home', repo_name=repo_name, revision='tip'))
def __get_filenode_or_redirect(self, repo_name, cs, path):
Returns file_node, if error occurs or given path is directory,
it'll redirect to top level path
:param repo_name: repo_name
:param cs: given changeset
:param path: path to lookup
file_node = cs.get_node(path)
if file_node.is_dir():
raise RepositoryError('given path is a directory')
redirect(h.url('files_home', repo_name=repo_name,
revision=cs.raw_id))
return file_node
def index(self, repo_name, revision, f_path):
#reditect to given revision from form if given
post_revision = request.POST.get('at_rev', None)
if post_revision:
cs = self.__get_cs_or_redirect(revision, repo_name)
redirect(url('files_home', repo_name=c.repo_name,
revision=cs.raw_id, f_path=f_path))
c.changeset = self.__get_cs_or_redirect(revision, repo_name)
c.branch = request.GET.get('branch', None)
c.f_path = f_path
cur_rev = c.changeset.revision
#prev link
prev_rev = c.rhodecode_repo.get_changeset(cur_rev).prev(c.branch)
c.url_prev = url('files_home', repo_name=c.repo_name,
revision=prev_rev.raw_id, f_path=f_path)
if c.branch:
c.url_prev += '?branch=%s' % c.branch
except (ChangesetDoesNotExistError, VCSError):
c.url_prev = '#'
#next link
next_rev = c.rhodecode_repo.get_changeset(cur_rev).next(c.branch)
c.url_next = url('files_home', repo_name=c.repo_name,
revision=next_rev.raw_id, f_path=f_path)
c.url_next += '?branch=%s' % c.branch
c.url_next = '#'
#files or dirs
c.files_list = c.changeset.get_node(f_path)
if c.files_list.is_file():
c.file_history = self._get_node_history(c.changeset, f_path)
c.file_history = []
revision=revision))
return render('files/files.html')
def rawfile(self, repo_name, revision, f_path):
file_node = self.__get_filenode_or_redirect(repo_name, cs, f_path)
response.content_disposition = 'attachment; filename=%s' % \
f_path.split(os.sep)[-1].encode('utf8', 'replace')
response.content_type = file_node.mimetype
return file_node.content
def raw(self, repo_name, revision, f_path):
def annotate(self, repo_name, revision, f_path):
c.cs = self.__get_cs_or_redirect(revision, repo_name)
c.file = self.__get_filenode_or_redirect(repo_name, c.cs, f_path)
c.file_history = self._get_node_history(c.cs, f_path)
return render('files/files_annotate.html')
def archivefile(self, repo_name, fname):
fileformat = None
revision = None
ext = None
for a_type, ext_data in ARCHIVE_SPECS.items():
archive_spec = fname.split(ext_data[1])
if len(archive_spec) == 2 and archive_spec[1] == '':
fileformat = a_type or ext_data[1]
revision = archive_spec[0]
ext = ext_data[1]
dbrepo = RepoModel().get_by_repo_name(repo_name)
if dbrepo.enable_downloads is False:
return _('downloads disabled')
cs = c.rhodecode_repo.get_changeset(revision)
content_type = ARCHIVE_SPECS[fileformat][0]
except ChangesetDoesNotExistError:
return _('Unknown revision %s') % revision
except EmptyRepositoryError:
return _('Empty repository')
except (ImproperArchiveTypeError, KeyError):
return _('Unknown archive type')
response.content_type = content_type
response.content_disposition = 'attachment; filename=%s-%s%s' \
% (repo_name, revision, ext)
return cs.get_chunked_archive(stream=None, kind=fileformat)
def diff(self, repo_name, f_path):
diff1 = request.GET.get('diff1')
diff2 = request.GET.get('diff2')
c.action = request.GET.get('diff')
c.no_changes = diff1 == diff2
rhodecode.controllers.home
Home controller for Rhodecode
:created_on: Feb 18, 2010
from pylons import tmpl_context as c, request
from paste.httpexceptions import HTTPBadRequest
from rhodecode.lib.auth import LoginRequired
class HomeController(BaseController):
super(HomeController, self).__before__()
sortables = ['name', 'description', 'last_change', 'tip', 'owner']
current_sort = request.GET.get('sort', 'name')
current_sort_slug = current_sort.replace('-', '')
if current_sort_slug not in sortables:
c.sort_by = 'name'
current_sort_slug = c.sort_by
c.sort_by = current_sort
c.sort_slug = current_sort_slug
sort_key = current_sort_slug + '_sort'
if c.sort_by.startswith('-'):
c.repos_list = sorted(c.cached_repo_list, key=itemgetter(sort_key),
reverse=True)
reverse=False)
c.repo_cnt = len(c.repos_list)
return render('/index.html')
def repo_switcher(self):
if request.is_xhr:
c.repos_list = sorted(c.cached_repo_list,
key=itemgetter('name_sort'), reverse=False)
return render('/repo_switcher_list.html')
return HTTPBadRequest()
rhodecode.controllers.journal
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Journal controller for pylons
:created_on: Nov 21, 2010
from sqlalchemy import or_
from sqlalchemy.orm import joinedload, make_transient
from itertools import groupby
from pylons import request, tmpl_context as c, response, url
from rhodecode.lib.auth import LoginRequired, NotAnonymous
from rhodecode.model.db import UserLog, UserFollowing
class JournalController(BaseController):
super(JournalController, self).__before__()
self.rhodecode_user = self.rhodecode_user
self.title = _('%s public journal %s feed') % (c.rhodecode_name, '%s')
self.feed_nr = 20
@NotAnonymous()
# Return a rendered template
c.following = self.sa.query(UserFollowing)\
.filter(UserFollowing.user_id == self.rhodecode_user.user_id)\
.options(joinedload(UserFollowing.follows_repository))\
.all()
journal = self._get_journal_data(c.following)
c.journal_pager = Page(journal, page=p, items_per_page=20)
c.journal_day_aggreagate = self._get_daily_aggregate(c.journal_pager)
c.journal_data = render('journal/journal_data.html')
return c.journal_data
return render('journal/journal.html')
def _get_daily_aggregate(self, journal):
groups = []
for k, g in groupby(journal, lambda x:x.action_as_day):
user_group = []
for k2, g2 in groupby(list(g), lambda x:x.user.email):
l = list(g2)
user_group.append((l[0].user, l))
groups.append((k, user_group,))
return groups
def _get_journal_data(self, following_repos):
repo_ids = [x.follows_repository.repo_id for x in following_repos
if x.follows_repository is not None]
user_ids = [x.follows_user.user_id for x in following_repos
if x.follows_user is not None]
filtering_criterion = None
if repo_ids and user_ids:
filtering_criterion = or_(UserLog.repository_id.in_(repo_ids),
UserLog.user_id.in_(user_ids))
if repo_ids and not user_ids:
filtering_criterion = UserLog.repository_id.in_(repo_ids)
if not repo_ids and user_ids:
filtering_criterion = UserLog.user_id.in_(user_ids)
if filtering_criterion is not None:
journal = self.sa.query(UserLog)\
.filter(filtering_criterion)\
journal = []
return journal
def toggle_following(self):
cur_token = request.POST.get('auth_token')
token = h.get_token()
if cur_token == token:
user_id = request.POST.get('follows_user_id')
if user_id:
self.scm_model.toggle_following_user(user_id,
self.rhodecode_user.user_id)
return 'ok'
raise HTTPBadRequest()
repo_id = request.POST.get('follows_repo_id')
if repo_id:
self.scm_model.toggle_following_repo(repo_id,
log.debug('token mismatch %s vs %s', cur_token, token)
def public_journal(self):
return render('journal/public_journal.html')
def public_journal_atom(self):
Produce an atom-1.0 feed via feedgenerator module
feed = Atom1Feed(title=self.title % 'atom',
link=url('public_journal_atom', qualified=True),
description=_('Public journal'),
for entry in journal[:self.feed_nr]:
#tmpl = h.action_parser(entry)[0]
action, action_extra = h.action_parser(entry, feed=True)
title = "%s - %s %s" % (entry.user.short_contact, action,
entry.repository.repo_name)
desc = action_extra()
feed.add_item(title=title,
pubdate=entry.action_date,
link=url('', qualified=True),
author_email=entry.user.email,
author_name=entry.user.full_contact,
def public_journal_rss(self):
Produce an rss2 feed via feedgenerator module
rhodecode.controllers.login
Login controller for rhodeocode
:created_on: Apr 22, 2010
from rhodecode.lib.auth import AuthUser, HasPermissionAnyDecorator
from rhodecode.model.forms import LoginForm, RegisterForm, PasswordResetForm
class LoginController(BaseController):
super(LoginController, self).__before__()
#redirect if already logged in
c.came_from = request.GET.get('came_from', None)
if self.rhodecode_user.is_authenticated \
and self.rhodecode_user.username != 'default':
if request.POST:
#import Login Form validator class
login_form = LoginForm()
c.form_result = login_form.to_python(dict(request.POST))
#form checks for username/password, now we're authenticated
username = c.form_result['username']
user = UserModel().get_by_username(username,
case_insensitive=True)
auth_user = AuthUser(user.user_id)
auth_user.set_authenticated()
session['rhodecode_user'] = auth_user
log.info('user %s is now authenticated and stored in session',
username)
user.update_lastlogin()
if c.came_from:
return redirect(c.came_from)
render('/login.html'),
return render('/login.html')
@HasPermissionAnyDecorator('hg.admin', 'hg.register.auto_activate',
'hg.register.manual_activate')
def register(self):
c.auto_active = False
for perm in user_model.get_by_username('default', cache=False).user_perms:
if perm.permission.permission_name == 'hg.register.auto_activate':
c.auto_active = True
register_form = RegisterForm()()
form_result = register_form.to_python(dict(request.POST))
form_result['active'] = c.auto_active
user_model.create_registration(form_result)
h.flash(_('You have successfully registered into rhodecode'),
return redirect(url('login_home'))
render('/register.html'),
return render('/register.html')
def password_reset(self):
password_reset_form = PasswordResetForm()()
form_result = password_reset_form.to_python(dict(request.POST))
user_model.reset_password(form_result)
h.flash(_('Your new password was sent'),
render('/password_reset.html'),
return render('/password_reset.html')
def logout(self):
del session['rhodecode_user']
log.info('Logging out and setting user as Empty')
redirect(url('home'))
rhodecode.controllers.search
~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Search controller for rhodecode
:created_on: Aug 7, 2010
from pylons import request, config, session, tmpl_context as c
from rhodecode.lib.indexers import SCHEMA, IDX_NAME, ResultWrapper
from webhelpers.util import update_params
from whoosh.index import open_dir, EmptyIndexError
from whoosh.qparser import QueryParser, QueryParserError
from whoosh.query import Phrase
class SearchController(BaseController):
super(SearchController, self).__before__()
def index(self, search_repo=None):
c.repo_name = search_repo
c.formated_results = []
c.runtime = ''
c.cur_query = request.GET.get('q', None)
c.cur_type = request.GET.get('type', 'source')
c.cur_search = search_type = {'content':'content',
'commit':'content',
'path':'path',
'repository':'repository'}\
.get(c.cur_type, 'content')
if c.cur_query:
cur_query = c.cur_query.lower()
highlight_items = set()
idx = open_dir(config['app_conf']['index_dir']
, indexname=IDX_NAME)
searcher = idx.searcher()
qp = QueryParser(search_type, schema=SCHEMA)
if c.repo_name:
cur_query = u'repository:%s %s' % (c.repo_name, cur_query)
query = qp.parse(unicode(cur_query))
if isinstance(query, Phrase):
highlight_items.update(query.words)
for i in query.all_terms():
if i[0] == 'content':
highlight_items.add(i[1])
matcher = query.matcher(searcher)
log.debug(query)
log.debug(highlight_items)
results = searcher.search(query)
res_ln = len(results)
c.runtime = '%s results (%.3f seconds)' \
% (res_ln, results.runtime)
def url_generator(**kw):
return update_params("?q=%s&type=%s" \
% (c.cur_query, c.cur_search), **kw)
c.formated_results = Page(
ResultWrapper(search_type, searcher, matcher,
highlight_items),
page=p, item_count=res_ln,
items_per_page=10, url=url_generator)
except QueryParserError:
c.runtime = _('Invalid search query. Try quoting it.')
searcher.close()
except (EmptyIndexError, IOError):
log.error('Empty Index data')
c.runtime = _('There is no index to search in. '
'Please run whoosh indexer')
return render('/search/search.html')
rhodecode.controllers.settings
Settings controller for rhodecode
:created_on: Jun 30, 2010
from pylons import tmpl_context as c, request, url
from rhodecode.lib.auth import LoginRequired, HasRepoPermissionAllDecorator, \
HasRepoPermissionAnyDecorator, NotAnonymous
from rhodecode.lib.utils import invalidate_cache, action_logger
from rhodecode.model.forms import RepoSettingsForm, RepoForkForm
class SettingsController(BaseRepoController):
@HasRepoPermissionAllDecorator('repository.admin')
def index(self, repo_name):
c.repo_info = repo = repo_model.get_by_repo_name(repo_name)
if not repo:
' it was created or renamed from the file system'
render('settings/repo_settings.html'),
def update(self, repo_name):
changed_name = repo_name
_form = RepoSettingsForm(edit=True, old_data={'repo_name':repo_name})()
repo_model.update(repo_name, form_result)
h.flash(_('Repository %s updated successfully' % repo_name),
changed_name = form_result['repo_name']
action_logger(self.rhodecode_user, 'user_updated_repo',
changed_name, '', self.sa)
errors.value.update({'user':c.repo_info.user.username})
h.flash(_('error occurred during update of repository %s') \
% repo_name, category='error')
return redirect(url('repo_settings_home', repo_name=changed_name))
def delete(self, repo_name):
"""DELETE /repos/repo_name: Delete an existing item"""
# h.form(url('repo_settings_delete', repo_name=ID),
# url('repo_settings_delete', repo_name=ID)
repo = repo_model.get_by_repo_name(repo_name)
' it was moved or renamed from the filesystem'
action_logger(self.rhodecode_user, 'user_deleted_repo',
repo_name, '', self.sa)
repo_model.delete(repo)
h.flash(_('deleted repository %s') % repo_name, category='success')
h.flash(_('An error occurred during deletion of %s') % repo_name,
def fork(self, repo_name):
return render('settings/repo_fork.html')
def fork_create(self, repo_name):
_form = RepoForkForm(old_data={'repo_type':c.repo_info.repo_type})()
form_result.update({'repo_name':repo_name})
repo_model.create_fork(form_result, self.rhodecode_user)
h.flash(_('forked %s repository as %s') \
% (repo_name, form_result['fork_name']),
action_logger(self.rhodecode_user,
'user_forked_repo:%s' % form_result['fork_name'],
c.new_repo = errors.value['fork_name']
r = render('settings/repo_fork.html')
rhodecode.controllers.shortlog
Shortlog controller for rhodecode
:created_on: Apr 18, 2010
class ShortlogController(BaseRepoController):
super(ShortlogController, self).__before__()
c.repo_changesets = RepoPage(c.rhodecode_repo, page=p, items_per_page=20)
c.shortlog_data = render('shortlog/shortlog_data.html')
return c.shortlog_data
r = render('shortlog/shortlog.html')
return r
rhodecode.controllers.summary
Summary controller for Rhodecode
import calendar
from time import mktime
from datetime import datetime, timedelta, date
from vcs.exceptions import ChangesetError
from rhodecode.model.db import Statistics, Repository
from rhodecode.lib.utils import OrderedDict, EmptyChangeset
from rhodecode.lib.celerylib import run_task
from rhodecode.lib.celerylib.tasks import get_commits_stats
class SummaryController(BaseRepoController):
super(SummaryController, self).__before__()
c.dbrepo = dbrepo = Repository.by_repo_name(repo_name)
c.following = self.scm_model.is_following_repo(repo_name,
return url('shortlog_home', repo_name=repo_name, **kw)
c.repo_changesets = RepoPage(c.rhodecode_repo, page=1, items_per_page=10,
url=url_generator)
if self.rhodecode_user.username == 'default':
#for default(anonymous) user we don't need to pass credentials
username = ''
password = ''
username = str(self.rhodecode_user.username)
password = '@'
uri = u'%(protocol)s://%(user)s%(password)s%(host)s%(prefix)s/%(repo_name)s' % {
'user':username,
'password':password,
'prefix':e.get('SCRIPT_NAME'),
'repo_name':repo_name, }
c.clone_repo_url = uri
c.repo_tags = OrderedDict()
for name, hash in c.rhodecode_repo.tags.items()[:10]:
c.repo_tags[name] = c.rhodecode_repo.get_changeset(hash)
c.repo_tags[name] = EmptyChangeset(hash)
for name, hash in c.rhodecode_repo.branches.items()[:10]:
c.repo_branches[name] = c.rhodecode_repo.get_changeset(hash)
c.repo_branches[name] = EmptyChangeset(hash)
td = date.today() + timedelta(days=1)
td_1m = td - timedelta(days=calendar.mdays[td.month])
td_1y = td - timedelta(days=365)
ts_min_m = mktime(td_1m.timetuple())
ts_min_y = mktime(td_1y.timetuple())
ts_max_y = mktime(td.timetuple())
if dbrepo.enable_statistics:
c.no_data_msg = _('No data loaded yet')
run_task(get_commits_stats, c.dbrepo.repo_name, ts_min_y, ts_max_y)
c.no_data_msg = _('Statistics are disabled for this repository')
c.ts_min = ts_min_m
c.ts_max = ts_max_y
stats = self.sa.query(Statistics)\
.filter(Statistics.repository == dbrepo)\
.scalar()
if stats and stats.languages:
c.no_data = False is dbrepo.enable_statistics
lang_stats = json.loads(stats.languages)
c.commit_data = stats.commit_activity
c.overview_data = stats.commit_activity_combined
c.trending_languages = json.dumps(OrderedDict(
sorted(lang_stats.items(), reverse=True,
key=lambda k: k[1])[:10]
last_rev = stats.stat_on_revision
c.repo_last_rev = c.rhodecode_repo.count() - 1 \
if c.rhodecode_repo.revisions else 0
pass
c.commit_data = json.dumps({})
c.overview_data = json.dumps([[ts_min_y, 0], [ts_max_y, 10] ])
c.trending_languages = json.dumps({})
c.no_data = True
c.enable_downloads = dbrepo.enable_downloads
if c.enable_downloads:
c.download_options = self._get_download_links(c.rhodecode_repo)
return render('summary/summary.html')
def _get_download_links(self, repo):
download_l = []
branches_group = ([], _("Branches"))
tags_group = ([], _("Tags"))
for name, chs in c.rhodecode_repo.branches.items():
#chs = chs.split(':')[-1]
branches_group[0].append((chs, name),)
download_l.append(branches_group)
for name, chs in c.rhodecode_repo.tags.items():
tags_group[0].append((chs, name),)
download_l.append(tags_group)
return download_l
rhodecode.controllers.tags
Tags controller for rhodecode
class TagsController(BaseRepoController):
super(TagsController, self).__before__()
tags = [(name, c.rhodecode_repo.get_changeset(hash_)) for \
name, hash_ in c.rhodecode_repo.tags.items()]
ordered_tags = sorted(tags, key=lambda x:x[1].date, reverse=True)
for name, cs_tag in ordered_tags:
c.repo_tags[name] = cs_tag
return render('tags/tags.html')
rhodecode.lib.__init__
~~~~~~~~~~~~~~~~~~~~~~~
Some simple helper functions
:created_on: Jan 5, 2011
:copyright: (C) 2009-2010 Marcin Kuzminski <marcin@python-works.com>
def str2bool(s):
if s is None:
return False
if s in (True, False):
return s
s = str(s).strip().lower()
return s in ('t', 'true', 'y', 'yes', 'on', '1')
def generate_api_key(username, salt=None):
Generates uniq API key for given username
:param username: username as string
:param salt: salt to hash generate KEY
from tempfile import _RandomNameSequence
import hashlib
if salt is None:
salt = _RandomNameSequence().next()
return hashlib.sha1(username + salt).hexdigest()
def safe_unicode(_str):
safe unicode function. In case of UnicodeDecode error we try to return
unicode with errors replace, if this fails we return unicode with
string_escape decoding
if isinstance(_str, unicode):
return _str
u_str = unicode(_str)
except UnicodeDecodeError:
u_str = _str.decode('utf-8', 'replace')
#incase we have a decode error just represent as byte string
u_str = unicode(_str.encode('string_escape'))
return u_str
rhodecode.lib.auth
authentication and permission libraries
:copyright: (c) 2010 by marcink.
:license: LICENSE_NAME, see LICENSE_FILE for more details.
import random
from decorator import decorator
from pylons import config, session, url, request
from rhodecode import __platform__, PLATFORM_WIN, PLATFORM_OTHERS
if __platform__ in PLATFORM_WIN:
from hashlib import sha256
if __platform__ in PLATFORM_OTHERS:
import bcrypt
from rhodecode.lib import str2bool
from rhodecode.lib.exceptions import LdapPasswordError, LdapUsernameError
from rhodecode.lib.utils import get_repo_slug
from rhodecode.lib.auth_ldap import AuthLdap
from rhodecode.model import meta
from rhodecode.model.db import Permission
class PasswordGenerator(object):
"""This is a simple class for generating password from
different sets of characters
usage:
passwd_gen = PasswordGenerator()
#print 8-letter password containing only big and small letters of alphabet
print passwd_gen.gen_password(8, passwd_gen.ALPHABETS_BIG_SMALL)
ALPHABETS_NUM = r'''1234567890'''#[0]
ALPHABETS_SMALL = r'''qwertyuiopasdfghjklzxcvbnm'''#[1]
ALPHABETS_BIG = r'''QWERTYUIOPASDFGHJKLZXCVBNM'''#[2]
ALPHABETS_SPECIAL = r'''`-=[]\;',./~!@#$%^&*()_+{}|:"<>?''' #[3]
ALPHABETS_FULL = ALPHABETS_BIG + ALPHABETS_SMALL + ALPHABETS_NUM + ALPHABETS_SPECIAL#[4]
ALPHABETS_ALPHANUM = ALPHABETS_BIG + ALPHABETS_SMALL + ALPHABETS_NUM#[5]
ALPHABETS_BIG_SMALL = ALPHABETS_BIG + ALPHABETS_SMALL
ALPHABETS_ALPHANUM_BIG = ALPHABETS_BIG + ALPHABETS_NUM#[6]
ALPHABETS_ALPHANUM_SMALL = ALPHABETS_SMALL + ALPHABETS_NUM#[7]
def __init__(self, passwd=''):
self.passwd = passwd
def gen_password(self, len, type):
self.passwd = ''.join([random.choice(type) for _ in xrange(len)])
return self.passwd
class RhodeCodeCrypto(object):
@classmethod
def hash_string(cls, str_):
Cryptographic function used for password hashing based on pybcrypt
or pycrypto in windows
:param password: password to hash
return sha256(str_).hexdigest()
elif __platform__ in PLATFORM_OTHERS:
return bcrypt.hashpw(str_, bcrypt.gensalt(10))
raise Exception('Unknown or unsupported platform %s' % __platform__)
def hash_check(cls, password, hashed):
Checks matching password with it's hashed value, runs different
implementation based on platform it runs on
:param password: password
:param hashed: password in hashed form
return sha256(password).hexdigest() == hashed
return bcrypt.hashpw(password, hashed) == hashed
def get_crypt_password(password):
return RhodeCodeCrypto.hash_string(password)
def check_password(password, hashed):
return RhodeCodeCrypto.hash_check(password, hashed)
def authfunc(environ, username, password):
"""Dummy authentication function used in Mercurial/Git/ and access control,
:param environ: needed only for using in Basic auth
return authenticate(username, password)
def authenticate(username, password):
"""Authentication function used for access control,
firstly checks for db authentication then if ldap is enabled for ldap
authentication, also creates ldap user if not in database
:param username: username
user = user_model.get_by_username(username, cache=False)
log.debug('Authenticating user using RhodeCode account')
if user is not None and not user.ldap_dn:
if user.active:
if user.username == 'default' and user.active:
log.info('user %s authenticated correctly as anonymous user',
return True
elif user.username == username and check_password(password, user.password):
log.info('user %s authenticated correctly', username)
log.warning('user %s is disabled', username)
log.debug('Regular authentication failed')
user_obj = user_model.get_by_username(username, cache=False,
if user_obj is not None and not user_obj.ldap_dn:
log.debug('this user already exists as non ldap')
ldap_settings = SettingsModel().get_ldap_settings()
#======================================================================
# FALLBACK TO LDAP AUTH IF ENABLE
if str2bool(ldap_settings.get('ldap_active')):
log.debug("Authenticating user using ldap")
kwargs = {
'server':ldap_settings.get('ldap_host', ''),
'base_dn':ldap_settings.get('ldap_base_dn', ''),
'port':ldap_settings.get('ldap_port'),
'bind_dn':ldap_settings.get('ldap_dn_user'),
'bind_pass':ldap_settings.get('ldap_dn_pass'),
'use_ldaps':str2bool(ldap_settings.get('ldap_ldaps')),
'tls_reqcert':ldap_settings.get('ldap_tls_reqcert'),
'ldap_filter':ldap_settings.get('ldap_filter'),
'search_scope':ldap_settings.get('ldap_search_scope'),
'attr_login':ldap_settings.get('ldap_attr_login'),
'ldap_version':3,
log.debug('Checking for ldap authentication')
aldap = AuthLdap(**kwargs)
(user_dn, ldap_attrs) = aldap.authenticate_ldap(username, password)
log.debug('Got ldap DN response %s', user_dn)
user_attrs = {
'name' : ldap_attrs[ldap_settings.get('ldap_attr_firstname')][0],
'lastname' : ldap_attrs[ldap_settings.get('ldap_attr_lastname')][0],
'email' : ldap_attrs[ldap_settings.get('ldap_attr_email')][0],
if user_model.create_ldap(username, password, user_dn, user_attrs):
log.info('created new ldap user %s', username)
except (LdapUsernameError, LdapPasswordError,):
except (Exception,):
class AuthUser(object):
#!/usr/bin/env python
# encoding: utf-8
# ldap authentication lib
# Copyright (C) 2009-2011 Marcin Kuzminski <marcin@python-works.com>
Created on Nov 17, 2010
@author: marcink
from rhodecode.lib.exceptions import *
import ldap
class AuthLdap(object):
def __init__(self, server, base_dn, port=389, bind_dn='', bind_pass='',
use_ldaps=False, tls_reqcert='DEMAND', ldap_version=3,
ldap_filter='(&(objectClass=user)(!(objectClass=computer)))',
search_scope='SUBTREE',
attr_login='uid'):
self.ldap_version = ldap_version
if use_ldaps:
port = port or 689
self.LDAP_USE_LDAPS = use_ldaps
self.TLS_REQCERT = ldap.__dict__['OPT_X_TLS_' + tls_reqcert]
self.LDAP_SERVER_ADDRESS = server
self.LDAP_SERVER_PORT = port
#USE FOR READ ONLY BIND TO LDAP SERVER
self.LDAP_BIND_DN = bind_dn
self.LDAP_BIND_PASS = bind_pass
ldap_server_type = 'ldap'
if self.LDAP_USE_LDAPS:ldap_server_type = ldap_server_type + 's'
self.LDAP_SERVER = "%s://%s:%s" % (ldap_server_type,
self.LDAP_SERVER_ADDRESS,
self.LDAP_SERVER_PORT)
self.BASE_DN = base_dn
self.LDAP_FILTER = ldap_filter
self.SEARCH_SCOPE = ldap.__dict__['SCOPE_' + search_scope]
self.attr_login = attr_login
def authenticate_ldap(self, username, password):
"""Authenticate a user via LDAP and return his/her LDAP properties.
Raises AuthenticationError if the credentials are rejected, or
EnvironmentError if the LDAP server can't be reached.
from rhodecode.lib.helpers import chop_at
uid = chop_at(username, "@%s" % self.LDAP_SERVER_ADDRESS)
if "," in username:
raise LdapUsernameError("invalid character in username: ,")
ldap.set_option(ldap.OPT_X_TLS_CACERTDIR, '/etc/openldap/cacerts')
ldap.set_option(ldap.OPT_REFERRALS, ldap.OPT_OFF)
ldap.set_option(ldap.OPT_RESTART, ldap.OPT_ON)
ldap.set_option(ldap.OPT_TIMEOUT, 20)
ldap.set_option(ldap.OPT_NETWORK_TIMEOUT, 10)
ldap.set_option(ldap.OPT_TIMELIMIT, 15)
if self.LDAP_USE_LDAPS:
ldap.set_option(ldap.OPT_X_TLS_REQUIRE_CERT, self.TLS_REQCERT)
server = ldap.initialize(self.LDAP_SERVER)
if self.ldap_version == 2:
server.protocol = ldap.VERSION2
server.protocol = ldap.VERSION3
if self.LDAP_BIND_DN and self.LDAP_BIND_PASS:
server.simple_bind_s(self.LDAP_BIND_DN, self.LDAP_BIND_PASS)
filt = '(&%s(%s=%s))' % (self.LDAP_FILTER, self.attr_login, username)
log.debug("Authenticating %r filt %s at %s", self.BASE_DN,
filt, self.LDAP_SERVER)
lobjects = server.search_ext_s(self.BASE_DN, self.SEARCH_SCOPE,
filt)
if not lobjects:
raise ldap.NO_SUCH_OBJECT()
for (dn, attrs) in lobjects:
server.simple_bind_s(dn, password)
except ldap.INVALID_CREDENTIALS, e:
log.debug("LDAP rejected password for user '%s' (%s): %s",
uid, username, dn)
log.debug("No matching LDAP objects for authentication "
"of '%s' (%s)", uid, username)
raise LdapPasswordError()
except ldap.NO_SUCH_OBJECT, e:
log.debug("LDAP says no such user '%s' (%s)", uid, username)
raise LdapUsernameError()
except ldap.SERVER_DOWN, e:
raise LdapConnectionError("LDAP can't access authentication server")
return (dn, attrs)
# mercurial repository backup manager
Created on Feb 28, 2010
Mercurial repositories backup manager
import tarfile
import datetime
import sys
import subprocess
logging.basicConfig(level=logging.DEBUG,
format="%(asctime)s %(levelname)-5.5s %(message)s")
class BackupManager(object):
def __init__(self, repos_location, rsa_key, backup_server):
today = datetime.datetime.now().weekday() + 1
self.backup_file_name = "mercurial_repos.%s.tar.gz" % today
self.id_rsa_path = self.get_id_rsa(rsa_key)
self.repos_path = self.get_repos_path(repos_location)
self.backup_server = backup_server
self.backup_file_path = '/tmp'
logging.info('starting backup for %s', self.repos_path)
logging.info('backup target %s', self.backup_file_path)
def get_id_rsa(self, rsa_key):
if not os.path.isfile(rsa_key):
logging.error('Could not load id_rsa key file in %s', rsa_key)
sys.exit()
return rsa_key
def get_repos_path(self, path):
if not os.path.isdir(path):
logging.error('Wrong location for repositories in %s', path)
return path
def backup_repos(self):
bckp_file = os.path.join(self.backup_file_path, self.backup_file_name)
tar = tarfile.open(bckp_file, "w:gz")
for dir_name in os.listdir(self.repos_path):
logging.info('backing up %s', dir_name)
tar.add(os.path.join(self.repos_path, dir_name), dir_name)
tar.close()
logging.info('finished backup of mercurial repositories')
def transfer_files(self):
params = {
'id_rsa_key': self.id_rsa_path,
'backup_file':os.path.join(self.backup_file_path,
self.backup_file_name),
'backup_server':self.backup_server
cmd = ['scp', '-l', '40000', '-i', '%(id_rsa_key)s' % params,
'%(backup_file)s' % params,
'%(backup_server)s' % params]
subprocess.call(cmd)
logging.info('Transfered file %s to %s', self.backup_file_name, cmd[4])
def rm_file(self):
logging.info('Removing file %s', self.backup_file_name)
os.remove(os.path.join(self.backup_file_path, self.backup_file_name))
if __name__ == "__main__":
repo_location = '/home/repo_path'
backup_server = 'root@192.168.1.100:/backups/mercurial'
rsa_key = '/home/id_rsa'
B_MANAGER = BackupManager(repo_location, rsa_key, backup_server)
B_MANAGER.backup_repos()
B_MANAGER.transfer_files()
B_MANAGER.rm_file()
rhodecode.lib.celerylib.__init__
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
celery libs for RhodeCode
:created_on: Nov 27, 2010
import socket
from hashlib import md5
from pylons import config
from vcs.utils.lazy import LazyProperty
from rhodecode.lib.pidlock import DaemonLock, LockHeld
from celery.messaging import establish_connection
CELERY_ON = str2bool(config['app_conf'].get('use_celery'))
except KeyError:
CELERY_ON = False
class ResultWrapper(object):
def __init__(self, task):
self.task = task
@LazyProperty
def result(self):
return self.task
def run_task(task, *args, **kwargs):
if CELERY_ON:
t = task.apply_async(args=args, kwargs=kwargs)
log.info('running task %s:%s', t.task_id, task)
return t
except socket.error, e:
if e.errno == 111:
log.debug('Unable to connect to celeryd. Sync execution')
except KeyError, e:
except Exception, e:
log.debug('executing task %s in sync mode', task)
return ResultWrapper(task(*args, **kwargs))
def locked_task(func):
def __wrapper(func, *fargs, **fkwargs):
params = list(fargs)
params.extend(['%s-%s' % ar for ar in fkwargs.items()])
lockkey = 'task_%s' % \
md5(str(func.__name__) + '-' + \
'-'.join(map(str, params))).hexdigest()
log.info('running task with lockkey %s', lockkey)
l = DaemonLock(lockkey)
ret = func(*fargs, **fkwargs)
l.release()
return ret
except LockHeld:
log.info('LockHeld')
return 'Task with key %s already running' % lockkey
return decorator(__wrapper, func)
rhodecode.lib.celerylib.tasks
RhodeCode task modules, containing all task that suppose to be run
by celery daemon
:created_on: Oct 6, 2010
from celery.decorators import task
from rhodecode.lib.celerylib import run_task, locked_task, str2bool
from rhodecode.lib.helpers import person
from rhodecode.lib.smtp_mailer import SmtpMailer
from rhodecode.lib.utils import OrderedDict, add_cache
from rhodecode.model import init_model
from rhodecode.model.db import RhodeCodeUi
from vcs.backends import get_repo
from sqlalchemy import engine_from_config
add_cache(config)
__all__ = ['whoosh_index', 'get_commits_stats',
'reset_user_password', 'send_email']
def get_session():
engine = engine_from_config(config, 'sqlalchemy.db1.')
init_model(engine)
sa = meta.Session()
return sa
def get_repos_path():
sa = get_session()
q = sa.query(RhodeCodeUi).filter(RhodeCodeUi.ui_key == '/').one()
return q.ui_value
@task(ignore_result=True)
@locked_task
def whoosh_index(repo_location, full_index):
#log = whoosh_index.get_logger()
from rhodecode.lib.indexers.daemon import WhooshIndexingDaemon
index_location = config['index_dir']
WhooshIndexingDaemon(index_location=index_location,
repo_location=repo_location, sa=get_session())\
.run(full_index=full_index)
def get_commits_stats(repo_name, ts_min_y, ts_max_y):
log = get_commits_stats.get_logger()
#for js data compatibilty
author_key_cleaner = lambda k: person(k).replace('"', "")
commits_by_day_author_aggregate = {}
commits_by_day_aggregate = {}
repos_path = get_repos_path()
p = os.path.join(repos_path, repo_name)
repo = get_repo(p)
skip_date_limit = True
parse_limit = int(config['app_conf'].get('commit_parse_limit'))
last_cs = None
timegetter = itemgetter('time')
dbrepo = sa.query(Repository)\
.filter(Repository.repo_name == repo_name).scalar()
cur_stats = sa.query(Statistics)\
.filter(Statistics.repository == dbrepo).scalar()
if cur_stats is not None:
last_rev = cur_stats.stat_on_revision
#return if repo is empty
if not repo.revisions:
if last_rev == repo.get_changeset().revision and len(repo.revisions) > 1:
#pass silently without any work if we're not on first revision or
#current state of parsing revision(from db marker) is the last revision
if cur_stats:
commits_by_day_aggregate = OrderedDict(
json.loads(
cur_stats.commit_activity_combined))
commits_by_day_author_aggregate = json.loads(cur_stats.commit_activity)
log.debug('starting parsing %s', parse_limit)
lmktime = mktime
last_rev = last_rev + 1 if last_rev > 0 else last_rev
for cs in repo[last_rev:last_rev + parse_limit]:
last_cs = cs #remember last parsed changeset
k = lmktime([cs.date.timetuple()[0], cs.date.timetuple()[1],
cs.date.timetuple()[2], 0, 0, 0, 0, 0, 0])
if commits_by_day_author_aggregate.has_key(author_key_cleaner(cs.author)):
l = [timegetter(x) for x in commits_by_day_author_aggregate\
[author_key_cleaner(cs.author)]['data']]
time_pos = l.index(k)
time_pos = False
if time_pos >= 0 and time_pos is not False:
datadict = commits_by_day_author_aggregate\
[author_key_cleaner(cs.author)]['data'][time_pos]
datadict["commits"] += 1
datadict["added"] += len(cs.added)
datadict["changed"] += len(cs.changed)
datadict["removed"] += len(cs.removed)
if k >= ts_min_y and k <= ts_max_y or skip_date_limit:
datadict = {"time":k,
"commits":1,
"added":len(cs.added),
"changed":len(cs.changed),
"removed":len(cs.removed),
commits_by_day_author_aggregate\
[author_key_cleaner(cs.author)]['data'].append(datadict)
commits_by_day_author_aggregate[author_key_cleaner(cs.author)] = {
"label":author_key_cleaner(cs.author),
"data":[{"time":k,
}],
"schema":["commits"],
#gather all data by day
if commits_by_day_aggregate.has_key(k):
commits_by_day_aggregate[k] += 1
commits_by_day_aggregate[k] = 1
overview_data = sorted(commits_by_day_aggregate.items(), key=itemgetter(0))
if not commits_by_day_author_aggregate:
commits_by_day_author_aggregate[author_key_cleaner(repo.contact)] = {
"label":author_key_cleaner(repo.contact),
"data":[0, 1],
stats = cur_stats if cur_stats else Statistics()
stats.commit_activity = json.dumps(commits_by_day_author_aggregate)
stats.commit_activity_combined = json.dumps(overview_data)
log.debug('last revison %s', last_rev)
leftovers = len(repo.revisions[last_rev:])
log.debug('revisions to parse %s', leftovers)
if last_rev == 0 or leftovers < parse_limit:
log.debug('getting code trending stats')
stats.languages = json.dumps(__get_codes_stats(repo_name))
stats.repository = dbrepo
stats.stat_on_revision = last_cs.revision if last_cs else 0
sa.add(stats)
rhodecode.lib.db_manage
Database creation, and setup module for RhodeCode. Used for creation
of database as well as for migration operations
:created_on: Apr 10, 2010
import uuid
from os.path import dirname as dn, join as jn
from rhodecode import __dbversion__
from rhodecode.lib.auth import get_crypt_password, generate_api_key
from rhodecode.lib.utils import ask_ok
from rhodecode.model.db import User, Permission, RhodeCodeUi, RhodeCodeSettings, \
UserToPerm, DbMigrateVersion
from sqlalchemy.engine import create_engine
class DbManage(object):
def __init__(self, log_sql, dbconf, root, tests=False):
self.dbname = dbconf.split('/')[-1]
self.tests = tests
self.root = root
self.dburi = dbconf
self.log_sql = log_sql
self.db_exists = False
self.init_db()
def init_db(self):
engine = create_engine(self.dburi, echo=self.log_sql)
self.sa = meta.Session()
def create_tables(self, override=False):
"""Create a auth database
log.info("Any existing database is going to be destroyed")
if self.tests:
destroy = True
destroy = ask_ok('Are you sure to destroy old database ? [y/n]')
if not destroy:
if destroy:
meta.Base.metadata.drop_all()
checkfirst = not override
meta.Base.metadata.create_all(checkfirst=checkfirst)
log.info('Created tables for %s', self.dbname)
def set_db_version(self):
ver = DbMigrateVersion()
ver.version = __dbversion__
ver.repository_id = 'rhodecode_db_migrations'
ver.repository_path = 'versions'
self.sa.add(ver)
log.info('db version set to: %s', __dbversion__)
def upgrade(self):
"""Upgrades given database schema to given revision following
all needed steps, to perform the upgrade
from rhodecode.lib.dbmigrate.migrate.versioning import api
from rhodecode.lib.dbmigrate.migrate.exceptions import \
DatabaseNotControlledError
upgrade = ask_ok('You are about to perform database upgrade, make '
'sure You backed up your database before. '
'Continue ? [y/n]')
if not upgrade:
sys.exit('Nothing done')
repository_path = jn(dn(dn(dn(os.path.realpath(__file__)))),
'rhodecode/lib/dbmigrate')
db_uri = self.dburi
curr_version = api.db_version(db_uri, repository_path)
msg = ('Found current database under version'
' control with version %s' % curr_version)
except (RuntimeError, DatabaseNotControlledError), e:
curr_version = 1
msg = ('Current database is not under version control. Setting'
' as version %s' % curr_version)
api.version_control(db_uri, repository_path, curr_version)
print (msg)
if curr_version == __dbversion__:
sys.exit('This database is already at the newest version')
# UPGRADE STEPS
class UpgradeSteps(object):
"""Those steps follow schema versions so for example schema
for example schema with seq 002 == step_2 and so on.
def __init__(self, klass):
self.klass = klass
def step_0(self):
#step 0 is the schema upgrade, and than follow proper upgrades
print ('attempting to do database upgrade to version %s' \
% __dbversion__)
api.upgrade(db_uri, repository_path, __dbversion__)
print ('Schema upgrade completed')
def step_1(self):
def step_2(self):
print ('Patching repo paths for newer version of RhodeCode')
self.klass.fix_repo_paths()
print ('Patching default user of RhodeCode')
self.klass.fix_default_user()
log.info('Changing ui settings')
self.klass.create_ui_settings()
def step_3(self):
print ('Adding additional settings into RhodeCode db')
self.klass.fix_settings()
upgrade_steps = [0] + range(curr_version + 1, __dbversion__ + 1)
#CALL THE PROPER ORDER OF STEPS TO PERFORM FULL UPGRADE
for step in upgrade_steps:
print ('performing upgrade step %s' % step)
callable = getattr(UpgradeSteps(self), 'step_%s' % step)()
def fix_repo_paths(self):
"""Fixes a old rhodecode version path into new one without a '*'
paths = self.sa.query(RhodeCodeUi)\
.filter(RhodeCodeUi.ui_key == '/')\
paths.ui_value = paths.ui_value.replace('*', '')
self.sa.add(paths)
def fix_default_user(self):
"""Fixes a old default user with some 'nicer' default values,
used mostly for anonymous access
def_user = self.sa.query(User)\
.filter(User.username == 'default')\
.one()
def_user.name = 'Anonymous'
def_user.lastname = 'User'
def_user.email = 'anonymous@rhodecode.org'
self.sa.add(def_user)
def fix_settings(self):
"""Fixes rhodecode settings adds ga_code key for google analytics
hgsettings3 = RhodeCodeSettings('ga_code', '')
rhodecode.lib.dbmigrate.__init__
Database migration modules
:created_on: Dec 11, 2010
from rhodecode.lib.utils import BasePasterCommand, Command, add_cache
from rhodecode.lib.db_manage import DbManage
class UpgradeDb(BasePasterCommand):
"""Command used for paster to upgrade our database to newer version
max_args = 1
min_args = 1
usage = "CONFIG_FILE"
summary = "Upgrades current db to newer version given configuration file"
group_name = "RhodeCode"
parser = Command.standard_parser(verbose=True)
def command(self):
db_uri = config['sqlalchemy.db1.url']
dbmanage = DbManage(log_sql=True, dbconf=db_uri,
root=config['here'], tests=False)
dbmanage.upgrade()
def update_parser(self):
self.parser.add_option('--sql',
action='store_true',
dest='just_sql',
help="Prints upgrade sql for further investigation",
default=False)
rhodecode.lib.dbmigrate.versions.__init__
Package containing new versions of database models
# Custom Exceptions modules
Custom Exceptions modules
class LdapUsernameError(Exception):pass
class LdapPasswordError(Exception):pass
class LdapConnectionError(Exception):pass
class LdapImportError(Exception):pass
class DefaultUserException(Exception):pass
class UserOwnsReposException(Exception):pass
rhodecode.lib.hooks
~~~~~~~~~~~~~~~~~~~
Hooks runned by rhodecode
:created_on: Aug 6, 2010
import getpass
from mercurial.cmdutil import revrange
from mercurial.node import nullrev
from rhodecode.lib.utils import action_logger
def repo_size(ui, repo, hooktype=None, **kwargs):
"""Presents size of repository after push
:param ui:
:param repo:
:param hooktype:
if hooktype != 'changegroup':
size_hg, size_root = 0, 0
for path, dirs, files in os.walk(repo.root):
if path.find('.hg') != -1:
for f in files:
size_hg += os.path.getsize(os.path.join(path, f))
except OSError:
size_root += os.path.getsize(os.path.join(path, f))
size_hg_f = h.format_byte_size(size_hg)
size_root_f = h.format_byte_size(size_root)
size_total_f = h.format_byte_size(size_root + size_hg)
sys.stdout.write('Repository size .hg:%s repo:%s total:%s\n' \
% (size_hg_f, size_root_f, size_total_f))
def log_pull_action(ui, repo, **kwargs):
"""Logs user last pull action
extra_params = dict(repo.ui.configitems('rhodecode_extras'))
username = extra_params['username']
repository = extra_params['repository']
action = 'pull'
action_logger(username, action, repository, extra_params['ip'])
return 0
def log_push_action(ui, repo, **kwargs):
"""Maps user last push action to new changeset id, from mercurial
action = extra_params['action'] + ':%s'
node = kwargs['node']
def get_revs(repo, rev_opt):
if rev_opt:
revs = revrange(repo, rev_opt)
if len(revs) == 0:
return (nullrev, nullrev)
return (max(revs), min(revs))
return (len(repo) - 1, 0)
stop, start = get_revs(repo, [node + ':'])
revs = (str(repo[r]) for r in xrange(start, stop + 1))
action = action % ','.join(revs)
rhodecode.lib.indexers.__init__
Whoosh indexing module for RhodeCode
:created_on: Aug 17, 2010
#to get the rhodecode import
sys.path.append(dn(dn(dn(os.path.realpath(__file__)))))
from string import strip
from rhodecode.config.environment import load_environment
from shutil import rmtree
from webhelpers.html.builder import escape
from whoosh.analysis import RegexTokenizer, LowercaseFilter, StopFilter
from whoosh.fields import TEXT, ID, STORED, Schema, FieldType
from whoosh.index import create_in, open_dir
from whoosh.formats import Characters
from whoosh.highlight import highlight, SimpleFragmenter, HtmlFormatter
#EXTENSIONS WE WANT TO INDEX CONTENT OFF
INDEX_EXTENSIONS = ['action', 'adp', 'ashx', 'asmx', 'aspx', 'asx', 'axd', 'c',
'cfg', 'cfm', 'cpp', 'cs', 'css', 'diff', 'do', 'el', 'erl',
'h', 'htm', 'html', 'ini', 'java', 'js', 'jsp', 'jspx', 'lisp',
'lua', 'm', 'mako', 'ml', 'pas', 'patch', 'php', 'php3',
'php4', 'phtml', 'pm', 'py', 'rb', 'rst', 's', 'sh', 'sql',
'tpl', 'txt', 'vim', 'wss', 'xhtml', 'xml', 'xsl', 'xslt',
'yaws']
#CUSTOM ANALYZER wordsplit + lowercase filter
ANALYZER = RegexTokenizer(expression=r"\w+") | LowercaseFilter()
#INDEX SCHEMA DEFINITION
SCHEMA = Schema(owner=TEXT(),
repository=TEXT(stored=True),
path=TEXT(stored=True),
content=FieldType(format=Characters(ANALYZER),
scorable=True, stored=True),
modtime=STORED(), extension=TEXT(stored=True))
IDX_NAME = 'HG_INDEX'
FORMATTER = HtmlFormatter('span', between='\n<span class="break">...</span>\n')
FRAGMENTER = SimpleFragmenter(200)
class MakeIndex(BasePasterCommand):
summary = "Creates index for full text search given configuration file"
takes_config_file = -1
repo_location = self.options.repo_location
repo_list = map(strip, self.options.repo_list.split(',')) \
if self.options.repo_list else None
# WHOOSH DAEMON
from rhodecode.lib.pidlock import LockHeld, DaemonLock
l = DaemonLock()
repo_location=repo_location,
repo_list=repo_list)\
.run(full_index=self.options.full_index)
sys.exit(1)
self.parser.add_option('--repo-location',
action='store',
dest='repo_location',
help="Specifies repositories location to index REQUIRED",
self.parser.add_option('--index-only',
dest='repo_list',
help="Specifies a comma separated list of repositores "
"to build index on OPTIONAL",
self.parser.add_option('-f',
dest='full_index',
help="Specifies that index should be made full i.e"
" destroy old and build from scratch",
def __init__(self, search_type, searcher, matcher, highlight_items):
self.search_type = search_type
self.searcher = searcher
self.matcher = matcher
self.highlight_items = highlight_items
self.fragment_size = 200 / 2
def doc_ids(self):
docs_id = []
while self.matcher.is_active():
docnum = self.matcher.id()
chunks = [offsets for offsets in self.get_chunks()]
docs_id.append([docnum, chunks])
self.matcher.next()
return docs_id
def __str__(self):
return '<%s at %s>' % (self.__class__.__name__, len(self.doc_ids))
def __repr__(self):
return self.__str__()
def __len__(self):
return len(self.doc_ids)
def __iter__(self):
Allows Iteration over results,and lazy generate content
*Requires* implementation of ``__getitem__`` method.
for docid in self.doc_ids:
yield self.get_full_content(docid)
def __getitem__(self, key):
Slicing of resultWrapper
i, j = key.start, key.stop
slice = []
for docid in self.doc_ids[i:j]:
slice.append(self.get_full_content(docid))
return slice
def get_full_content(self, docid):
res = self.searcher.stored_fields(docid[0])
f_path = res['path'][res['path'].find(res['repository']) \
+ len(res['repository']):].lstrip('/')
content_short = self.get_short_content(res, docid[1])
res.update({'content_short':content_short,
'content_short_hl':self.highlight(content_short),
'f_path':f_path})
return res
def get_short_content(self, res, chunks):
return ''.join([res['content'][chunk[0]:chunk[1]] for chunk in chunks])
def get_chunks(self):
Smart function that implements chunking the content
but not overlap chunks so it doesn't highlight the same
close occurrences twice.
@param matcher:
@param size:
memory = [(0, 0)]
for span in self.matcher.spans():
start = span.startchar or 0
end = span.endchar or 0
start_offseted = max(0, start - self.fragment_size)
end_offseted = end + self.fragment_size
if start_offseted < memory[-1][1]:
rhodecode.lib.indexers.daemon
A deamon will read from task table and run tasks
:created_on: Jan 26, 2010
from os.path import dirname as dn
from os.path import join as jn
project_path = dn(dn(dn(dn(os.path.realpath(__file__)))))
sys.path.append(project_path)
from rhodecode.lib import safe_unicode
from rhodecode.lib.indexers import INDEX_EXTENSIONS, SCHEMA, IDX_NAME
from vcs.exceptions import ChangesetError, RepositoryError
log = logging.getLogger('whooshIndexer')
# create logger
log.setLevel(logging.DEBUG)
log.propagate = False
# create console handler and set level to debug
ch = logging.StreamHandler()
ch.setLevel(logging.DEBUG)
# create formatter
formatter = logging.Formatter("%(asctime)s - %(name)s -"
" %(levelname)s - %(message)s")
# add formatter to ch
ch.setFormatter(formatter)
# add ch to logger
log.addHandler(ch)
class WhooshIndexingDaemon(object):
Deamon for atomic jobs
def __init__(self, indexname='HG_INDEX', index_location=None,
repo_location=None, sa=None, repo_list=None):
self.indexname = indexname
self.index_location = index_location
if not index_location:
raise Exception('You have to provide index location')
self.repo_location = repo_location
if not repo_location:
raise Exception('You have to provide repositories location')
self.repo_paths = ScmModel(sa).repo_scan(self.repo_location)
if repo_list:
filtered_repo_paths = {}
for repo_name, repo in self.repo_paths.items():
if repo_name in repo_list:
filtered_repo_paths[repo_name] = repo
self.repo_paths = filtered_repo_paths
self.initial = False
if not os.path.isdir(self.index_location):
os.makedirs(self.index_location)
log.info('Cannot run incremental index since it does not'
' yet exist running full build')
self.initial = True
def get_paths(self, repo):
"""recursive walk in root dir and return a set of all path in that dir
based on repository walk function
index_paths_ = set()
tip = repo.get_changeset('tip')
for topnode, dirs, files in tip.walk('/'):
index_paths_.add(jn(repo.path, f.path))
for dir in dirs:
log.debug(traceback.format_exc())
return index_paths_
def get_node(self, repo, path):
n_path = path[len(repo.path) + 1:]
node = repo.get_changeset().get_node(n_path)
return node
def get_node_mtime(self, node):
return mktime(node.last_changeset.date.timetuple())
def add_doc(self, writer, path, repo, repo_name):
"""Adding doc to writer this function itself fetches data from
the instance of vcs backend"""
node = self.get_node(repo, path)
#we just index the content of chosen files, and skip binary files
if node.extension in INDEX_EXTENSIONS and not node.is_binary:
u_content = node.content
if not isinstance(u_content, unicode):
log.warning(' >> %s Could not get this content as unicode '
'replacing with empty content', path)
u_content = u''
log.debug(' >> %s [WITH CONTENT]' % path)
log.debug(' >> %s' % path)
#just index file name without it's content
writer.add_document(owner=unicode(repo.contact),
repository=safe_unicode(repo_name),
path=safe_unicode(path),
content=u_content,
modtime=self.get_node_mtime(node),
extension=node.extension)
def build_index(self):
if os.path.exists(self.index_location):
log.debug('removing previous index')
rmtree(self.index_location)
if not os.path.exists(self.index_location):
os.mkdir(self.index_location)
idx = create_in(self.index_location, SCHEMA, indexname=IDX_NAME)
writer = idx.writer()
log.debug('building index @ %s' % repo.path)
for idx_path in self.get_paths(repo):
self.add_doc(writer, idx_path, repo, repo_name)
log.debug('>> COMMITING CHANGES <<')
writer.commit(merge=True)
log.debug('>>> FINISHED BUILDING INDEX <<<')
def update_index(self):
log.debug('STARTING INCREMENTAL INDEXING UPDATE')
idx = open_dir(self.index_location, indexname=self.indexname)
# The set of all paths in the index
indexed_paths = set()
# The set of all paths we need to re-index
to_index = set()
reader = idx.reader()
# Loop over the stored fields in the index
for fields in reader.all_stored_fields():
indexed_path = fields['path']
indexed_paths.add(indexed_path)
repo = self.repo_paths[fields['repository']]
node = self.get_node(repo, indexed_path)
# This file was deleted since it was indexed
log.debug('removing from index %s' % indexed_path)
writer.delete_by_term('path', indexed_path)
# Check if this file was changed since it was indexed
indexed_time = fields['modtime']
mtime = self.get_node_mtime(node)
if mtime > indexed_time:
# The file has changed, delete it and add it to the list of
# files to reindex
log.debug('adding to reindex list %s' % indexed_path)
rhodecode.lib.middleware.https_fixup
middleware to handle https correctly
:created_on: May 23, 2010
class HttpsFixup(object):
def __init__(self, app, config):
self.application = app
self.config = config
def __call__(self, environ, start_response):
self.__fixup(environ)
return self.application(environ, start_response)
def __fixup(self, environ):
"""Function to fixup the environ as needed. In order to use this
middleware you should set this header inside your
proxy ie. nginx, apache etc.
proto = environ.get('HTTP_X_URL_SCHEME')
if str2bool(self.config.get('force_https')):
proto = 'https'
if proto == 'https':
environ['wsgi.url_scheme'] = proto
environ['wsgi.url_scheme'] = 'http'
return None
rhodecode.lib.middleware.simplegit
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
SimpleGit middleware for handling git protocol request (push/clone etc.)
It's implemented with basic auth function
:created_on: Apr 28, 2010
from dulwich import server as dulserver
class SimpleGitUploadPackHandler(dulserver.UploadPackHandler):
def handle(self):
write = lambda x: self.proto.write_sideband(1, x)
graph_walker = dulserver.ProtocolGraphWalker(self, self.repo.object_store,
self.repo.get_peeled)
objects_iter = self.repo.fetch_objects(
graph_walker.determine_wants, graph_walker, self.progress,
get_tagged=self.get_tagged)
# Do they want any objects?
if len(objects_iter) == 0:
self.progress("counting objects: %d, done.\n" % len(objects_iter))
dulserver.write_pack_data(dulserver.ProtocolFile(None, write), objects_iter,
len(objects_iter))
messages = []
messages.append('thank you for using rhodecode')
for msg in messages:
self.progress(msg + "\n")
# we are done
self.proto.write("0000")
dulserver.DEFAULT_HANDLERS = {
'git-upload-pack': SimpleGitUploadPackHandler,
'git-receive-pack': dulserver.ReceivePackHandler,
from dulwich.repo import Repo
from dulwich.web import HTTPGitApplication
from paste.auth.basic import AuthBasicAuthenticator
from paste.httpheaders import REMOTE_USER, AUTH_TYPE
from rhodecode.lib.auth import authfunc, HasPermissionAnyMiddleware
from rhodecode.lib.utils import invalidate_cache, check_repo_fast
from webob.exc import HTTPNotFound, HTTPForbidden, HTTPInternalServerError
def is_git(environ):
"""Returns True if request's target is git server.
``HTTP_USER_AGENT`` would then have git client version given.
:param environ:
http_user_agent = environ.get('HTTP_USER_AGENT')
if http_user_agent and http_user_agent.startswith('git'):
class SimpleGit(object):
def __init__(self, application, config):
self.application = application
#authenticate this git request using
self.authenticate = AuthBasicAuthenticator('', authfunc)
self.ipaddr = '0.0.0.0'
self.repository = None
self.username = None
self.action = None
if not is_git(environ):
proxy_key = 'HTTP_X_REAL_IP'
def_key = 'REMOTE_ADDR'
self.ipaddr = environ.get(proxy_key, environ.get(def_key, '0.0.0.0'))
# skip passing error to error controller
environ['pylons.status_code_redirect'] = True
# GET ACTION PULL or PUSH
self.action = self.__get_action(environ)
# GET REPOSITORY NAME
self.repo_name = self.__get_repository(environ)
return HTTPInternalServerError()(environ, start_response)
# CHECK ANONYMOUS PERMISSION
if self.action in ['pull', 'push'] or self.action:
anonymous_user = self.__get_user('default')
self.username = anonymous_user.username
anonymous_perm = self.__check_permission(self.action, anonymous_user ,
self.repo_name)
if anonymous_perm is not True or anonymous_user.active is False:
if anonymous_perm is not True:
log.debug('Not enough credentials to access this repository'
'as anonymous user')
if anonymous_user.active is False:
log.debug('Anonymous access is disabled, running '
'authentication')
#==============================================================
# DEFAULT PERM FAILED OR ANONYMOUS ACCESS IS DISABLED SO WE
# NEED TO AUTHENTICATE AND ASK FOR AUTH USER PERMISSIONS
if not REMOTE_USER(environ):
self.authenticate.realm = str(self.config['rhodecode_realm'])
result = self.authenticate(environ)
if isinstance(result, str):
AUTH_TYPE.update(environ, 'basic')
REMOTE_USER.update(environ, result)
return result.wsgi_application(environ, start_response)
# CHECK PERMISSIONS FOR THIS REQUEST USING GIVEN USERNAME FROM
# BASIC AUTH
username = REMOTE_USER(environ)
user = self.__get_user(username)
self.username = user.username
#check permissions for this repository
perm = self.__check_permission(self.action, user, self.repo_name)
if perm is not True:
print 'not allowed'
return HTTPForbidden()(environ, start_response)
self.extras = {'ip':self.ipaddr,
'username':self.username,
'action':self.action,
'repository':self.repo_name}
#===================================================================
# GIT REQUEST HANDLING
self.basepath = self.config['base_path']
self.repo_path = os.path.join(self.basepath, self.repo_name)
#quick check if that dir exists...
if check_repo_fast(self.repo_name, self.basepath):
return HTTPNotFound()(environ, start_response)
app = self.__make_app()
#invalidate cache on push
if self.action == 'push':
self.__invalidate_cache(self.repo_name)
return app(environ, start_response)
def __make_app(self):
backend = dulserver.DictBackend({'/' + self.repo_name: Repo(self.repo_path)})
gitserve = HTTPGitApplication(backend)
return gitserve
def __check_permission(self, action, user, repo_name):
"""Checks permissions using action (push/pull) user and repository
name
:param action: push or pull action
:param user: user instance
:param repo_name: repository name
if action == 'push':
rhodecode.lib.middleware.simplehg
SimpleHG middleware for handling mercurial protocol request
(push/clone etc.). It's implemented with basic auth function
from mercurial.error import RepoError
from mercurial.hgweb import hgweb
from mercurial.hgweb.request import wsgiapplication
from rhodecode.lib.utils import make_ui, invalidate_cache, \
check_repo_fast, ui_sections
def is_mercurial(environ):
"""Returns True if request's target is mercurial server - header
``HTTP_ACCEPT`` of such request would start with ``application/mercurial``.
http_accept = environ.get('HTTP_ACCEPT')
if http_accept and http_accept.startswith('application/mercurial'):
class SimpleHg(object):
#authenticate this mercurial request using authfunc
self.repo_name = None
if not is_mercurial(environ):
if self.action in ['pull', 'push']:
# MERCURIAL REQUEST HANDLING
environ['PATH_INFO'] = '/'#since we wrap into hgweb, reset the path
self.baseui = make_ui('db')
app = wsgiapplication(self.__make_app)
except RepoError, e:
if str(e).find('not found') != -1:
"""Make an wsgi application using hgweb, and my generated baseui
instance
hgserve = hgweb(str(self.repo_path), baseui=self.baseui)
return self.__load_web_settings(hgserve, self.extras)
if not HasPermissionAnyMiddleware('repository.write',
'repository.admin')\
(user, repo_name):
#any other action need at least read permission
if not HasPermissionAnyMiddleware('repository.read',
'repository.write',
def __get_repository(self, environ):
"""Get's repository name out of PATH_INFO header
:param environ: environ where PATH_INFO is stored
repo_name = '/'.join(environ['PATH_INFO'].split('/')[1:])
if repo_name.endswith('/'):
repo_name = repo_name.rstrip('/')
rhodecode.lib.utils
Utilities library for RhodeCode
import paste
import beaker
from paste.script.command import Command, BadCommand
from UserDict import DictMixin
from mercurial import ui, config, hg
from webhelpers.text import collapse, remove_formatting, strip_tags
from vcs.backends.base import BaseChangeset
from rhodecode.model.caching_query import FromCache
from rhodecode.model.db import Repository, User, RhodeCodeUi, UserLog, Group
def recursive_replace(str, replace=' '):
"""Recursive replace of given sign to just one instance
:param str: given string
:param replace: char to find and replace multiple instances
Examples::
>>> recursive_replace("Mighty---Mighty-Bo--sstones",'-')
'Mighty-Mighty-Bo-sstones'
if str.find(replace * 2) == -1:
return str
str = str.replace(replace * 2, replace)
return recursive_replace(str, replace)
def repo_name_slug(value):
"""Return slug of name of repository
This function is called on each creation/modification
of repository to prevent bad names in repo
slug = remove_formatting(value)
slug = strip_tags(slug)
for c in """=[]\;'"<>,/~!@#$%^&*()+{}|: """:
slug = slug.replace(c, '-')
slug = recursive_replace(slug, '-')
slug = collapse(slug, '-')
return slug
def get_repo_slug(request):
return request.environ['pylons.routes_dict'].get('repo_name')
def action_logger(user, action, repo, ipaddr='', sa=None):
Action logger for various actions made by users
:param user: user that made this action, can be a unique username string or
object containing user_id attribute
:param action: action to log, should be on of predefined unique actions for
easy translations
:param repo: string name of repository or object containing repo_id,
that action was made on
:param ipaddr: optional ip address from what the action was made
:param sa: optional sqlalchemy session
if not sa:
um = UserModel()
if hasattr(user, 'user_id'):
user_obj = user
elif isinstance(user, basestring):
user_obj = um.get_by_username(user, cache=False)
raise Exception('You have to provide user object or username')
rm = RepoModel()
if hasattr(repo, 'repo_id'):
repo_obj = rm.get(repo.repo_id, cache=False)
repo_name = repo_obj.repo_name
elif isinstance(repo, basestring):
repo_name = repo.lstrip('/')
repo_obj = rm.get_by_repo_name(repo_name, cache=False)
raise Exception('You have to provide repository to action logger')
user_log = UserLog()
user_log.user_id = user_obj.user_id
user_log.action = action
user_log.repository_id = repo_obj.repo_id
user_log.repository_name = repo_name
user_log.action_date = datetime.datetime.now()
user_log.user_ip = ipaddr
sa.add(user_log)
sa.commit()
log.info('Adding user %s, action %s on %s', user_obj, action, repo)
sa.rollback()
def get_repos(path, recursive=False):
Scans given path for repos and return (name,(type,path)) tuple
:param path: path to scann for repositories
:param recursive: recursive search and return names with subdirs in front
from vcs.utils.helpers import get_scm
from vcs.exceptions import VCSError
if path.endswith('/'):
#add ending slash for better results
path = path[:-1]
def _get_repos(p):
for dirpath in os.listdir(p):
if os.path.isfile(os.path.join(p, dirpath)):
cur_path = os.path.join(p, dirpath)
scm_info = get_scm(cur_path)
yield scm_info[1].split(path)[-1].lstrip(os.sep), scm_info
except VCSError:
if not recursive:
#check if this dir containts other repos for recursive scan
rec_path = os.path.join(p, dirpath)
if os.path.isdir(rec_path):
for inner_scm in _get_repos(rec_path):
yield inner_scm
return _get_repos(path)
def check_repo_fast(repo_name, base_path):
Check given path for existence of directory
:param base_path:
:return False: if this directory is present
if os.path.isdir(os.path.join(base_path, repo_name)):return False
def check_repo(repo_name, base_path, verify=True):
repo_path = os.path.join(base_path, repo_name)
if not check_repo_fast(repo_name, base_path):
r = hg.repository(ui.ui(), repo_path)
if verify:
hg.verify(r)
#here we hnow that repo exists it was verified
log.info('%s repo is already created', repo_name)
except RepoError:
#it means that there is no valid repo there...
log.info('%s repo is free for creation', repo_name)
def ask_ok(prompt, retries=4, complaint='Yes or no, please!'):
while True:
ok = raw_input(prompt)
if ok in ('y', 'ye', 'yes'): return True
if ok in ('n', 'no', 'nop', 'nope'): return False
retries = retries - 1
if retries < 0: raise IOError
print complaint
#propagated from mercurial documentation
rhodecode.model.__init__
~~~~~~~~~~~~~~~~~~~~~~~~
The application's model objects
:created_on: Nov 25, 2010
:example:
.. code-block:: python
from paste.deploy import appconfig
conf = appconfig('config:development.ini', relative_to = './../../')
load_environment(conf.global_conf, conf.local_conf)
engine = engine_from_config(config, 'sqlalchemy.')
# RUN YOUR CODE HERE
def init_model(engine):
"""Initializes db session, bind the engine with the metadata,
Call this before using any of the tables or classes in the model, preferably
once in application start
:param engine: engine to bind to
log.info("initializing db for %s", engine)
meta.Base.metadata.bind = engine
class BaseModel(object):
"""Base Model for all RhodeCode models, it adds sql alchemy session
into instance of model
:param sa: If passed it reuses this session instead of creating a new one
def __init__(self, sa=None):
if sa is not None:
self.sa = sa
rhodecode.model.db
Database Models for RhodeCode
:created_on: Apr 08, 2010
from datetime import date
from sqlalchemy import *
from sqlalchemy.orm import relationship, backref
from sqlalchemy.orm.interfaces import MapperExtension
from rhodecode.model.meta import Base, Session
#==============================================================================
# MAPPER EXTENSIONS
class RepositoryMapper(MapperExtension):
def after_update(self, mapper, connection, instance):
class RhodeCodeSettings(Base):
__tablename__ = 'rhodecode_settings'
__table_args__ = (UniqueConstraint('app_settings_name'), {'useexisting':True})
app_settings_id = Column("app_settings_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
app_settings_name = Column("app_settings_name", String(length=255, convert_unicode=False, assert_unicode=None), nullable=True, unique=None, default=None)
app_settings_value = Column("app_settings_value", String(length=255, convert_unicode=False, assert_unicode=None), nullable=True, unique=None, default=None)
def __init__(self, k='', v=''):
self.app_settings_name = k
self.app_settings_value = v
return "<%s('%s:%s')>" % (self.__class__.__name__,
self.app_settings_name, self.app_settings_value)
class RhodeCodeUi(Base):
__tablename__ = 'rhodecode_ui'
__table_args__ = {'useexisting':True}
ui_id = Column("ui_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
ui_section = Column("ui_section", String(length=255, convert_unicode=False, assert_unicode=None), nullable=True, unique=None, default=None)
ui_key = Column("ui_key", String(length=255, convert_unicode=False, assert_unicode=None), nullable=True, unique=None, default=None)
ui_value = Column("ui_value", String(length=255, convert_unicode=False, assert_unicode=None), nullable=True, unique=None, default=None)
ui_active = Column("ui_active", Boolean(), nullable=True, unique=None, default=True)
class User(Base):
__tablename__ = 'users'
__table_args__ = (UniqueConstraint('username'), UniqueConstraint('email'), {'useexisting':True})
user_id = Column("user_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
username = Column("username", String(length=255, convert_unicode=False, assert_unicode=None), nullable=True, unique=None, default=None)
password = Column("password", String(length=255, convert_unicode=False, assert_unicode=None), nullable=True, unique=None, default=None)
active = Column("active", Boolean(), nullable=True, unique=None, default=None)
admin = Column("admin", Boolean(), nullable=True, unique=None, default=False)
name = Column("name", String(length=255, convert_unicode=False, assert_unicode=None), nullable=True, unique=None, default=None)
lastname = Column("lastname", String(length=255, convert_unicode=False, assert_unicode=None), nullable=True, unique=None, default=None)
email = Column("email", String(length=255, convert_unicode=False, assert_unicode=None), nullable=True, unique=None, default=None)
last_login = Column("last_login", DateTime(timezone=False), nullable=True, unique=None, default=None)
ldap_dn = Column("ldap_dn", String(length=255, convert_unicode=False, assert_unicode=None), nullable=True, unique=None, default=None)
api_key = Column("api_key", String(length=255, convert_unicode=False, assert_unicode=None), nullable=True, unique=None, default=None)
user_log = relationship('UserLog', cascade='all')
user_perms = relationship('UserToPerm', primaryjoin="User.user_id==UserToPerm.user_id", cascade='all')
repositories = relationship('Repository')
user_followers = relationship('UserFollowing', primaryjoin='UserFollowing.follows_user_id==User.user_id', cascade='all')
group_member = relationship('UsersGroupMember', cascade='all')
@property
def full_contact(self):
return '%s %s <%s>' % (self.name, self.lastname, self.email)
def short_contact(self):
return '%s %s' % (self.name, self.lastname)
def is_admin(self):
return self.admin
return "<%s('id:%s:%s')>" % (self.__class__.__name__,
self.user_id, self.username)
def by_username(cls, username):
return Session.query(cls).filter(cls.username == username).one()
def update_lastlogin(self):
"""Update user lastlogin"""
session = Session.object_session(self)
self.last_login = datetime.datetime.now()
session.add(self)
session.commit()
log.debug('updated user %s lastlogin', self.username)
session.rollback()
class UserLog(Base):
__tablename__ = 'user_logs'
user_log_id = Column("user_log_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=None, default=None)
repository_id = Column("repository_id", Integer(length=None, convert_unicode=False, assert_unicode=None), ForeignKey('repositories.repo_id'), nullable=False, unique=None, default=None)
repository_name = Column("repository_name", String(length=255, convert_unicode=False, assert_unicode=None), nullable=True, unique=None, default=None)
user_ip = Column("user_ip", String(length=255, convert_unicode=False, assert_unicode=None), nullable=True, unique=None, default=None)
action = Column("action", UnicodeText(length=1200000, convert_unicode=False, assert_unicode=None), nullable=True, unique=None, default=None)
action_date = Column("action_date", DateTime(timezone=False), nullable=True, unique=None, default=None)
def action_as_day(self):
return date(*self.action_date.timetuple()[:3])
user = relationship('User')
repository = relationship('Repository')
class UsersGroup(Base):
__tablename__ = 'users_groups'
users_group_id = Column("users_group_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
users_group_name = Column("users_group_name", String(length=255, convert_unicode=False, assert_unicode=None), nullable=False, unique=True, default=None)
users_group_active = Column("users_group_active", Boolean(), nullable=True, unique=None, default=None)
members = relationship('UsersGroupMember', cascade="all, delete, delete-orphan", lazy="joined")
class UsersGroupMember(Base):
__tablename__ = 'users_groups_members'
users_group_member_id = Column("users_group_member_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
users_group_id = Column("users_group_id", Integer(), ForeignKey('users_groups.users_group_id'), nullable=False, unique=None, default=None)
user = relationship('User', lazy='joined')
users_group = relationship('UsersGroup')
def __init__(self, gr_id='', u_id=''):
self.users_group_id = gr_id
self.user_id = u_id
class Repository(Base):
__tablename__ = 'repositories'
__table_args__ = (UniqueConstraint('repo_name'), {'useexisting':True},)
__mapper_args__ = {'extension':RepositoryMapper()}
repo_id = Column("repo_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
repo_name = Column("repo_name", String(length=255, convert_unicode=False, assert_unicode=None), nullable=False, unique=True, default=None)
clone_uri = Column("clone_uri", String(length=255, convert_unicode=False, assert_unicode=None), nullable=True, unique=False, default=None)
repo_type = Column("repo_type", String(length=255, convert_unicode=False, assert_unicode=None), nullable=False, unique=False, default='hg')
user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=False, default=None)
private = Column("private", Boolean(), nullable=True, unique=None, default=None)
enable_statistics = Column("statistics", Boolean(), nullable=True, unique=None, default=True)
enable_downloads = Column("downloads", Boolean(), nullable=True, unique=None, default=True)
description = Column("description", String(length=10000, convert_unicode=False, assert_unicode=None), nullable=True, unique=None, default=None)
fork_id = Column("fork_id", Integer(), ForeignKey('repositories.repo_id'), nullable=True, unique=False, default=None)
group_id = Column("group_id", Integer(), ForeignKey('groups.group_id'), nullable=True, unique=False, default=None)
fork = relationship('Repository', remote_side=repo_id)
group = relationship('Group')
repo_to_perm = relationship('RepoToPerm', cascade='all', order_by='RepoToPerm.repo_to_perm_id')
users_group_to_perm = relationship('UsersGroupToPerm', cascade='all')
stats = relationship('Statistics', cascade='all', uselist=False)
followers = relationship('UserFollowing', primaryjoin='UserFollowing.follows_repo_id==Repository.repo_id', cascade='all')
logs = relationship('UserLog', cascade='all')
self.repo_id, self.repo_name)
def by_repo_name(cls, repo_name):
return Session.query(cls).filter(cls.repo_name == repo_name).one()
def just_name(self):
return self.repo_name.split(os.sep)[-1]
rhodecode.model.permission
permissions model for RhodeCode
:created_on: Aug 20, 2010
from rhodecode.model import BaseModel
from rhodecode.model.db import User, Permission, UserToPerm, RepoToPerm
class PermissionModel(BaseModel):
"""Permissions model for RhodeCode
def get_permission(self, permission_id, cache=False):
"""Get's permissions by id
:param permission_id: id of permission to get from database
:param cache: use Cache for this query
perm = self.sa.query(Permission)
if cache:
perm = perm.options(FromCache("sql_cache_short",
"get_permission_%s" % permission_id))
return perm.get(permission_id)
def get_permission_by_name(self, name, cache=False):
"""Get's permissions by given name
:param name: name to fetch
:param cache: Use cache for this query
perm = self.sa.query(Permission)\
.filter(Permission.permission_name == name)
"get_permission_%s" % name))
return perm.scalar()
def update(self, form_result):
perm_user = self.sa.query(User)\
.filter(User.username == form_result['perm_user_name']).scalar()
u2p = self.sa.query(UserToPerm).filter(UserToPerm.user == perm_user).all()
if len(u2p) != 3:
raise Exception('Defined: %s should be 3 permissions for default'
' user. This should not happen please verify'
' your database' % len(u2p))
#stage 1 change defaults
for p in u2p:
p.permission = self.get_permission_by_name(
form_result['default_perm'])
self.sa.add(p)
form_result['default_register'])
form_result['default_create'])
#stage 2 update all default permissions for repos if checked
if form_result['overwrite_default'] == True:
for r2p in self.sa.query(RepoToPerm)\
.filter(RepoToPerm.user == perm_user).all():
r2p.permission = self.get_permission_by_name(
self.sa.add(r2p)
#stage 3 set anonymous access
if perm_user.username == 'default':
perm_user.active = bool(form_result['anonymous'])
self.sa.add(perm_user)
rhodecode.model.repo
~~~~~~~~~~~~~~~~~~~~
Repository model for rhodecode
:created_on: Jun 5, 2010
import shutil
from datetime import datetime
from vcs.backends import get_backend
from rhodecode.model.db import Repository, RepoToPerm, User, Permission, \
Statistics, UsersGroup, UsersGroupToPerm, RhodeCodeUi
from rhodecode.model.users_group import UsersGroupMember, UsersGroupModel
class RepoModel(BaseModel):
def repos_path(self):
"""Get's the repositories root path from database
q = self.sa.query(RhodeCodeUi).filter(RhodeCodeUi.ui_key == '/').one()
def get(self, repo_id, cache=False):
repo = self.sa.query(Repository)\
.filter(Repository.repo_id == repo_id)
repo = repo.options(FromCache("sql_cache_short",
"get_repo_%s" % repo_id))
return repo.scalar()
def get_by_repo_name(self, repo_name, cache=False):
.filter(Repository.repo_name == repo_name)
"get_repo_%s" % repo_name))
def get_full(self, repo_name, cache=False, invalidate=False):
.options(joinedload(Repository.fork))\
.options(joinedload(Repository.user))\
.filter(Repository.repo_name == repo_name)\
repo = repo.options(FromCache("sql_cache_long",
"get_repo_full_%s" % repo_name))
if invalidate and cache:
repo.invalidate()
ret = repo.scalar()
#make transient for sake of errors
make_transient(ret)
for k in ['fork', 'user']:
attr = getattr(ret, k, False)
if attr:
make_transient(attr)
def get_users_js(self):
users = self.sa.query(User).filter(User.active == True).all()
u_tmpl = '''{id:%s, fname:"%s", lname:"%s", nname:"%s"},'''
users_array = '[%s]' % '\n'.join([u_tmpl % (u.user_id, u.name,
u.lastname, u.username)
for u in users])
return users_array
def get_users_groups_js(self):
users_groups = self.sa.query(UsersGroup)\
.filter(UsersGroup.users_group_active == True).all()
g_tmpl = '''{id:%s, grname:"%s",grmembers:"%s"},'''
users_groups_array = '[%s]' % '\n'.join([g_tmpl % \
(gr.users_group_id, gr.users_group_name,
len(gr.members))
for gr in users_groups])
return users_groups_array
def update(self, repo_name, form_data):
cur_repo = self.get_by_repo_name(repo_name, cache=False)
user_model = UserModel(self.sa)
users_group_model = UsersGroupModel(self.sa)
#update permissions
for member, perm, member_type in form_data['perms_updates']:
if member_type == 'user':
r2p = self.sa.query(RepoToPerm)\
.filter(RepoToPerm.user == user_model.get_by_username(member))\
.filter(RepoToPerm.repository == cur_repo)\
r2p.permission = self.sa.query(Permission)\
.filter(Permission.permission_name == perm)\
g2p = self.sa.query(UsersGroupToPerm)\
.filter(UsersGroupToPerm.users_group == users_group_model.get_by_groupname(member))\
.filter(UsersGroupToPerm.repository == cur_repo)\
g2p.permission = self.sa.query(Permission)\
self.sa.add(g2p)
#set new permissions
for member, perm, member_type in form_data['perms_new']:
r2p = RepoToPerm()
r2p.repository = cur_repo
r2p.user = user_model.get_by_username(member)
g2p = UsersGroupToPerm()
g2p.repository = cur_repo
g2p.users_group = users_group_model.get_by_groupname(member)
#update current repo
for k, v in form_data.items():
if k == 'user':
cur_repo.user = user_model.get(v)
setattr(cur_repo, k, v)
self.sa.add(cur_repo)
if repo_name != form_data['repo_name']:
#rename our data
self.__rename_repo(repo_name, form_data['repo_name'])
def create(self, form_data, cur_user, just_db=False, fork=False):
if fork:
#force str since hg doesn't go with unicode
repo_name = str(form_data['fork_name'])
org_name = str(form_data['repo_name'])
org_name = repo_name = str(form_data['repo_name'])
new_repo = Repository()
new_repo.enable_statistics = False
if k == 'repo_name':
v = repo_name
setattr(new_repo, k, v)
parent_repo = self.sa.query(Repository)\
.filter(Repository.repo_name == org_name).scalar()
new_repo.fork = parent_repo
new_repo.user_id = cur_user.user_id
self.sa.add(new_repo)
#create default permission
repo_to_perm = RepoToPerm()
default = 'repository.read'
rhodecode.model.scm
Scm model for RhodeCode
import time
from mercurial import ui
from sqlalchemy.orm import make_transient
from beaker.cache import cache_region, region_invalidate
from vcs import get_backend
from vcs.exceptions import RepositoryError, VCSError
from rhodecode import BACKENDS
from rhodecode.lib.auth import HasRepoPermissionAny
from rhodecode.lib.utils import get_repos as get_filesystem_repos, make_ui, \
action_logger
from rhodecode.model.db import Repository, RhodeCodeUi, CacheInvalidation, \
UserFollowing, UserLog
class UserTemp(object):
def __init__(self, user_id):
self.user_id = user_id
return "<%s('id:%s')>" % (self.__class__.__name__, self.user_id)
class RepoTemp(object):
def __init__(self, repo_id):
self.repo_id = repo_id
return "<%s('id:%s')>" % (self.__class__.__name__, self.repo_id)
class ScmModel(BaseModel):
"""Generic Scm Model
def repo_scan(self, repos_path=None):
"""Listing of repositories in given path. This path should not be a
repository itself. Return a dictionary of repository objects
:param repos_path: path to directory containing repositories
log.info('scanning for repositories in %s', repos_path)
if repos_path is None:
repos_path = self.repos_path
baseui = make_ui('db')
repos_list = {}
for name, path in get_filesystem_repos(repos_path, recursive=True):
if repos_list.has_key(name):
raise RepositoryError('Duplicate repository name %s '
'found in %s' % (name, path))
klass = get_backend(path[0])
if path[0] == 'hg' and path[0] in BACKENDS.keys():
repos_list[name] = klass(path[1], baseui=baseui)
if path[0] == 'git' and path[0] in BACKENDS.keys():
repos_list[name] = klass(path[1])
return repos_list
def get_repos(self, all_repos=None):
"""Get all repos from db and for each repo create it's backend instance.
and fill that backed with information from database
:param all_repos: give specific repositories list, good for filtering
this have to be a list of just the repository names
if all_repos is None:
repos = self.sa.query(Repository)\
.order_by(Repository.repo_name).all()
all_repos = [r.repo_name for r in repos]
#get the repositories that should be invalidated
invalidation_list = [str(x.cache_key) for x in \
self.sa.query(CacheInvalidation.cache_key)\
.filter(CacheInvalidation.cache_active == False)\
.all()]
for r_name in all_repos:
r_dbr = self.get(r_name, invalidation_list)
if r_dbr is not None:
repo, dbrepo = r_dbr
last_change = repo.last_change
tip = h.get_changeset_safe(repo, 'tip')
tmp_d = {}
tmp_d['name'] = dbrepo.repo_name
tmp_d['name_sort'] = tmp_d['name'].lower()
tmp_d['description'] = dbrepo.description
tmp_d['description_sort'] = tmp_d['description']
tmp_d['last_change'] = last_change
tmp_d['last_change_sort'] = time.mktime(last_change.timetuple())
tmp_d['tip'] = tip.raw_id
tmp_d['tip_sort'] = tip.revision
tmp_d['rev'] = tip.revision
tmp_d['contact'] = dbrepo.user.full_contact
tmp_d['contact_sort'] = tmp_d['contact']
tmp_d['owner_sort'] = tmp_d['contact']
tmp_d['repo_archives'] = list(repo._get_archives())
tmp_d['last_msg'] = tip.message
tmp_d['repo'] = repo
tmp_d['dbrepo'] = dbrepo.get_dict()
tmp_d['dbrepo_fork'] = dbrepo.fork.get_dict() if dbrepo.fork else {}
yield tmp_d
def get(self, repo_name, invalidation_list=None, retval='all'):
"""Returns a tuple of Repository,DbRepository,
Get's repository from given name, creates BackendInstance and
propagates it's data from database with all additional information
:param invalidation_list: if a invalidation list is given the get
method should not manually check if this repository needs
invalidation and just invalidate the repositories in list
:param retval: string specifing what to return one of 'repo','dbrepo',
'all'if repo or dbrepo is given it'll just lazy load chosen type
and return None as the second
if not HasRepoPermissionAny('repository.read', 'repository.write',
'repository.admin')(repo_name, 'get repo check'):
# CACHE FUNCTION
@cache_region('long_term')
def _get_repo(repo_name):
repo_path = os.path.join(self.repos_path, repo_name)
alias = get_scm(repo_path)[0]
log.debug('Creating instance of %s repository', alias)
backend = get_backend(alias)
log.error('Perhaps this repository is in db and not in '
'filesystem run rescan repositories with '
'"destroy old data " option from admin panel')
if alias == 'hg':
repo = backend(repo_path, create=False, baseui=make_ui('db'))
#skip hidden web repository
if repo._get_hidden():
repo = backend(repo_path, create=False)
return repo
pre_invalidate = True
dbinvalidate = False
if invalidation_list is not None:
pre_invalidate = repo_name in invalidation_list
if pre_invalidate:
#this returns object to invalidate
rhodecode.model.settings
Settings model for RhodeCode
:created on Nov 17, 2010
from rhodecode.model.db import RhodeCodeSettings
class SettingsModel(BaseModel):
Settings model
def get(self, settings_key, cache=False):
r = self.sa.query(RhodeCodeSettings)\
.filter(RhodeCodeSettings.app_settings_name == settings_key).scalar()
r = r.options(FromCache("sql_cache_short",
"get_setting_%s" % settings_key))
def get_app_settings(self, cache=False):
"""Get's config from database, each config key is prefixed with
'rhodecode_' prefix, than global pylons config is updated with such
keys
ret = self.sa.query(RhodeCodeSettings)
ret = ret.options(FromCache("sql_cache_short", "get_hg_settings"))
if not ret:
raise Exception('Could not get application settings !')
settings = {}
for each in ret:
settings['rhodecode_' + each.app_settings_name] = each.app_settings_value
return settings
def get_ldap_settings(self):
Returns ldap settings from database
:returns:
ldap_active
ldap_host
ldap_port
ldap_ldaps
ldap_tls_reqcert
ldap_dn_user
ldap_dn_pass
ldap_base_dn
ldap_filter
ldap_search_scope
ldap_attr_login
ldap_attr_firstname
ldap_attr_lastname
ldap_attr_email
# ldap_search_scope
.filter(RhodeCodeSettings.app_settings_name\
.startswith('ldap_'))\
fd = {}
for row in r:
v = row.app_settings_value
if v in ['true', 'yes', 'on', 'y', 't', '1']:
v = True
elif v in ['false', 'no', 'off', 'n', 'f', '0']:
v = False
fd.update({row.app_settings_name:v})
return fd
rhodecode.model.user
users model for RhodeCode
from rhodecode.model.db import User, RepoToPerm, Repository, Permission, \
UserToPerm, UsersGroupToPerm, UsersGroupMember
from rhodecode.lib import generate_api_key
PERM_WEIGHTS = {'repository.none':0,
'repository.read':1,
'repository.write':3,
'repository.admin':3}
class UserModel(BaseModel):
def get(self, user_id, cache=False):
user = self.sa.query(User)
user = user.options(FromCache("sql_cache_short",
"get_user_%s" % user_id))
return user.get(user_id)
def get_by_username(self, username, cache=False, case_insensitive=False):
if case_insensitive:
user = self.sa.query(User).filter(User.username.ilike(username))
user = self.sa.query(User)\
.filter(User.username == username)
"get_user_%s" % username))
return user.scalar()
def get_by_api_key(self, api_key, cache=False):
.filter(User.api_key == api_key)
"get_user_%s" % api_key))
def create(self, form_data):
new_user = User()
setattr(new_user, k, v)
new_user.api_key = generate_api_key(form_data['username'])
self.sa.add(new_user)
def create_ldap(self, username, password, user_dn, attrs):
Checks if user is in database, if not creates this user marked
as ldap user
:param username:
:param password:
:param user_dn:
:param attrs:
from rhodecode.lib.auth import get_crypt_password
log.debug('Checking for such ldap account in RhodeCode database')
if self.get_by_username(username, case_insensitive=True) is None:
new_user.username = username.lower() # add ldap account always lowercase
new_user.password = get_crypt_password(password)
new_user.api_key = generate_api_key(username)
new_user.email = attrs['email']
new_user.active = True
new_user.ldap_dn = user_dn
new_user.name = attrs['name']
new_user.lastname = attrs['lastname']
log.debug('this %s user exists skipping creation of ldap account',
def create_registration(self, form_data):
if k != 'admin':
body = ('New user registration\n'
'username: %s\n'
'email: %s\n')
body = body % (form_data['username'], form_data['email'])
run_task(tasks.send_email, None,
_('[RhodeCode] New User registration'),
body)
def update(self, user_id, form_data):
user = self.get(user_id, cache=False)
if user.username == 'default':
raise DefaultUserException(
_("You can't Edit this user since it's"
" crucial for entire application"))
if k == 'new_password' and v != '':
user.password = v
user.api_key = generate_api_key(user.username)
setattr(user, k, v)
self.sa.add(user)
def update_my_account(self, user_id, form_data):
if k not in ['admin', 'active']:
def delete(self, user_id):
_("You can't remove this user since it's"
if user.repositories:
raise UserOwnsReposException(_('This user still owns %s '
'repositories and cannot be '
'removed. Switch owners or '
'remove those repositories') \
% user.repositories)
self.sa.delete(user)
def reset_password(self, data):
rhodecode.model.user_group
users groups model for RhodeCode
from rhodecode.model.db import UsersGroup, UsersGroupMember
class UsersGroupModel(BaseModel):
def get(self, users_group_id, cache=False):
users_group = self.sa.query(UsersGroup)
users_group = users_group.options(FromCache("sql_cache_short",
"get_users_group_%s" % users_group_id))
return users_group.get(users_group_id)
def get_by_groupname(self, users_group_name, cache=False,
case_insensitive=False):
user = self.sa.query(UsersGroup)\
.filter(UsersGroup.users_group_name.ilike(users_group_name))
.filter(UsersGroup.users_group_name == users_group_name)
"get_user_%s" % users_group_name))
new_users_group = UsersGroup()
setattr(new_users_group, k, v)
self.sa.add(new_users_group)
def update(self, users_group_id, form_data):
users_group = self.get(users_group_id, cache=False)
if k == 'users_group_members':
users_group.members = []
self.sa.flush()
members_list = []
if v:
for u_id in set(v):
members_list.append(UsersGroupMember(users_group_id,
u_id))
setattr(users_group, 'members', members_list)
setattr(users_group, k, v)
self.sa.add(users_group)
def delete(self, users_group_id):
self.sa.delete(users_group)
rhodecode.websetup
Weboperations and setup for rhodecode
def setup_app(command, conf, vars):
"""Place any commands to setup rhodecode here"""
dbconf = conf['sqlalchemy.db1.url']
dbmanage = DbManage(log_sql=True, dbconf=dbconf, root=conf['here'],
tests=False)
dbmanage.create_tables(override=True)
dbmanage.set_db_version()
dbmanage.create_settings(dbmanage.config_prompt(None))
dbmanage.create_default_user()
dbmanage.admin_prompt()
dbmanage.create_permissions()
dbmanage.populate_default_permissions()
load_environment(conf.global_conf, conf.local_conf, initial=True)
Status change: