2025-12-01

This commit is contained in:
2026-03-17 14:58:51 -06:00
parent 183e865f8b
commit 4b82b57113
6846 changed files with 954887 additions and 162606 deletions
+674
View File
@@ -0,0 +1,674 @@
GNU GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
Copyright (C) 2007 Free Software Foundation, Inc. <https://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 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
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 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 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.
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.
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, 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
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
"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.
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
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.
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.
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.
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.
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.
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 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.
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.
If 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 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.
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.
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 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.
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.
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.
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.
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.
17. Interpretation of Sections 15 and 16.
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.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
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
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, see <https://www.gnu.org/licenses/>.
Also add information on how to contact you by electronic and paper mail.
If the program does terminal interaction, make it output a short
notice like this when it starts in an interactive mode:
<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, your program's commands
might be different; for a GUI interface, you would use an "about box".
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
<https://www.gnu.org/licenses/>.
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
<https://www.gnu.org/licenses/why-not-lgpl.html>.
+4
View File
@@ -0,0 +1,4 @@
# Blender SVN
blender-svn is a Blender add-on to interact with the Subversion version control system from within Blender.
You can find the documentation [here](https://studio.blender.org/tools/addons/blender_svn).
+76
View File
@@ -0,0 +1,76 @@
# SPDX-FileCopyrightText: 2021 Blender Studio Tools Authors
#
# SPDX-License-Identifier: GPL-3.0-or-later
import importlib
import bpy
from . import (
props,
repository,
operators,
threaded,
ui,
prefs,
svn_info,
)
bl_info = {
"name": "Blender SVN",
"author": "Demeter Dzadik, Paul Golter",
"description": "An SVN (Subversion) interface built directly into Blender",
"blender": (3, 1, 0),
"version": (1, 0, 3),
"location": "View3D",
"warning": "",
"doc_url": "",
"tracker_url": "https://projects.blender.org/studio/blender-studio-tools/src/branch/main/scripts-blender/addons/blender_svn",
"category": "Generic",
}
modules = [
props,
operators,
repository,
threaded,
ui,
prefs,
svn_info,
]
def register_unregister_modules(modules, register: bool):
"""Recursively register or unregister modules by looking for either
un/register() functions or lists named `registry` which should be a list of
registerable classes.
"""
register_func = bpy.utils.register_class if register else bpy.utils.unregister_class
for m in modules:
if register:
importlib.reload(m)
if hasattr(m, 'registry'):
for c in m.registry:
try:
register_func(c)
except Exception as e:
un = 'un' if not register else ''
print(f"Warning: Failed to {un}register class: {c.__name__}")
print(e)
if hasattr(m, 'modules'):
register_unregister_modules(m.modules, register)
if register and hasattr(m, 'register'):
m.register()
elif hasattr(m, 'unregister'):
m.unregister()
def register():
register_unregister_modules(modules, True)
def unregister():
register_unregister_modules(modules, False)
@@ -0,0 +1,29 @@
schema_version = "1.0.0"
id = "blender_svn"
version = "1.0.3"
name = "Blender SVN"
tagline = "An SVN (Subversion) interface built directly into Blender"
maintainer = "Demeter Dzadik <demeter@blender.org>"
type = "add-on"
website = "https://studio.blender.org/tools/addons/blender_svn"
tags = ["Pipeline"]
blender_version_min = "4.2.0"
license = [
"SPDX:GPL-3.0-or-later",
]
copyright = [
"2019-2025 Demeter Dzadik & Blender Studio",
]
wheels = [
"./wheels/python_dateutil-2.8.2-py2.py3-none-any.whl",
"./wheels/Send2Trash-1.8.0-py3-none-any.whl",
"./wheels/six-1.16.0-py2.py3-none-any.whl",
"./wheels/xmltodict-0.12.0-py2.py3-none-any.whl",
]
[permissions]
files = "To update files in the local SVN repository checkout, or move them to system trash"
+122
View File
@@ -0,0 +1,122 @@
# SPDX-FileCopyrightText: 2022 Blender Studio Tools Authors
#
# SPDX-License-Identifier: GPL-3.0-or-later
from collections import OrderedDict
SVN_STATUS_DATA = OrderedDict(
[
(
"added",
(
"ADD",
"This file was added",
),
),
(
"conflicted",
(
"ERROR",
"This file was modified locally, and a newer version has appeared on the remote repository at the same time. To resolve the conflict, one of the changes must be discarded",
),
),
(
"deleted",
(
"TRASH",
"This file was deleted",
),
),
(
"external",
(
"EXTERNAL_DRIVE",
"This file is present because of an externals definition",
),
),
(
"ignored",
(
"RADIOBUT_OFF",
"This file is being ignored (e.g., with the svn:ignore property)",
),
),
(
"incomplete",
(
"FOLDER_REDIRECT",
"A directory is incomplete (a checkout or update was interrupted)",
),
),
("merged", ("AUTOMERGE_ON", "TODO")),
(
"missing",
(
"FILE_HIDDEN",
"This file is missing (e.g., you moved or deleted it without using svn)",
),
),
(
"modified",
(
"GREASEPENCIL",
"This file was modified",
),
),
(
"none",
(
"TIME",
"There is a newer version of this file available on the remote repository. You should update it",
),
),
(
"normal",
(
"CHECKMARK",
"This file is in the repository. There are no local modifications to commit",
),
),
("obstructed", ("ERROR", "Something has gone horribly wrong. Try svn cleanup")),
(
"replaced",
(
"FILE_REFRESH",
"This file has been moved",
),
),
(
"unversioned",
(
"FILE_NEW",
"This file is new in file system, but not yet added to the local repository. It needs to be added before it can be committed to the remote repository",
),
),
]
)
# Based on PySVN/svn/constants.py/STATUS_TYPE_LOOKUP.
ENUM_SVN_STATUS = [
(status, status.title(),
SVN_STATUS_DATA[status][1], SVN_STATUS_DATA[status][0], i)
for i, status in enumerate(SVN_STATUS_DATA.keys())
]
SVN_STATUS_CHAR_TO_NAME = {
'': 'normal',
'A': 'added',
'D': 'deleted',
'M': 'modified',
'R': 'replaced',
'C': 'conflicted',
'X': 'external',
'I': 'ignored',
'?': 'unversioned',
'!': 'missing',
'~': 'replaced'
}
SVN_STATUS_NAME_TO_CHAR = {value: key for key,
value in SVN_STATUS_CHAR_TO_NAME.items()}
@@ -0,0 +1,19 @@
# SPDX-FileCopyrightText: 2025 Blender Studio Tools Authors
#
# SPDX-License-Identifier: GPL-3.0-or-later
from . import (
simple_commands,
svn_commit,
svn_update,
ui_operators,
svn_checkout
)
modules = [
simple_commands,
svn_commit,
svn_update,
ui_operators,
svn_checkout
]
@@ -0,0 +1,503 @@
# SPDX-FileCopyrightText: 2021 Blender Studio Tools Authors
#
# SPDX-License-Identifier: GPL-3.0-or-later
from typing import List, Dict, Union, Any, Set, Optional, Tuple
from pathlib import Path
import bpy
from bpy.props import StringProperty, IntProperty, EnumProperty, BoolProperty
from bpy.types import Context, Operator
from send2trash import send2trash
from ..threaded.execute_subprocess import execute_svn_command
from ..threaded.background_process import Processes
from ..util import get_addon_prefs, redraw_viewport
class SVN_Operator:
@staticmethod
def update_file_list(context):
repo = context.scene.svn.get_repo(context)
repo.refresh_ui_lists(context)
def execute_svn_command(self, context, command: List[str], use_cred=False) -> str:
# Since a status update might already be being requested when an SVN operator is run,
# we want to ignore the first update after any SVN operator.
# Otherwise it can result in a predicted state being overwritten by an outdated state.
# For example, the Commit operator sets a file to "Normal" state, then the old svn status
# arrives and sets it back to "Modified" state, which it isn't anymore.
return execute_svn_command(context, command, use_cred=use_cred)
class SVN_Operator_Single_File(SVN_Operator):
"""Base class for SVN operators operating on a single file."""
file_rel_path: StringProperty()
# Flag to differentiate operators that require that the file exists pre-execute.
missing_file_allowed = False
def execute(self, context: Context) -> Set[str]:
if not self.file_exists(context) and not type(self).missing_file_allowed:
# If the operator requires the file to exist and it doesn't, cancel.
self.report(
{'ERROR'},
f'File is no longer on the file system: "{self.file_rel_path}"',
)
return {'CANCELLED'}
status = Processes.get('Status')
if status:
Processes.kill('Status')
ret = self._execute(context)
file = self.get_file(context)
Processes.start('Status')
redraw_viewport()
self.update_file_list(context)
return ret
def _execute(self, context: Context) -> Set[str]:
raise NotImplementedError
def get_file_full_path(self, context) -> Path:
repo = context.scene.svn.get_repo(context)
return Path.joinpath(Path(repo.directory), Path(self.file_rel_path))
def get_file(self, context) -> "SVN_file":
repo = context.scene.svn.get_repo(context)
return repo.external_files.get(self.file_rel_path)
def file_exists(self, context) -> bool:
exists = self.get_file_full_path(context).exists()
if not exists and not type(self).missing_file_allowed:
self.report({'INFO'}, "File was not found, cancelling.")
return exists
def set_predicted_file_status(self, repo, file_entry: "SVN_file"):
return
class Popup_Operator:
popup_width = 400
def invoke(self, context, event):
return context.window_manager.invoke_props_dialog(
self, width=type(self).popup_width
)
class Warning_Operator(Popup_Operator):
def draw(self, context):
layout = self.layout.column(align=True)
warning = self.get_warning_text(context)
for line in warning.split("\n"):
row = layout.row()
row.alert = True
row.label(text=line)
def get_warning_text(self, context):
raise NotImplemented
class May_Modifiy_Current_Blend(SVN_Operator_Single_File, Warning_Operator):
def file_is_current_blend(self, context) -> bool:
current_blend = context.scene.svn.get_repo(context).current_blend_file
return current_blend and current_blend.svn_path == self.file_rel_path
set_outdated_flag = True
reload_file: BoolProperty(
name="Reload File (Keep UI)",
description="Reload the file after the operation is completed. The UI layout will be preserved",
default=False,
)
def invoke(self, context, event):
self.reload_file = False
if self.file_is_current_blend(context) or self.get_warning_text(context):
return context.window_manager.invoke_props_dialog(self, width=500)
return self.execute(context)
def get_warning_text(self, context):
if self.file_is_current_blend(context):
return "This will modify the currently opened .blend file."
return ""
def draw(self, context):
super().draw(context)
if self.file_is_current_blend(context):
self.layout.prop(self, 'reload_file')
def execute(self, context):
super().execute(context)
if self.reload_file:
bpy.ops.wm.open_mainfile(filepath=bpy.data.filepath, load_ui=False)
elif self.file_is_current_blend(context) and self.set_outdated_flag:
context.scene.svn.file_is_outdated = True
return {'FINISHED'}
class SVN_OT_update_single(May_Modifiy_Current_Blend, Operator):
bl_idname = "svn.update_single"
bl_label = "Update File"
bl_description = (
"Download the latest available version of this file from the remote repository"
)
bl_options = {'INTERNAL'}
missing_file_allowed = True
def _execute(self, context: Context) -> Set[str]:
self.will_conflict = False
repo = context.scene.svn.get_repo(context)
file_entry = repo.external_files.get(self.file_rel_path)
if file_entry.status not in ['normal', 'none']:
self.will_conflict = True
self.execute_svn_command(
context,
["svn", "up", f"{self.file_rel_path}", "--accept", "postpone"],
use_cred=True,
)
self.report({'INFO'}, f'Updated "{self.file_rel_path}" to the latest version.')
def set_predicted_file_status(self, repo, file_entry: "SVN_file"):
if self.will_conflict:
file_entry.status = 'conflicted'
else:
file_entry.status = 'normal'
file_entry.repos_status = 'none'
return {"FINISHED"}
class SVN_OT_download_file_revision(May_Modifiy_Current_Blend, Operator):
bl_idname = "svn.download_file_revision"
bl_label = "Download Revision"
bl_description = "Download this revision of this file"
bl_options = {'INTERNAL'}
missing_file_allowed = True
revision: IntProperty(default=0)
def invoke(self, context, event):
repo = context.scene.svn.get_repo(context)
file_entry = repo.external_files.get(self.file_rel_path)
if self.file_is_current_blend(context) and file_entry.status != 'normal':
self.report(
{'ERROR'}, 'You must first revert or commit the changes to this file.'
)
return {'CANCELLED'}
return super().invoke(context, event)
def _execute(self, context: Context) -> Set[str]:
repo = context.scene.svn.get_repo(context)
file_entry = repo.external_files.get(self.file_rel_path)
if file_entry.status == 'modified':
# If file has local modifications, let's avoid a conflict by cancelling
# and telling the user to resolve it in advance.
self.report(
{'ERROR'},
"Cancelled: You have local modifications to this file. You must revert or commit it first!",
)
return {'CANCELLED'}
self.svn_download_file_revision(context, self.file_rel_path, self.revision)
self.report(
{'INFO'}, f"Checked out revision {self.revision} of {self.file_rel_path}"
)
return {"FINISHED"}
def svn_download_file_revision(self, context, svn_file_path: str, revision=0):
commands = ["svn", "up", f"{self.file_rel_path}", "--accept", "postpone"]
if self.revision > 0:
commands.insert(2, f"-r{self.revision}")
self.execute_svn_command(context, commands, use_cred=True)
def set_predicted_file_status(self, repo, file_entry: "SVN_file"):
file_entry['revision'] = self.revision
latest_rev = repo.get_latest_revision_of_file(self.file_rel_path)
if latest_rev == self.revision:
file_entry.status = 'normal'
file_entry.repos_status = 'none'
else:
file_entry.status = 'normal'
file_entry.repos_status = 'modified'
class SVN_OT_restore_file(May_Modifiy_Current_Blend, Operator):
bl_idname = "svn.restore_file"
bl_label = "Restore File"
bl_description = "Restore this deleted file to its previously checked out revision"
bl_options = {'INTERNAL'}
missing_file_allowed = True
def svn_revert(self, context, svn_file_path):
self.execute_svn_command(context, ["svn", "revert", f"{svn_file_path}"])
def _execute(self, context: Context) -> Set[str]:
self.svn_revert(context, self.file_rel_path)
return {"FINISHED"}
def set_predicted_file_status(self, repo, file_entry: "SVN_file"):
file_entry.status = 'normal'
class SVN_OT_revert_file(SVN_OT_restore_file):
bl_idname = "svn.revert_file"
bl_label = "Revert File"
bl_description = "PERMANENTLY DISCARD local changes to this file and return it to the state of the last local revision. Cannot be undone"
bl_options = {'INTERNAL'}
missing_file_allowed = False
def get_warning_text(self, context) -> str:
return (
"You will irreversibly and permanently lose the changes you've made to this file:\n "
+ self.file_rel_path
)
class SVN_OT_revert_and_update(SVN_OT_download_file_revision, SVN_OT_revert_file):
"""Convenience operator for the "This file is outdated" warning message. Normally, these two operations should be done separately!"""
bl_idname = "svn.revert_and_update_file"
bl_label = "Revert And Update File"
bl_description = "A different version of this file was downloaded while it was open. This warning will persist until the file is updated and reloaded, or committed. Click to PERMANENTLY DISCARD local changes to this file and update it to the latest revision. Cannot be undone"
bl_options = {'INTERNAL'}
missing_file_allowed = False
def invoke(self, context, event):
return super(May_Modifiy_Current_Blend, self).invoke(context, event)
def get_warning_text(self, context) -> str:
if self.get_file(context).status != 'normal':
return (
"You will irreversibly and permanently lose the changes you've made to this file:\n "
+ self.file_rel_path
)
else:
return "File will be updated to latest revision."
def _execute(self, context: Context) -> Set[str]:
self.svn_revert(context, self.file_rel_path)
self.svn_download_file_revision(context, self.file_rel_path, self.revision)
return {"FINISHED"}
class SVN_OT_add_file(SVN_Operator_Single_File, Operator):
bl_idname = "svn.add_file"
bl_label = "Add File"
bl_description = (
"Mark this file for addition to the remote repository. It can then be committed"
)
bl_options = {'INTERNAL'}
def _execute(self, context: Context) -> Set[str]:
result = self.execute_svn_command(
context, ["svn", "add", f"{self.file_rel_path}"]
)
if result:
f = self.get_file(context)
return {"FINISHED"}
def set_predicted_file_status(self, repo, file_entry: "SVN_file"):
file_entry.status = 'added'
class SVN_OT_unadd_file(SVN_Operator_Single_File, Operator):
bl_idname = "svn.unadd_file"
bl_label = "Un-Add File"
bl_description = "Un-mark this file as being added to the remote repository. It will not be committed"
bl_options = {'INTERNAL'}
def _execute(self, context: Context) -> Set[str]:
self.execute_svn_command(
context, ["svn", "rm", "--keep-local", f"{self.file_rel_path}"]
)
return {"FINISHED"}
def set_predicted_file_status(self, repo, file_entry: "SVN_file"):
file_entry.status = 'unversioned'
class SVN_OT_trash_file(SVN_Operator_Single_File, Warning_Operator, Operator):
bl_idname = "svn.trash_file"
bl_label = "Trash File"
bl_description = "Move this file to the recycle bin"
bl_options = {'INTERNAL'}
file_rel_path: StringProperty()
missing_file_allowed = False
def get_warning_text(self, context):
return (
"Are you sure you want to move this file to the recycle bin?\n "
+ self.file_rel_path
)
def _execute(self, context: Context) -> Set[str]:
send2trash([self.get_file_full_path(context)])
f = self.get_file(context)
# Since this operator is only available for Unversioned files,
# we want to remove the file entry when removing the file.
context.scene.svn.get_repo(context).remove_file_entry(f)
return {"FINISHED"}
class SVN_OT_remove_file(SVN_Operator_Single_File, Warning_Operator, Operator):
bl_idname = "svn.remove_file"
bl_label = "Remove File"
bl_description = "Mark this file for removal from the remote repository"
bl_options = {'INTERNAL'}
missing_file_allowed = True
def get_warning_text(self, context):
return (
"This file will be deleted for everyone:\n "
+ self.file_rel_path
+ "\nAre you sure?"
)
def _execute(self, context: Context) -> Set[str]:
self.execute_svn_command(context, ["svn", "remove", f"{self.file_rel_path}"])
return {"FINISHED"}
def set_predicted_file_status(self, repo, file_entry: "SVN_file"):
file_entry.status = 'deleted'
class SVN_OT_resolve_conflict(May_Modifiy_Current_Blend, Operator):
bl_idname = "svn.resolve_conflict"
bl_label = "Resolve Conflict"
bl_description = "Resolve a conflict, by discarding either local or remote changes"
bl_options = {'INTERNAL'}
set_outdated_flag = False
resolve_method: EnumProperty(
name="Resolve Method",
description="Method to use to resolve the conflict",
items=[
(
'mine-full',
'Keep Mine',
'Overwrite the new changes downloaded from the remote, and keep the local changes instead',
),
(
'theirs-full',
'Keep Theirs',
'Overwrite the local changes with those downloaded from the remote',
),
],
)
def invoke(self, context, event):
wm = context.window_manager
return wm.invoke_props_dialog(self, width=500)
def draw(self, context):
layout = self.layout
col = layout.column(align=True)
col.alert = True
col.label(text="Choose which version of the file to keep.")
col.row().prop(self, 'resolve_method', expand=True)
col.separator()
if self.resolve_method == 'mine-full':
col.label(text="Local changes will be kept.")
col.label(
text="When committing, the changes someone else made will be overwritten."
)
else:
col.label(text="Local changes will be permanently lost.")
super().draw(context)
def _execute(self, context: Context) -> Set[str]:
self.execute_svn_command(
context,
[
"svn",
"resolve",
f"{self.file_rel_path}",
"--accept",
f"{self.resolve_method}",
],
)
if self.file_is_current_blend(context):
# If user wants to keep their changes to the current file,
# remove the outdated file warning UI.
context.scene.svn.file_is_outdated = self.resolve_method != 'mine-full'
return {"FINISHED"}
def set_predicted_file_status(self, repo, file_entry: "SVN_file"):
if self.resolve_method == 'mine-full':
file_entry.status = 'modified'
else:
file_entry.status = 'normal'
class SVN_OT_cleanup(SVN_Operator, Operator):
bl_idname = "svn.cleanup"
bl_label = "SVN Cleanup"
bl_description = "Resolve issues that can arise from previous SVN processes having been interrupted"
bl_options = {'INTERNAL'}
@classmethod
def poll(cls, context):
# Don't allow attempting to cleanup while Update/Commit is running.
return not get_addon_prefs(context).is_busy
def execute(self, context: Context) -> Set[str]:
repo = context.scene.svn.get_repo(context)
repo.external_files.clear()
self.execute_svn_command(context, ["svn", "cleanup"])
repo.reload_svn_log(context)
Processes.kill('Commit')
Processes.kill('Update')
Processes.kill('Authenticate')
Processes.kill('Activate File')
Processes.restart('Status')
Processes.restart('Log')
Processes.restart('Redraw Viewport')
self.report({'INFO'}, "SVN Cleanup complete.")
return {"FINISHED"}
registry = [
SVN_OT_update_single,
SVN_OT_revert_and_update,
SVN_OT_revert_file,
SVN_OT_restore_file,
SVN_OT_download_file_revision,
SVN_OT_add_file,
SVN_OT_unadd_file,
SVN_OT_trash_file,
SVN_OT_remove_file,
SVN_OT_resolve_conflict,
SVN_OT_cleanup,
]
@@ -0,0 +1,98 @@
# SPDX-FileCopyrightText: 2022 Blender Studio Tools Authors
#
# SPDX-License-Identifier: GPL-3.0-or-later
from typing import List, Dict, Union, Any, Set, Optional, Tuple
from bpy.types import Operator
from bpy.props import BoolProperty
from .simple_commands import SVN_Operator
from ..util import get_addon_prefs
from ..threaded.background_process import Processes
import subprocess
from pathlib import Path
class SVN_OT_checkout_initiate(Operator):
bl_idname = "svn.checkout_initiate"
bl_label = "Initiate SVN Checkout"
bl_description = "Checkout a remote SVN repository"
bl_options = {'INTERNAL'}
create: BoolProperty(
name="Create Repo Entry",
description="Whether a new repo entry should be created, or the active one used",
default=True
)
def execute(self, context):
prefs = get_addon_prefs(context)
if self.create:
prefs.repositories.add()
prefs.active_repo_idx = len(prefs.repositories)-1
prefs.checkout_mode = True
return {'FINISHED'}
class SVN_OT_checkout_finalize(Operator, SVN_Operator):
bl_idname = "svn.checkout_finalize"
bl_label = "Finalize SVN Checkout"
bl_description = "Checkout the specified SVN repository to the selected path"
bl_options = {'INTERNAL'}
def execute(self, context):
prefs = get_addon_prefs(context)
repo = prefs.active_repo
# `svn checkout` is an outlier in every way from other SVN commands:
# - Credentials are provided with an equal sign
# - We need live output in the console, but we don't need to store it.
# - It needs to be able to run even if the current directory isn't a valid repo.
# So, we're not going to use our `execute_subprocess` api here.
self.execute_svn_command(
context,
['svn', 'cleanup']
)
p = subprocess.Popen(
["svn", "checkout", f"--username={repo.username}",
f"--password={repo.password}", repo.url, repo.display_name],
shell=False,
cwd=repo.directory+"/",
stdout=subprocess.PIPE,
start_new_session=True
)
repo.directory = str((Path(repo.directory) / repo.display_name))
while True:
line = p.stdout.readline().decode()
print(line.replace("\n", ""))
if not line:
break
prefs = get_addon_prefs(context)
prefs.checkout_mode = False
prefs.save_repo_info_to_file()
Processes.start('Authenticate')
return {'FINISHED'}
class SVN_OT_checkout_cancel(Operator):
bl_idname = "svn.checkout_cancel"
bl_label = "Cancel SVN Checkout"
bl_description = "Cancel the checkout UI"
bl_options = {'INTERNAL'}
def execute(self, context):
prefs = get_addon_prefs(context)
prefs.checkout_mode = False
repo = prefs.active_repo
if not repo.url and not repo.username and not repo.password and not repo.directory:
prefs.repositories.remove(prefs.active_repo_idx)
return {'FINISHED'}
registry = [
SVN_OT_checkout_initiate,
SVN_OT_checkout_finalize,
SVN_OT_checkout_cancel
]
@@ -0,0 +1,234 @@
# SPDX-FileCopyrightText: 2023 Blender Studio Tools Authors
#
# SPDX-License-Identifier: GPL-3.0-or-later
from typing import List, Dict, Union, Any, Set, Optional, Tuple
import bpy
from bpy.types import PropertyGroup, Operator, Context
from bpy.props import StringProperty
from ..threaded.background_process import Processes
from .simple_commands import SVN_Operator, Popup_Operator
from ..util import get_addon_prefs
# Store a reference to the running operator in global namespace when it runs,
# so that its sub-operators can mess
active_commit_operator = None
class SVN_commit_line(PropertyGroup):
"""Property Group representing a single line of a commit message.
Only needed for UI/UX purpose, so we can store the commit message
even if the user changes their mind about wanting to commit."""
def update_line(self, context):
line_entries = context.scene.svn.get_repo(context).commit_lines
for i, line_entry in enumerate(line_entries):
if line_entry == self and i >= len(line_entries)-2:
# The last line was just modified
if self.line:
# Content was added to the last line - add another line.
line_entries.add()
line: StringProperty(update=update_line)
class SVN_OT_commit(SVN_Operator, Popup_Operator, Operator):
bl_idname = "svn.commit"
bl_label = "SVN Commit"
bl_description = "Commit a selection of files to the remote repository"
bl_options = {'INTERNAL'}
bl_property = "first_line" # Focus the text input box
popup_width = 600
# The first line of the commit message needs to be an operator property in order
# for us to be able to focus the input box automatically when the window pops up
# (see bl_property above)
def update_first_line(self, context):
repo = context.scene.svn.get_repo(context)
repo.commit_lines[0].line = self.first_line
first_line: StringProperty(
name="First Line",
description="First line of the commit message",
update=update_first_line
)
@staticmethod
def get_committable_files(context) -> List["SVN_file"]:
"""Return the list of file entries whose status allows committing"""
repo = context.scene.svn.get_repo(context)
if not repo:
return
svn_file_list = repo.external_files
committable_statuses = ['modified', 'added', 'deleted']
files_to_commit = [
f for f in svn_file_list if f.status in committable_statuses]
return files_to_commit
@classmethod
def poll(cls, context):
if get_addon_prefs(context).is_busy:
# Don't allow attempting to Update/Commit while either is still running.
return False
return cls.get_committable_files(context)
def invoke(self, context, event):
repo = context.scene.svn.get_repo(context)
if repo.commit_message == "":
repo.commit_message = ""
global active_commit_operator
active_commit_operator = self
self.first_line = repo.commit_lines[0].line
self.is_file_really_dirty = bpy.data.is_dirty
# This flag is needed as a workaround because bpy.data.is_dirty gets set to True
# when we change the operator's checkboxes or
self.is_file_dirty_on_invoke = bpy.data.is_dirty
for f in repo.external_files:
f.include_in_commit = False
for f in self.get_committable_files(context):
if not f.will_conflict:
f.include_in_commit = True
return super().invoke(context, event)
def draw(self, context):
"""Draws the boolean toggle list with a list of strings for the button texts."""
layout = self.layout
files = self.get_committable_files(context)
layout.label(
text="These files will be pushed to the remote repository:")
repo = context.scene.svn.get_repo(context)
row = layout.row()
row.label(text="Filename")
row.label(text="Status")
for file in files:
row = layout.row()
split = row.split()
checkbox_ui = split.row()
status_ui = split.row()
checkbox_ui.prop(file, "include_in_commit", text=file.file_name)
text = file.status_name
icon = file.status_icon
if file.will_conflict:
# We don't want to conflict-resolve during a commit, it's
# confusing. User should resolve this as a separate step.
checkbox_ui.enabled = False
text = "Conflicting"
status_ui.alert = True
icon = 'ERROR'
elif file == repo.current_blend_file and self.is_file_really_dirty:
split = status_ui.split(factor=0.7)
status_ui = split.row()
status_ui.alert = True
text += " but not saved!"
icon = 'ERROR'
op_row = split.row()
op_row.alignment = 'LEFT'
op_row.operator('svn.save_during_commit',
icon='FILE_BLEND', text="Save")
status_ui.label(text=text, icon=icon)
row = layout.row()
row.label(text="Commit message:")
# Draw input box for first line, which is special because we want it to
# get focused automatically for smooth UX. (see `bl_property` above)
row = layout.row()
row.prop(self, 'first_line', text="")
row.operator(SVN_OT_commit_msg_clear.bl_idname, text="", icon='TRASH')
for i in range(1, len(repo.commit_lines)):
# Draw input boxes until the last one that has text, plus two, minimum three.
# Why two after the last line? Because then you can use Tab to go to the next line.
# Why at least 3 lines? Because then you can write a one-liner without
# the OK button jumping away.
layout.prop(
repo.commit_lines[i], 'line', index=i, text="")
continue
def execute(self, context: Context) -> Set[str]:
committable_files = self.get_committable_files(context)
files_to_commit = [f for f in committable_files if f.include_in_commit]
repo = context.scene.svn.get_repo(context)
if not files_to_commit:
self.report({'ERROR'},
"No files were selected, nothing to commit.")
return {'CANCELLED'}
if len(repo.commit_message) < 2:
self.report({'ERROR'},
"Please describe your changes in the commit message.")
return {'CANCELLED'}
filepaths = [f.svn_path for f in files_to_commit]
self.set_predicted_file_statuses(files_to_commit)
Processes.stop('Status')
Processes.start('Commit',
commit_msg=repo.commit_message,
file_list=filepaths
)
report = f"{(len(files_to_commit))} files"
if len(files_to_commit) == 1:
report = files_to_commit[0].svn_path
self.report({'INFO'},
f"Started committing {report}. See console for when it's finished.")
return {"FINISHED"}
def set_predicted_file_statuses(self, file_entries):
for f in file_entries:
if f.status != 'deleted':
if f.repos_status == 'none':
# We modified the file, and it was not modified on the repo,
# predict the status to be "normal".
f.status = 'normal'
else:
# If we modified the file, but it was modified on the repo:
f.status = 'conflicted'
# TODO: What happens if we DID delete the file, AND it was modified on the repo?
# Should probably also predict a conflict.
f.status_prediction_type = "SVN_COMMIT"
class SVN_OT_commit_save_file(Operator):
bl_idname = "svn.save_during_commit"
bl_label = "Save During SVN Commit"
bl_description = "Save During SVN Commit"
bl_options = {'INTERNAL'}
def execute(self, context):
global active_commit_operator
active_commit_operator.is_file_really_dirty = False
bpy.ops.wm.save_mainfile()
return {'FINISHED'}
class SVN_OT_commit_msg_clear(Operator):
bl_idname = "svn.clear_commit_message"
bl_label = "Clear SVN Commit Message"
bl_description = "Clear the commit message"
bl_options = {'INTERNAL'}
def execute(self, context):
context.scene.svn.get_repo(context).commit_message = ""
global active_commit_operator
active_commit_operator.first_line = ""
return {'FINISHED'}
registry = [
SVN_OT_commit,
SVN_OT_commit_save_file,
SVN_OT_commit_msg_clear,
SVN_commit_line
]
@@ -0,0 +1,96 @@
# SPDX-FileCopyrightText: 2022 Blender Studio Tools Authors
#
# SPDX-License-Identifier: GPL-3.0-or-later
from typing import Set
import bpy
from bpy.types import Operator, Context
from bpy.props import IntProperty
from .simple_commands import May_Modifiy_Current_Blend
from ..threaded.background_process import Processes
from ..util import get_addon_prefs
class SVN_OT_update_all(May_Modifiy_Current_Blend, Operator):
bl_idname = "svn.update_all"
bl_label = "SVN Update All"
bl_description = "Download all the latest updates from the remote repository"
bl_options = {'INTERNAL'}
revision: IntProperty(
name="Revision",
description="Which revision to revert the repository to. 0 means to update to the latest version instead",
default=0
)
@classmethod
def poll(cls, context):
if get_addon_prefs(context).is_busy:
# Don't allow attempting to Update/Commit while either is still running.
return False
repo = context.scene.svn.get_repo(context)
if not repo:
return False
for f in repo.external_files:
if f.repos_status != 'none':
return True
return True
def invoke(self, context, event):
repo = context.scene.svn.get_repo(context)
current_blend = repo.current_blend_file
if self.revision == 0:
if current_blend and current_blend.repos_status != 'none':
# If the current file will be modified, warn user.
self.file_rel_path = current_blend.svn_path
return context.window_manager.invoke_props_dialog(self, width=500)
else:
for f in repo.external_files:
if f.status in ['modified', 'added', 'conflicted', 'deleted', 'missing', 'unversioned']:
# If user wants to check out an older version of the repo but
# there are uncommitted local changes to any files, warn user.
return context.window_manager.invoke_props_dialog(self, width=500)
return self.execute(context)
def draw(self, context):
if self.revision != 0:
layout = self.layout
col = layout.column()
col.label(text="You have uncommitted local changes.")
col.label(
text="These won't be lost, but if you want to revert the state of the entire local repository to a ")
col.label(
text="past point in time, you would get a better result if you reverted or committed your changes first.")
col.separator()
col.label(
text="Press OK to proceed anyways. Click out of this window to cancel.")
super().draw(context)
def execute(self, context: Context) -> Set[str]:
Processes.stop('Status')
if self.reload_file:
current_file = context.scene.svn.get_repo(context).current_blend_file
command = ["svn", "up", current_file.svn_path, "--accept", "postpone"]
if self.revision > 0:
command.insert(2, f"-r{self.revision}")
self.execute_svn_command(
context,
command,
use_cred=True
)
bpy.ops.wm.open_mainfile(filepath=bpy.data.filepath, load_ui=False)
Processes.start('Log')
Processes.start('Update', revision=self.revision)
return {"FINISHED"}
registry = [
SVN_OT_update_all,
]
@@ -0,0 +1,77 @@
# SPDX-FileCopyrightText: 2025 Blender Studio Tools Authors
#
# SPDX-License-Identifier: GPL-3.0-or-later
from bpy.props import BoolProperty, StringProperty
from bpy.types import Operator
from ..threaded.background_process import Processes
class SVN_OT_custom_tooltip(Operator):
"""Tooltip"""
bl_idname = "svn.custom_tooltip"
bl_label = ""
bl_description = " "
bl_options = {'INTERNAL'}
tooltip: StringProperty(
name="Tooltip",
description="Tooltip that is displayed when mouse hovering this operator"
)
copy_on_click: BoolProperty(
name="Copy on Click",
description="If True, the tooltip will be copied to the clipboard when the operator is clicked",
default=False
)
@classmethod
def description(cls, context, properties):
tooltip = properties.tooltip
if properties.copy_on_click:
tooltip = "Copy to clipboard: " + properties.tooltip
return tooltip
def execute(self, context):
if self.copy_on_click:
context.window_manager.clipboard = self.tooltip
self.report({'INFO'}, "Copied to Clipboard: " + self.tooltip)
return {'FINISHED'}
class SVN_OT_clear_error(Operator):
bl_idname = "svn.clear_error"
bl_label = "Error:"
bl_description = ""
bl_options = {'INTERNAL'}
process_id: StringProperty()
@classmethod
def description(cls, context, properties):
process = Processes.get(properties.process_id)
if not process:
return "Process doesn't exist: " + properties.process_id
return process.error_description + "\n\n" + process.error + "\n\n Click to clear the error and copy it to your clipboard"
def execute(self, context):
process = Processes.get(self.process_id)
if not process:
self.report({'WARNING'}, f'Process not found: "{self.process_id}"')
return {'FINISHED'}
context.window_manager.clipboard = process.error_description + "\n\n" + process.error
if process.repeat_delay > 0:
process.start()
else:
process.error = ""
process.output = ""
self.report({'INFO'}, "Copied error to Clipboard.")
return {'FINISHED'}
registry = [
SVN_OT_custom_tooltip,
SVN_OT_clear_error
]
+190
View File
@@ -0,0 +1,190 @@
# SPDX-FileCopyrightText: 2021 Blender Studio Tools Authors
#
# SPDX-License-Identifier: GPL-3.0-or-later
from typing import Optional, Any, Set, Tuple, List
import platform
import bpy
from bpy.props import IntProperty, CollectionProperty, BoolProperty, EnumProperty
from bpy.types import AddonPreferences
from .ui.ui_repo_list import draw_checkout, draw_repo_list
from .repository import SVN_repository
from .svn_info import get_svn_info
import json
from pathlib import Path
from .threaded.background_process import Processes
class SVN_addon_preferences(AddonPreferences):
bl_idname = __package__
is_svn_installed: BoolProperty(
name="Is SVN Installed",
description="Whether the `svn` command works at all in the user's command line. If not, user needs to install SVN",
default=False
)
repositories: CollectionProperty(type=SVN_repository)
def init_repo_list(self):
# If we have any repository entries, make sure at least one is active.
self.sync_repo_info_file()
if self.active_repo_idx == -1 and len(self.repositories) > 0:
self.active_repo_idx = 0
elif self.active_repo_idx > len(self.repositories)-1:
self.active_repo_idx = 0
else:
self.active_repo_idx = self.active_repo_idx
def init_repo(self, context, repo_path: Path or str):
"""Attempt to initialize a repository based on a directory.
This means executing `svn info` in the repo_path to get the URL and root dir.
If we already have an SVN_repository instance with that root dir, just return it.
Otherwise, initialize it by storing its directory, URL, and a display name, and then return it.
"""
root_dir, base_url = get_svn_info(repo_path)
if not root_dir:
return
existing_repo = self.repositories.get(root_dir)
if existing_repo:
if existing_repo.external_files_active_index > len(existing_repo.external_files):
existing_repo.external_files_active_index = 0
existing_repo.log_active_index = len(existing_repo.log)-1
existing_repo.reload_svn_log(context)
return existing_repo
repo = self.repositories.add()
repo.initialize(root_dir, base_url)
self.active_repo_idx = len(self.repositories)-1
return repo
checkout_mode: BoolProperty(
name="Checkout In Progress",
description="Internal flag to indicate that the user is currently trying to create a new checkout",
default=False
)
def update_active_repo_idx(self, context):
if len(self.repositories) == 0:
return
active_repo = self.active_repo
# Authenticate when switching repos.
if (
active_repo and
not active_repo.auth_failed and
active_repo.is_cred_entered
):
Processes.start('Redraw Viewport')
if active_repo.authenticated:
Processes.restart('Status')
else:
active_repo.authenticate()
else:
Processes.kill('Status')
active_repo_idx: IntProperty(
name="SVN Repositories",
options=set(),
update=update_active_repo_idx
)
@property
def active_repo(self) -> Optional[SVN_repository]:
if not self.is_svn_installed:
return
if 0 <= self.active_repo_idx <= len(self.repositories)-1:
return self.repositories[self.active_repo_idx]
debug_mode: BoolProperty(
name="Debug Mode",
description="Enable some debug UI",
default=False
)
@property
def is_busy(self):
return Processes.is_running('Commit', 'Update')
loading: BoolProperty(
name="Loading",
description="Disable the credential update callbacks while loading repo data to avoid infinite loops",
default=False
)
def save_repo_info_to_file(self):
saved_props = {'url', 'directory', 'name',
'username', 'password', 'display_name'}
repo_data = {}
for repo in self.repositories:
directory = repo.get('directory', '')
repo_data[directory] = {
key: value for key, value in repo.items() if key in saved_props}
filepath = Path(bpy.utils.user_resource('CONFIG')) / \
Path("blender_svn.txt")
with open(filepath, "w") as f:
json.dump(repo_data, f, indent=4)
def load_repo_info_from_file(self):
self.loading = True
try:
filepath = Path(bpy.utils.user_resource(
'CONFIG')) / Path("blender_svn.txt")
if not filepath.exists():
return
with open(filepath, "r") as f:
repo_data = json.load(f)
for directory, repo_data in repo_data.items():
repo = self.repositories.get(directory)
if not repo:
repo = self.repositories.add()
repo.directory = directory
for key, value in repo_data.items():
setattr(repo, key, value)
finally:
self.loading = False
def sync_repo_info_file(self):
self.load_repo_info_from_file()
self.save_repo_info_to_file()
def draw(self, context):
if not self.is_svn_installed:
draw_prefs_no_svn(self, context)
return
if self.checkout_mode:
draw_checkout(self, context)
else:
draw_repo_list(self, context)
def draw_prefs_no_svn(self, context):
terminal, url = "terminal", "https://subversion.apache.org/packages.html"
system = platform.system()
if system == "Windows":
terminal = "command line (cmd.exe)"
url = "https://subversion.apache.org/packages.html#windows"
elif system == "Darwin":
terminal = "Mac terminal"
url = "https://subversion.apache.org/packages.html#osx"
layout = self.layout
col = layout.column()
col.alert=True
col.label(text="Please ensure that Subversion (aka. SVN) is installed on your system.")
col.label(text=f"Typing `svn` into the {terminal} should yield a result.")
layout.operator("wm.url_open", icon='URL', text='Open Subversion Distribution Page').url=url
registry = [
SVN_addon_preferences
]
+52
View File
@@ -0,0 +1,52 @@
# SPDX-FileCopyrightText: 2021 Blender Studio Tools Authors
#
# SPDX-License-Identifier: GPL-3.0-or-later
from .util import get_addon_prefs
from bpy.props import StringProperty, PointerProperty, BoolProperty
from bpy.types import PropertyGroup
import bpy
from typing import Optional
from . import wheels
# This will load the dateutil and BAT wheel files.
wheels.preload_dependencies()
class SVN_scene_properties(PropertyGroup):
"""Subversion properties to match this scene to a repo in the UserPrefs"""
svn_url: StringProperty(
name="Remote URL",
default="",
description="URL of the remote SVN repository of the current file, if any. Used to match to the SVN data stored in the user preferences",
)
svn_directory: StringProperty(
name="Root Directory",
default="",
subtype="DIR_PATH",
description="Absolute directory path of the SVN repository's root in the file system",
)
file_is_outdated: BoolProperty(
name="File Is Outdated",
description="Set to True when downloading a newer version of this file without reloading it, so that the warning in the UI can persist. This won't work in some cases involving multiple running Blender instances",
default=False
)
def get_repo(self, context) -> Optional['SVN_repository']:
"""Return the active repository."""
prefs = get_addon_prefs(context)
return prefs.active_repo
registry = [
SVN_scene_properties,
]
def register() -> None:
# Scene Properties.
bpy.types.Scene.svn = PointerProperty(type=SVN_scene_properties)
def unregister() -> None:
del bpy.types.Scene.svn
+606
View File
@@ -0,0 +1,606 @@
# SPDX-FileCopyrightText: 2023 Blender Studio Tools Authors
#
# SPDX-License-Identifier: GPL-3.0-or-later
from typing import Optional,Tuple
from pathlib import Path
import bpy
from bpy.types import PropertyGroup
from bpy.props import (
StringProperty,
BoolProperty,
CollectionProperty,
IntProperty,
EnumProperty,
FloatProperty,
)
from .threaded import svn_log
from .threaded.background_process import Processes
from .operators.svn_commit import SVN_commit_line
from .svn_info import get_svn_info
from .util import get_addon_prefs
from . import constants
class SVN_file(PropertyGroup):
"""Property Group that can represent a version of a File in an SVN repository."""
name: StringProperty(
name="File Name",
options=set()
)
@property
def svn_path(self):
return self.name
@svn_path.setter
def svn_path(self, value):
self.name = value
@property
def file_name(self):
return Path(self.svn_path).name
absolute_path: StringProperty(
name="Absolute Path",
description="Absolute filepath",
options=set()
)
status: EnumProperty(
name="Status",
description="SVN Status of the file in the local repository (aka working copy)",
items=constants.ENUM_SVN_STATUS,
default="normal",
options=set()
)
repos_status: EnumProperty(
name="Remote's Status",
description="SVN Status of the file in the remote repository (periodically updated)",
items=constants.ENUM_SVN_STATUS,
default="none",
options=set()
)
@property
def will_conflict(self):
return self.status != 'normal' and self.repos_status != 'none'
status_prediction_type: EnumProperty(
name="Status Predicted By Process",
items=[
("NONE", "None", "File status is not predicted, but actual."),
("SVN_UP", "Update", "File status is predicted by `svn up`. Status is protected until process is finished."),
("SVN_COMMIT", "Commit",
"File status is predicted by `svn commit`. Status is protected until process is finished."),
("SKIP_ONCE", "Skip Once", "File status is predicted by a working-copy svn file operation, like Revert. Next status update should be ignored, and this enum should be set to SKIPPED_ONCE."),
("SKIPPED_ONCE", "Skipped Once", "File status update was skipped. Next status update can be considered accurate, and this flag can be reset to NONE. Until then, operations on this file should remain disabled."),
],
description="Internal flag that notes what process set a predicted status on this file. Should be empty string when the status is not predicted but confirmed. When svn commit/update predicts a status, that status should not be overwritten until the process is finished. With instantaneous processes, a single status update should be ignored since it may be outdated",
options=set()
)
include_in_commit: BoolProperty(
name="Commit",
description="Whether this file should be included in the commit or not",
default=False,
options=set()
)
@property
def is_outdated(self):
return self.repos_status == 'modified' and self.status == 'normal'
@property
def is_dir(self):
if self.exists:
return Path(self.absolute_path).is_dir()
else:
# This file may not exist locally yet, but it could still exist on the SVN,
# and in this case we still want to provide a guess as to whether it's a folder or not.
return "." not in Path(self.absolute_path).name
revision: IntProperty(
name="Revision",
description="Revision number",
options=set()
)
@property
def exists(self) -> bool:
return Path(self.absolute_path).exists()
@property
def status_icon(self) -> str:
return constants.SVN_STATUS_DATA[self.status][0]
@property
def status_name(self) -> str:
if self.status == 'none':
return 'Outdated'
return self.status.title()
@property
def file_icon(self) -> str:
if self.is_dir:
return 'FILE_FOLDER'
extension = Path(self.svn_path).suffix
if extension in ['.abc']:
return 'FILE_CACHE'
elif 'blend' in extension:
return 'FILE_BLEND'
elif extension in [
'.tga',
'.bmp',
'.tif',
'.tiff',
'.tga',
'.png',
'.dds',
'.jpg',
'.exr',
'.hdr',
]:
return 'TEXTURE'
elif extension in ['.psd', '.kra']:
return 'IMAGE_DATA'
elif extension in ['.mp4', '.mov']:
return 'SEQUENCE'
elif extension in ['.mp3', '.ogg', '.wav']:
return 'SPEAKER'
return 'QUESTION'
@property
def has_default_status(self):
return self.status == 'normal' and self.repos_status == 'none' and self.status_prediction_type == 'NONE'
show_in_filelist: BoolProperty(
name="Show In File List",
description="Flag indicating whether this file should be drawn in the file list. This flag is updated for every file whenever the file search string is modified. If we did this filtering during drawing time, it is painfully slow",
default=False
)
def get_file_size(self):
num = self.file_size_KiB
for unit in ("KiB", "MiB", "GiB", "TiB", "PiB", "EiB"):
if num < 1024:
return f"{num:3.1f} {unit}"
num /= 1024.0
return f"{num:.1f} YiB"
def update_file_size(self, _context):
self.file_size = self.get_file_size()
file_size_KiB: FloatProperty(description="One KibiByte (KiB) is 1024 bytes", update=update_file_size)
file_size: StringProperty(description="File size for displaying in the UI")
class SVN_log(PropertyGroup):
"""Property Group that can represent an SVN log entry."""
revision_number: IntProperty(
name="Revision Number",
description="Revision number of the current .blend file",
)
revision_date: StringProperty(
name="Revision Date",
description="Date when the current revision was committed",
)
revision_date_simple: StringProperty(
name="Revision Date",
description="Date when the current revision was committed",
)
revision_author: StringProperty(
name="Revision Author",
description="SVN username of the revision author",
)
commit_message: StringProperty(
name="Commit Message",
description="Commit message written by the commit author to describe the changes in this revision",
)
changed_files: CollectionProperty(
type=SVN_file,
name="Changed Files",
description="List of file entries that were affected by this revision. Note that these are NOT pointers to the actual file entries stored in repository.external_files. These are copies, merely serving to store a file path",
)
def changes_file(self, file: SVN_file) -> bool:
"""Return whether the given file is among this log entry's changed files list."""
for affected_file in self.changed_files:
if affected_file.svn_path == "/"+file.svn_path:
return True
return False
text_to_search: StringProperty(
name="Text to Search",
description="Text to be used by the search filter. This should be set by calling set_search_string() when the log entry is created, and then never touched again",
)
def set_search_string(self):
rev = "r"+str(self.revision_number)
auth = self.revision_author
files = " ".join([f.svn_path for f in self.changed_files])
msg = self.commit_message
date = self.revision_date_simple
self.text_to_search = " ".join([rev, auth, files, msg, date]).lower()
# Cached variables; Things that update when active file or search filter changes,
# so that they don't have to be re-calculated on each re-draw of the log UI.
matches_filter: BoolProperty(
name="Matches Filter",
description="Whether the log entry matches the currently typed in search filter. This is cached, and should be re-calculated ONLY whenever the search filter changes",
default=True,
)
affects_active_file: BoolProperty(
name="Affects Active File",
description="Flag set whenever the active file index updates. Used to accelerate drawing performance by moving filtering logic from the drawing code to update callbacks and flags",
default=False
)
class SVN_repository(PropertyGroup):
### Basic SVN Info. ###
@property
def name(self):
return self.directory
def update_repo_info_file(self, context):
get_addon_prefs(context).save_repo_info_to_file()
display_name: StringProperty(
name="Display Name",
description="Display name of this SVN repository",
update=update_repo_info_file
)
url: StringProperty(
name="URL",
description="URL of the remote repository",
)
def update_directory(self, context):
self.name = self.directory
root_dir, base_url = get_svn_info(self.directory)
if root_dir and base_url:
self.initialize(root_dir, base_url)
directory: StringProperty(
name="Root Directory",
default="",
subtype="DIR_PATH",
description="Absolute directory path of the SVN repository's root in the file system",
update=update_directory
)
@property
def dir_exists(self):
dir_path = Path(self.directory)
return dir_path.exists() and dir_path.is_dir()
@property
def is_valid_svn(self):
dir_path = Path(self.directory)
# TODO: This property is checked pretty often, so we run `svn info` pretty often. Might not be a big deal, but maybe it's a bit overkill?
root_dir, base_url = get_svn_info(self.directory)
return (
dir_path.exists() and
dir_path.is_dir() and
root_dir and base_url and
root_dir == self.directory and
base_url == self.url
)
def initialize(self, directory: str, url: str, display_name="", username="", password=""):
self.url = url
if username:
self.username = username
if password:
self.password = password
if self.directory != directory:
# Don't set this if it's already set, to avoid infinite recursion
# via the update callback.
self.directory = directory
if display_name:
self.display_name = display_name
else:
self.display_name = Path(directory).name
return self
### Credentials. ###
def update_cred(self, context):
if not (self.username and self.password):
# Only try to authenticate if BOTH username AND pw are entered.
self.authenticated = False
return
if get_addon_prefs(context).loading:
return
self.authenticate()
self.update_repo_info_file(context)
def authenticate(self):
self.auth_failed = False
if self.is_valid_svn and self.is_cred_entered:
Processes.start('Authenticate')
# Trigger the file list filtering.
self.file_search_filter = self.file_search_filter
username: StringProperty(
name="Username",
description="User name used for authentication with this SVN repository",
update=update_cred
)
password: StringProperty(
name="Password",
description="Password used for authentication with this SVN repository. This password is stored in your Blender user preferences as plain text. Somebody with access to your user preferences will be able to read your password",
subtype='PASSWORD',
update=update_cred
)
@property
def is_cred_entered(self) -> bool:
"""Check if there's a username and password entered at all."""
return bool(self.username and self.password)
authenticated: BoolProperty(
name="Authenticated",
description="Internal flag to mark whether the last entered credentials were confirmed by the repo as correct credentials",
default=False
)
auth_failed: BoolProperty(
name="Authentication Failed",
description="Internal flag to mark whether the last entered credentials were rejected by the repo",
default=False
)
### SVN Commit Message. ###
commit_lines: CollectionProperty(type=SVN_commit_line)
@property
def commit_message(self):
return "\n".join([l.line for l in self.commit_lines]).strip()
@commit_message.setter
def commit_message(self, msg: str):
self.commit_lines.clear()
for line in msg.split("\n"):
line_entry = self.commit_lines.add()
line_entry.line = line
while len(self.commit_lines) < 3:
self.commit_lines.add()
### SVN Log / Revision History. ###
log: CollectionProperty(type=SVN_log)
log_active_index: IntProperty(
name="SVN Log",
options=set()
)
reload_svn_log = svn_log.reload_svn_log
@property
def log_file_path(self) -> Path:
return Path(self.directory+"/.svn/svn.log")
@property
def active_log(self):
try:
return self.log[self.log_active_index]
except IndexError:
return None
def get_log_by_revision(self, revision: int) -> Tuple[int, SVN_log]:
for i, log in enumerate(self.log):
if log.revision_number == revision:
return i, log
def get_latest_revision_of_file(self, svn_path: str) -> int:
"""Return the revision number of the last log entry that affects the given file."""
svn_path = str(svn_path)
for log in reversed(self.log):
for changed_file in log.changed_files:
if changed_file.svn_path == "/"+str(svn_path):
return log.revision_number
return 0
def is_file_outdated(self, file: SVN_file) -> bool:
"""A file may have the 'modified' state while also being outdated.
In this case SVN is of no use, we need to detect and handle this case
by ourselves.
"""
latest = self.get_latest_revision_of_file(file.svn_path)
current = file.revision
return latest > current
def get_file_abspath(self, file: SVN_file) -> Path:
"""Return the absolute path of an SVN file if it were in this repo."""
return Path(self.directory) / Path(file.svn_path)
### SVN File List. ###
external_files: CollectionProperty(type=SVN_file)
def remove_file_entry(self, file_entry: SVN_file):
"""Remove a file entry from the file list, based on its filepath."""
for i, f in enumerate(self.external_files):
if f == file_entry:
self.external_files.remove(i)
if i <= self.external_files_active_index:
self.external_files_active_index -= 1
return
def absolute_to_svn_path(self, absolute_path: Path) -> Path:
if type(absolute_path) == str:
absolute_path = Path(absolute_path)
svn_dir = Path(self.directory)
try:
return absolute_path.relative_to(svn_dir)
except ValueError:
return None
def svn_to_absolute_path(self, svn_path: Path) -> Path:
if type(svn_path) == str:
svn_path = Path(svn_path)
svn_dir = Path(self.directory)
return svn_dir / svn_path
def get_file_by_absolute_path(self, abs_path: str or Path) -> Optional[SVN_file]:
rel_path = str(self.absolute_to_svn_path(abs_path))
if rel_path:
return self.external_files.get(rel_path)
def get_index_of_file(self, file_entry) -> Optional[int]:
for i, file in enumerate(self.external_files):
if file == file_entry:
return i
def force_update_ui_caches(self, context):
"""Update UI caches even if the active file index hasn't changed.
This is used when loading a file.
"""
self.prev_external_files_active_index = -1
self.update_ui_caches(context)
def update_ui_caches(self, context):
"""When user clicks on a different file, the latest log entry of that file
should become the active log entry.
NOTE: Try to only trigger this on explicit user actions!
"""
if self.external_files_active_index == self.prev_external_files_active_index:
return
self.prev_external_files_active_index = self.external_files_active_index
if not self.active_file:
return
latest_rev = self.get_latest_revision_of_file(
self.active_file.svn_path)
# SVN Revisions are not 0-indexed, so we need to subtract 1.
self.log_active_index = latest_rev-1
space = context.space_data
if space and space.type == 'FILE_BROWSER':
space.params.directory = Path(self.active_file.absolute_path).parent.as_posix().encode()
space.params.filename = self.active_file.file_name.encode()
space.deselect_all()
# Set the active file in the file browser to whatever was selected
# in the SVN Files panel.
space.activate_file_by_relative_path( # This doesn't actually work, due to what I assume is a bug.
relative_path=self.active_file.file_name)
Processes.start('Activate File') # This is my work-around.
# Set the filter flag of the log entries based on whether they affect the active file or not.
self.log.foreach_set(
'affects_active_file',
[log_entry.changes_file(self.active_file)
for log_entry in self.log]
)
prev_external_files_active_index: IntProperty(
name="Previous Active Index",
description="Internal value to avoid triggering the update callback unnecessarily",
options=set()
)
external_files_active_index: IntProperty(
name="File List",
description="Files tracked by SVN",
update=update_ui_caches,
options=set(),
)
@property
def active_file(self) -> SVN_file:
if len(self.external_files) == 0:
return
return self.external_files[self.external_files_active_index]
def is_filebrowser_directory_in_repo(self, context) -> bool:
assert context.space_data.type == 'FILE_BROWSER', "This function needs a File Browser context."
params = context.space_data.params
abs_path = Path(params.directory.decode())
if not abs_path.exists():
return False
return Path(self.directory) in [abs_path] + list(abs_path.parents)
def get_filebrowser_active_file(self, context) -> SVN_file:
assert context.space_data.type == 'FILE_BROWSER', "This function needs a File Browser context."
params = context.space_data.params
abs_path = Path(params.directory.decode()) / Path(params.filename)
if not abs_path.exists():
return
if Path(self.directory) not in abs_path.parents:
return False
svn_path = self.absolute_to_svn_path(abs_path)
svn_file = self.external_files.get(svn_path)
return svn_file
@property
def current_blend_file(self) -> SVN_file:
return self.get_file_by_absolute_path(bpy.data.filepath)
### File List UIList filter properties ###
def refresh_ui_lists(self, context):
"""Refresh the file UI list based on filter settings.
Also triggers a refresh of the SVN UIList, through the update callback of
external_files_active_index."""
UI_LIST = bpy.types.UI_UL_list
if self.file_search_filter:
filter_list = UI_LIST.filter_items_by_name(
self.file_search_filter,
1,
self.external_files,
"name",
reverse=False
)
filter_list = [bool(val) for val in filter_list]
self.external_files.foreach_set('show_in_filelist', filter_list)
else:
for file in self.external_files:
if file == self.current_blend_file:
file.show_in_filelist = True
continue
file.show_in_filelist = not file.has_default_status
if len(self.external_files) == 0:
return
# Make sure the active file isn't now being filtered out.
# If it is, change the active file to the first visible one.
if self.active_file.show_in_filelist:
return
for i, file in enumerate(self.external_files):
if file.show_in_filelist:
self.external_files_active_index = i
return
file_search_filter: StringProperty(
name="Search Filter",
description="Only show entries that contain this string",
update=refresh_ui_lists
)
registry = [
SVN_file,
SVN_log,
SVN_repository,
]
+47
View File
@@ -0,0 +1,47 @@
# SPDX-FileCopyrightText: 2025 Blender Studio Tools Authors
#
# SPDX-License-Identifier: GPL-3.0-or-later
from typing import Tuple
from pathlib import Path
import subprocess
from .threaded.execute_subprocess import execute_command
def get_svn_info(path: Path or str) -> Tuple[str, str]:
"""Use the `svn info` command to get the root dir, the URL, and the relative URL."""
path = Path(path)
if not path.exists():
return "", ""
try:
dirpath_str = str(path.as_posix())
svn_info = execute_command(dirpath_str, ["svn", "info"])
except subprocess.CalledProcessError as e:
error_msg = e.stderr.decode()
if "is not a working copy" in error_msg:
return None, None
elif "E200009" in error_msg:
# If we're in a folder that wasn't yet added to the repo,
# try again one folder higher.
parent = path.parent
if parent == path:
return None, None
return get_svn_info(path.parent)
else:
raise e
lines = svn_info.split("\n")
root_dir = lines[1].split("Working Copy Root Path: ")[1]
# On Windows, for some reason the path has a \r character at the end,
# which breaks absolutely everything.
root_dir = root_dir.replace("\r", "")
full_url = lines[2].split("URL: ")[1]
relative_url = lines[3].split("Relative URL: ")[1][1:]
base_url = full_url
if len(relative_url) > 1:
base_url = full_url.replace(relative_url, "").strip()
return root_dir, base_url
@@ -0,0 +1,25 @@
# SPDX-FileCopyrightText: 2025 Blender Studio Tools Authors
#
# SPDX-License-Identifier: GPL-3.0-or-later
from . import (
background_process,
execute_subprocess,
svn_log,
svn_status,
filebrowser_activate_file,
update,
commit,
redraw_viewport
)
modules = [
background_process,
execute_subprocess,
svn_log,
svn_status,
filebrowser_activate_file,
update,
commit,
redraw_viewport
]
@@ -0,0 +1,277 @@
# SPDX-FileCopyrightText: 2022 Blender Studio Tools Authors
#
# SPDX-License-Identifier: GPL-3.0-or-later
import bpy
import threading
import subprocess
import random
from typing import List
from ..util import get_addon_prefs, redraw_viewport
from bpy.app.handlers import persistent
class BackgroundProcess:
"""
Base class that uses bpy.app.timers and threading to execute SVN commands
without freezing the interface.
The class should be extended and the process_output and acquire_output functions
implemented for each SVN command, then a single instance of that subclass should
be created, which can from that point on be used to manage that SVN process.
"""
name = "Unnamed Process"
# If the acquire_output() function doesn't write anything into
# self.output/self.error after this long, we will write a timeout
# error into self.error.
timeout = 10
# After a successful execution of process_output(), wait this many seconds
# before trying to acquire_output() again.
# If 0, repeated execution will stop.
repeat_delay = 15
# How many seconds to wait between checks for whether output has been acquired yet.
tick_delay = 1.0
# Time in seconds to delay the first execution by.
first_interval = 0
needs_authentication = False
# Displayed in the tooltip on mouse-hover in the error message when an error occurs.
error_description = "SVN Error:"
debug = False
def debug_print(self, msg: str):
if self.debug:
print(f"{self.name} (#{self.id}): {msg}")
def __init__(self):
self.thread = None
self.thread_start_time = 0
self.is_running = False
self.output = ""
self.error = ""
self.id = int(random.random() * 10000)
self.start()
def acquire_output_safe(self, context, prefs):
"""
Executed from a thread to avoid UI freezing during execute_svn_command().
Should save data into self.output and self.error.
Reading Blender data from this function is safe, but writing isn't!
"""
repo = context.scene.svn.get_repo(context)
if not repo.is_valid_svn:
self.stop()
try:
self.acquire_output(context, prefs)
except subprocess.CalledProcessError as error:
self.handle_error(context, error)
def acquire_output(self, context, prefs):
raise NotImplementedError
def handle_error(self, context, error):
self.output = ""
self.error = error.stderr.decode()
self.stop()
def process_output(self, context, prefs):
"""
Executed on main thread when there is any value in self.output or self.error.
It is safe to read and write Blender data from this function.
"""
raise NotImplementedError
def tick(self, context, prefs):
"""
Executed repeatedly while the timer is running, with tick_delay seconds between
each call.
Doesn't have to be used for anything. Can be useful for redrawing the UI.
Just be careful with this though.
"""
return
@persistent
def timer_function(self):
"""This is the actual function registered to bpy.app.timers."""
context = bpy.context
if not hasattr(context.scene, 'svn'):
# With some bad luck, this can happen when in the middle of opening a .blend file.
return 1
repo = context.scene.svn.get_repo(context)
if not repo:
self.debug_print("Shutdown: Not in repo.")
self.stop()
return
prefs = get_addon_prefs(context)
self.tick(context, prefs)
if not self.is_running:
# Since unregistering timers seems to be broken, let's allow setting
# is_running to False in order to shut down this process.
self.debug_print("Shutdown: is_running was set to False.")
return
if self.needs_authentication and not repo.authenticated:
self.debug_print("Shutdown: Authentication needed.")
self.stop()
return
if not self.thread or not self.thread.is_alive() and not self.output and not self.error:
self.thread = threading.Thread(
target=self.acquire_output_safe, args=(context, prefs))
self.thread.start()
self.debug_print("Started thread")
return self.tick_delay
elif self.error:
self.debug_print("Shutdown: There was an error.")
return
elif self.output:
self.debug_print("Processing output")
# self.debug_print("Processing output: \n" + str(self.output))
self.process_output(context, prefs)
self.output = ""
redraw_viewport()
if self.repeat_delay == 0:
self.debug_print("Shutdown: Output was processed, repeat_delay==0.")
self.stop()
return
self.debug_print(f"Processed output. Waiting {self.repeat_delay}")
return self.repeat_delay
elif not self.thread and not self.thread.is_alive() and self.repeat_delay == 0:
self.debug_print("Shutdown: Finished.\n")
self.stop()
return
self.debug_print(f"Tick delay: {self.tick_delay}")
return self.tick_delay
def get_ui_message(self, context) -> str:
"""Return a string that should be drawn in the UI for user feedback,
depending on the state of the process."""
if self.is_running:
return "Running..."
return ""
def restart(self):
self.stop()
self.start()
def start(self, persistent=True):
"""Start the process if it isn't running already, by registering its timer function."""
self.is_running = True
self.error = ""
self.output = ""
if not bpy.app.timers.is_registered(self.timer_function):
self.debug_print("Register timer")
bpy.app.timers.register(
self.timer_function,
first_interval=self.first_interval,
persistent=persistent
)
def stop(self):
"""Stop the process if it isn't running, by unregistering its timer function"""
self.debug_print("stop() function was called.")
self.is_running = False
if bpy.app.timers.is_registered(self.timer_function):
# This won't work if the timer has returned None at any point, as that
# will have already unregistered it.
# Actually, it doesn't seem to work anyways...
bpy.app.timers.unregister(self.timer_function)
self.debug_print("Force-unregistered.")
def get_recursive_subclasses(typ) -> List[type]:
ret = []
for subcl in typ.__subclasses__():
ret.append(subcl)
ret.extend(get_recursive_subclasses(subcl))
return ret
processes = {}
class ProcessManager:
@property
def processes(self):
# I tried to implement this thing as a Singleton that inherits from the `dict` class,
# I tried having the `processes` dict on the class level,
# I tried having it on the instance level,
# and it just refuses to work properly. I add an instance to the dictionary,
# I print it, I can see that it's there, I make sure it absolutely doesn't get removed,
# but when I try to access it from anywhere, it's just empty. My mind is boggled.
# Global dict works. :shrug:
global processes
return processes
@property
def running_processes(self) -> List[BackgroundProcess]:
return [p for p in self.processes.values() if p.is_running]
def is_running(self, *args: List[str]):
for proc_name in args:
if proc_name in self.processes:
return self.processes[proc_name].is_running
def get(self, proc_name: str):
return self.processes.get(proc_name)
def start(self, proc_name: str, **kwargs):
"""Start a process if it's stopped, or create it if it hasn't yet been instantiated."""
process = self.processes.get(proc_name, None)
if process:
process.start()
for key, value in kwargs.items():
setattr(process, key, value)
return
else:
for subcl in get_recursive_subclasses(BackgroundProcess):
if subcl.name == proc_name:
self.processes[subcl.name] = subcl(**kwargs)
return
raise Exception("SVN: Process name not found: ", proc_name)
def stop(self, proc_name: str):
"""Stop a process if it exists, otherwise do nothing."""
process = self.processes.get(proc_name, None)
if process:
process.stop()
def kill(self, proc_name: str):
"""Destroy a process entirely, such that it cannot be started again
without initializing a new instance."""
process = self.processes.get(proc_name, None)
if process:
process.stop()
del self.processes[proc_name]
def restart(self, proc_name: str):
"""Destroy a process, then start it again.
Useful to skip the repeat_delay timer of infinite processes like Status or Log."""
self.kill(proc_name)
self.start(proc_name)
# I named this variable with title-case, to indicate that it's a Singleton.
# There should only be one.
Processes = ProcessManager()
@@ -0,0 +1,70 @@
# SPDX-FileCopyrightText: 2023 Blender Studio Tools Authors
#
# SPDX-License-Identifier: GPL-3.0-or-later
from typing import List
from .background_process import Processes, BackgroundProcess
from .execute_subprocess import execute_svn_command
class BGP_SVN_Commit(BackgroundProcess):
name = "Commit"
needs_authentication = True
timeout = 5*60
repeat_delay = 0
debug = False
def __init__(self, commit_msg: str, file_list: List[str]):
super().__init__()
self.commit_msg = commit_msg
self.file_list = file_list
def acquire_output(self, context, prefs):
"""This function should be executed from a separate thread to avoid freezing
Blender's UI during execute_svn_command().
"""
if not self.commit_msg:
self.stop()
return
Processes.kill('Status')
sanitized_commit_msg = self.commit_msg.replace('"', "'")
command = ["svn", "commit", "-m",
f"{sanitized_commit_msg}"] + self.file_list
self.output = execute_svn_command(
context,
command,
use_cred=True
)
def handle_error(self, context, error):
print("Commit failed.")
Processes.start('Status')
super().handle_error(context, error)
def process_output(self, context, prefs):
print(self.output)
repo = context.scene.svn.get_repo(context)
for f in repo.external_files:
if f == repo.current_blend_file:
context.scene.svn.file_is_outdated = False
if f.status_prediction_type == 'SVN_COMMIT':
f.status_prediction_type = 'SKIP_ONCE'
Processes.start('Log')
Processes.start('Status')
repo.commit_message = ""
Processes.kill('Commit')
def get_ui_message(self, context) -> str:
"""Return a string that should be drawn in the UI for user feedback,
depending on the state of the process."""
if self.is_running:
plural = "s" if len(self.file_list) > 1 else ""
return f"Committing {len(self.file_list)} file{plural}..."
return ""
def stop(self):
super().stop()
@@ -0,0 +1,72 @@
# SPDX-FileCopyrightText: 2022 Blender Studio Tools Authors
#
# SPDX-License-Identifier: GPL-3.0-or-later
import subprocess
from typing import List
from ..util import get_addon_prefs
def get_credential_commands(context) -> List[str]:
repo = context.scene.svn.get_repo(context)
assert (
repo.is_cred_entered
), "No username or password entered for this repository. The UI shouldn't have allowed you to get into a state where you can press an SVN operation button without having your credentials entered, so this is a bug!"
return ["--username", f"{repo.username}", "--password", f"{repo.password}"]
def execute_command(path: str, command: str) -> str:
output_bytes = subprocess.check_output(
command,
shell=False,
cwd=path + "/",
stderr=subprocess.PIPE,
start_new_session=True,
)
return output_bytes.decode(encoding='utf-8', errors='replace')
def execute_svn_command(
context,
command: List[str],
*,
ignore_errors=False,
print_errors=True,
use_cred=False,
) -> str:
"""Execute an svn command in the root of the current svn repository.
So any file paths that are part of the command should be relative to the
SVN root.
"""
repo = context.scene.svn.get_repo(context)
if "svn" not in command:
command.insert(0, "svn")
if use_cred:
command += get_credential_commands(context)
command.append("--non-interactive")
command.append("--trust-server-cert")
prefs = get_addon_prefs(context)
if prefs.debug_mode:
print(" ".join(command))
try:
if repo.is_valid_svn:
return execute_command(repo.directory, command)
except subprocess.CalledProcessError as error:
if ignore_errors:
return ""
else:
err_msg = error.stderr.decode()
if print_errors:
print(f"Command returned error: {command}")
print(err_msg)
raise error
def check_svn_installed():
code, message = subprocess.getstatusoutput('svn')
return code != 127
@@ -0,0 +1,37 @@
# SPDX-FileCopyrightText: 2025 Blender Studio Tools Authors
#
# SPDX-License-Identifier: GPL-3.0-or-later
from .background_process import BackgroundProcess
class BGP_SVN_Activate_File(BackgroundProcess):
"""This crazy hacky method of activating the file with some delay is necessary
because Blender won't let us select the file immediately when changing the
directory - some time needs to pass before the files actually appear.
(This is visible with the naked eye as the file browser is empty for a
brief moment whenever params.dictionary is changed.)
"""
name = "Activate File"
needs_authentication = False
tick_delay = 0.1
debug = False
def acquire_output(self, context, prefs):
self.output = "dummy"
def process_output(self, context, prefs):
if not hasattr(context.scene, 'svn'):
return
repo = context.scene.svn.get_repo(context)
for area in context.screen.areas:
if area.type == 'FILE_BROWSER':
area.spaces.active.activate_file_by_relative_path(
relative_path=repo.active_file.file_name)
self.stop()
def get_ui_message(self, context):
return ""
@@ -0,0 +1,27 @@
# SPDX-FileCopyrightText: 2025 Blender Studio Tools Authors
#
# SPDX-License-Identifier: GPL-3.0-or-later
from .background_process import BackgroundProcess, Processes
from ..util import redraw_viewport
class BGP_SVN_Redraw_Viewport(BackgroundProcess):
name = "Redraw Viewport"
repeat_delay = 1
debug = False
tick_delay = 1
needs_authentication = False
def tick(self, context, prefs):
redraw_viewport()
def acquire_output(self, context, prefs):
return ""
def process_output(self, context, prefs):
return ""
def register():
Processes.start("Redraw Viewport")
@@ -0,0 +1,190 @@
# SPDX-FileCopyrightText: 2022 Blender Studio Tools Authors
#
# SPDX-License-Identifier: GPL-3.0-or-later
from datetime import datetime
from pathlib import Path
import subprocess
from ..util import redraw_viewport
from .. import constants
from .execute_subprocess import execute_svn_command
from .background_process import BackgroundProcess
def reload_svn_log(self, context):
"""Read the svn.log file (written by this addon) into the log entry list."""
repo = self
repo.log.clear()
# Read file into lists of lines where each list is one log entry
filepath = self.log_file_path
if not filepath.exists():
# Nothing to read!
return
chunks = []
with open(filepath, 'r') as f:
next(f) # Skip the first line of dashes.
chunk = []
for line in f:
line = line.replace("\n", "")
if line == "-" * 72:
# Line of dashes indicates the log entry is over.
chunks.append(chunk)
chunk = []
continue
chunk.append(line)
previous_rev_number = 0
for chunk in chunks:
if not chunk[0]:
chunk.pop(0)
# Read the first line of the svn log containing revision number, author,
# date and commit message length.
r_number, r_author, r_date, r_msg_length = chunk[0].split(" | ")
r_number = int(r_number[1:])
if r_number != previous_rev_number+1:
# print(f"SVN: Warning: Revision order seems wrong at r{r_number}")
# TODO: Currently this can happen when multiple Blender instances are running and end up writing the same log entry to the .log file multiple times.
# This is not very ideal!
continue
previous_rev_number = r_number
r_msg_length = int(r_msg_length.split(" ")[0])
log_entry = repo.log.add()
log_entry.revision_number = r_number
log_entry.revision_author = r_author
log_entry.revision_date = r_date
log_entry.revision_date_simple = svn_date_simple(r_date).split(" ")[
0][5:]
# File change set is on line 3 until the commit message begins...
file_change_lines = chunk[2:-(r_msg_length+1)]
for line in file_change_lines:
line = line.strip()
status_char = line[0]
file_path = line[2:]
if ' (from ' in file_path:
# If the file was moved, let's just ignore that information for now.
# TODO: This can be improved later if neccessary.
file_path = file_path.split(" (from ")[0]
file_path = Path(file_path)
log_file_entry = log_entry.changed_files.add()
log_file_entry.svn_path = str(file_path.as_posix())
log_file_entry.revision = r_number
log_file_entry.status = constants.SVN_STATUS_CHAR_TO_NAME[status_char]
log_entry['commit_message'] = "\n".join(chunk[-r_msg_length:])
log_entry.set_search_string()
def write_to_svn_log_file_and_storage(context, data_str: str) -> int:
"""
Get all SVN Log entries from the remote repo in the background,
without freezing up the UI, by calling this function every 3 seconds.
These are then stored in a file, so each log entry only needs to be fetched
once per computer that runs the addon.
Return how many SVN log entries were contained in data_str.
"""
repo = context.scene.svn.get_repo(context)
log_file_path = repo.log_file_path
file_existed = False
if log_file_path.exists():
file_existed = True
repo.reload_svn_log(context)
num_entries = len(repo.log)
with open(log_file_path, 'a+') as f:
# Append to the file, create it if necessary.
if file_existed:
# We want to skip the first line of the svn log when continuing,
# to avoid duplicate dashed lines, which would also mess up our
# parsing logic.
data_str = data_str[73:] # 72 dashes and a newline
data_str = "\n" + data_str # TODO: This is untested on windows.
# On Windows, the `svn log` command outputs lines with all sorts of \r and \n shennanigans.
# TODO: For this reason, this should be implemented with the --xml arg.
data_str = data_str.replace("\r", "")
if data_str.endswith("\n"):
data_str = data_str[:-1]
f.write(data_str)
repo.reload_svn_log(context)
print(f"SVN Log now at r{repo.log[-1].revision_number}")
return len(repo.log) - num_entries
class BGP_SVN_Log(BackgroundProcess):
name = "Log"
needs_authentication = True
timeout = 10
repeat_delay = 3
debug = False
def acquire_output(self, context, prefs):
"""This function should be executed from a separate thread to avoid freezing
Blender's UI during execute_svn_command().
"""
repo = context.scene.svn.get_repo(context)
latest_log_rev = 0
if len(repo.log) > 0:
latest_log_rev = repo.log[-1].revision_number
self.debug_print("Acquire output...")
# We have no way to know if latest_log_rev+1 will exist or not, but we
# must check, and there is no safe way to check it, so let's just
# catch and handle the potential error.
try:
self.output = execute_svn_command(
context,
["svn", "log", "--verbose",
f"-r{latest_log_rev+1}:HEAD", "--limit", "10"],
print_errors=False,
use_cred=True
)
self.debug_print("Output: \n" + str(self.output))
except subprocess.CalledProcessError as error:
error_msg = error.stderr.decode()
if "No such revision" in error_msg:
print("SVN: Log is now fully up to date.")
self.stop()
else:
self.error = error_msg
def process_output(self, context, prefs):
num_logs = write_to_svn_log_file_and_storage(context, self.output)
if num_logs < 10:
self.stop()
def get_ui_message(self, context):
repo = context.scene.svn.get_repo(context)
if len(repo.log) > 0:
rev_no = repo.log[-1].revision_number
return f"Updating log. Current: r{rev_no}..."
def svn_date_to_datetime(datetime_str: str) -> datetime:
"""Convert a string from SVN's datetime format to a datetime object."""
date, time, _timezone, _day, _n_day, _mo, _y = datetime_str.split(" ")
return datetime.strptime(f"{date} {time}", '%Y-%m-%d %H:%M:%S')
def svn_date_simple(datetime_str: str) -> str:
"""Convert a string form SVN's datetime format to a simpler format."""
dt = svn_date_to_datetime(datetime_str)
month_name = dt.strftime("%b")
date_str = f"{dt.year}-{month_name}-{dt.day}"
time_str = f"{str(dt.hour).zfill(2)}:{str(dt.minute).zfill(2)}"
return date_str + " " + time_str
@@ -0,0 +1,395 @@
# SPDX-FileCopyrightText: 2022 Blender Studio Tools Authors
#
# SPDX-License-Identifier: GPL-3.0-or-later
from ..svn_info import get_svn_info
from ..util import get_addon_prefs
from .. import constants
from .execute_subprocess import execute_svn_command, check_svn_installed
from .background_process import BackgroundProcess, Processes
from bpy.types import Operator
from bpy.props import StringProperty
import bpy
import xmltodict
import time
from pathlib import Path
from typing import List, Dict, Union, Any, Set, Optional, Tuple
from .. import wheels
# This will load the xmltodict wheel file.
wheels.preload_dependencies()
class SVN_OT_explain_status(Operator):
bl_idname = "svn.explain_status"
bl_label = "" # Don't want the first line of the tooltip on mouse hover.
bl_description = "Show an explanation of this status, using a dynamic tooltip"
bl_options = {'INTERNAL'}
status: StringProperty(
description="Identifier of the status to show an explanation for"
)
file_rel_path: StringProperty(
description="Path of the file to select in the list when clicking this explanation, to act as if it was click-through-able"
)
@staticmethod
def get_explanation(status: str):
return constants.SVN_STATUS_DATA[status][1]
@classmethod
def description(cls, context, properties):
return cls.get_explanation(properties.status)
def draw(self, context):
self.layout.label(text=self.get_explanation(self.status))
def execute(self, context):
"""Set the index on click, to act as if this operator button was
click-through in the UIList."""
if not self.file_rel_path:
return {'FINISHED'}
repo = context.scene.svn.get_repo(context)
file_entry = repo.external_files.get(self.file_rel_path)
file_entry_idx = repo.get_index_of_file(file_entry)
if file_entry_idx:
repo.external_files_active_index = file_entry_idx
return {'FINISHED'}
@bpy.app.handlers.persistent
def ensure_svn_of_current_file(_scene=None):
"""When opening or saving a .blend file, it's possible that the new .blend
is part of an SVN repository. If this is the case, do the following:
- Check if this file's repository is already in our database
- If not, create it
- Switch to that repo
"""
context = bpy.context
prefs = get_addon_prefs(context)
prefs.is_svn_installed = check_svn_installed()
if not prefs.is_svn_installed:
return
scene_svn = context.scene.svn
old_active_repo = prefs.active_repo
prefs.init_repo_list()
# If the file is unsaved, nothing more to do.
if not bpy.data.filepath:
scene_svn.svn_url = ""
return
# If file is not in a repo, nothing more to do.
is_in_repo = set_scene_svn_info(context)
if not is_in_repo:
return
# If file is in an existing repo, we should switch over to that repo.
for i, existing_repo in enumerate(prefs.repositories):
if (
existing_repo.url == scene_svn.svn_url
and existing_repo.directory == scene_svn.svn_directory
and existing_repo != old_active_repo
):
prefs.active_repo_idx = i
else:
# If file is in a non-existing repo, initialize that repo.
prefs.init_repo(context, scene_svn.svn_directory)
context.scene.svn.get_repo(context).force_update_ui_caches(context)
def set_scene_svn_info(context) -> bool:
"""Check if the current .blend file is in an SVN repository.
If it is, use `svn info` to grab the SVN URL and directory and store them in the Scene.
The rest of the add-on will use this stored URL & Dir to find the corresponding
SVN repository data stored in the user preferences.
Returns whether initialization was successful or not.
"""
scene_svn = context.scene.svn
scene_svn.svn_directory = ""
scene_svn.svn_url = ""
blend_path = Path(bpy.data.filepath).parent
root_dir, base_url = get_svn_info(blend_path)
if not root_dir:
return False
scene_svn.svn_directory = root_dir
scene_svn.svn_url = base_url
return True
################################################################################
############## AUTOMATICALLY KEEPING FILE STATUSES UP TO DATE ##################
################################################################################
class BGP_SVN_Status(BackgroundProcess):
name = "Status"
needs_authentication = True
timeout = 10
repeat_delay = 15
debug = False
def __init__(self):
self.timestamp_last_update = 0
self.list_command_output = ""
super().__init__()
def acquire_output(self, context, prefs):
self.output = execute_svn_command(
context,
["svn", "status", "--show-updates", "--verbose", "--xml"],
use_cred=True,
)
# The list command includes file size info and also files of directories
# which have their Depth set to Empty, which is used for a partial check-out,
# which we also use for updating files and folders one-by-one instead of
# all-at-once, so we can provide more live feedback in the UI.
# NOTE: This one-by-one updating functionality conflicts with a potential
# future support for partial check-outs, so that would require storing user-intended
# partially checked out folders separately somewhere.
self.list_command_output = execute_svn_command(
context,
["svn", "list", "--recursive", "--xml"],
use_cred=True,
)
def process_output(self, context, prefs):
repo = context.scene.svn.get_repo(context)
update_file_list_svn_status(context, svn_status_xml_to_dict(self.output))
update_file_list_svn_list(context, self.list_command_output)
repo.refresh_ui_lists(context)
self.timestamp_last_update = time.time()
def get_ui_message(self, context):
time_since_last_update = time.time() - self.timestamp_last_update
time_delta = self.repeat_delay - time_since_last_update
if self.repeat_delay > time_delta > 0:
return f"Status update in {int(time_delta)}s."
return f"Updating repo status..."
class BGP_SVN_Authenticate(BGP_SVN_Status):
name = "Authenticate"
needs_authentication = False
timeout = 10
repeat_delay = 0
debug = False
def get_ui_message(self, context):
return "Authenticating..."
def acquire_output(self, context, prefs):
repo = context.scene.svn.get_repo(context)
if (
not repo
or not repo.is_valid_svn
or not repo.is_cred_entered
or repo.authenticated
):
return
super().acquire_output(context, prefs)
def handle_error(self, context, error):
super().handle_error(context, error)
repo = context.scene.svn.get_repo(context)
repo.authenticated = False
repo.auth_failed = True
def process_output(self, context, prefs):
repo = context.scene.svn.get_repo(context)
if not repo or not repo.is_cred_entered or repo.authenticated:
return
assert self.output
super().process_output(context, prefs)
repo.authenticated = True
repo.auth_failed = False
Processes.start('Status')
Processes.start('Log')
def update_file_list_svn_status(context, file_statuses: Dict[str, Tuple[str, str, int]]):
"""Update the file list based on data from get_svn_file_statuses().
(See timer_update_svn_status)"""
repo = context.scene.svn.get_repo(context)
svn_paths = []
new_files_on_repo = set()
for filepath_str, status_info in file_statuses.items():
svn_path = Path(filepath_str)
svn_path_str = str(filepath_str)
suffix = svn_path.suffix
if (
(suffix.startswith(".r") and suffix[2:].isdecimal())
or (suffix.startswith(".blend") and suffix[6:].isdecimal())
or suffix.endswith("blend@")
):
# Do not add certain file extensions, ever:
# .r### files are from SVN conflicts waiting to be resolved.
# .blend@ is the Blender filesave temp file.
# .blend### are Blender backup files.
continue
svn_paths.append(svn_path_str)
wc_status, repos_status, revision = status_info
file_entry = repo.external_files.get(svn_path_str)
entry_existed = True
if not file_entry:
entry_existed = False
file_entry = repo.external_files.add()
file_entry.svn_path = svn_path_str
if not file_entry.exists:
new_files_on_repo.add((file_entry.svn_path, repos_status))
if entry_existed and (
file_entry.repos_status == 'none' and repos_status != 'none'
):
new_files_on_repo.add((file_entry.svn_path, repos_status))
file_entry.revision = revision
file_entry.status = wc_status
file_entry.repos_status = repos_status
file_entry.status_prediction_type = 'NONE'
file_entry.absolute_path = str(repo.svn_to_absolute_path(svn_path))
if new_files_on_repo:
# File entry status has changed between local and repo.
file_strings = []
for svn_path, repos_status in new_files_on_repo:
status_char = constants.SVN_STATUS_NAME_TO_CHAR.get(repos_status, " ")
file_strings.append(f"{status_char} {svn_path}")
print(
"SVN: Detected file changes on remote:\n",
"\n".join(file_strings),
"\nUpdating log...\n",
)
Processes.start('Log')
# Remove file entries who no longer seem to have an SVN status.
# This can happen if an unversioned file was removed from the filesystem,
# Or sub-folders whose parent was Un-Added to the SVN.
for file_entry in repo.external_files[:]:
if file_entry.svn_path not in svn_paths:
repo.remove_file_entry(file_entry)
def svn_status_xml_to_dict(svn_status_str: str) -> Dict[str, Tuple[str, str, int]]:
svn_status_xml = xmltodict.parse(svn_status_str)
file_infos = svn_status_xml['status']['target']['entry']
# print(json.dumps(file_infos, indent=4))
file_statuses = {}
for file_info in file_infos:
filepath = file_info.get('@path')
assert filepath, f"Filepath was not found in an SVN status entry:\n{file_info}"
# Remote Repository status.
repos_status = "none"
if 'repos-status' in file_info:
repos_status_block = file_info.get('repos-status')
if repos_status_block:
repos_status = repos_status_block.get('@item', "none")
# _repo_props = repos_status_block.get('@props')
# Working Copy status.
wc_status_block = file_info.get('wc-status')
wc_status = wc_status_block.get('@item', 'normal')
# _revision = int(wc_status_block.get('@revision', 0))
# _props = wc_status_block['@props']
commit_revision = 0
if 'commit' in wc_status_block:
commit_block = wc_status_block['commit']
if commit_block:
commit_revision = int(commit_block.get('@revision', 0))
# _commit_author = commit_block.get('author')
# _commit_date = commit_block.get('date')
file_statuses[filepath] = (wc_status, repos_status, commit_revision)
return file_statuses
def update_file_list_svn_list(context, svn_list_str: str) -> Dict:
repo = context.scene.svn.get_repo(context)
try:
svn_list_xml = xmltodict.parse(svn_list_str)
except:
# This seems to fail with an "ExpatError" on Windows...?
return
file_infos = svn_list_xml['lists']['list']['entry']
for file_info in file_infos:
svn_path = file_info['name']
kind = file_info['@kind']
file_entry = repo.external_files.get(svn_path)
if not file_entry:
file_entry = repo.external_files.add()
file_entry.svn_path = svn_path
file_entry.absolute_path = str(repo.svn_to_absolute_path(svn_path))
if not file_entry.exists:
file_entry.status = 'none'
file_entry.repos_status = 'added'
file_entry.status_prediction_type = 'NONE'
if kind == 'file':
file_entry.file_size_KiB = float(file_info['size']) / 1024.0
@bpy.app.handlers.persistent
def mark_current_file_as_modified(_dummy1=None, _dummy2=None):
context = bpy.context
scene_svn = context.scene.svn
if not scene_svn.svn_directory:
return
repo = scene_svn.get_repo(context)
if not repo:
return
current_blend = repo.current_blend_file
if current_blend:
current_blend.status = 'modified'
current_blend.status_prediction_type = 'SKIP_ONCE'
################################################################################
############################# REGISTER #########################################
################################################################################
def delayed_init_svn(delay=1):
bpy.app.timers.register(ensure_svn_of_current_file, first_interval=delay)
def register():
bpy.app.handlers.load_post.append(ensure_svn_of_current_file)
bpy.app.handlers.save_post.append(ensure_svn_of_current_file)
bpy.app.handlers.save_post.append(mark_current_file_as_modified)
delayed_init_svn()
def unregister():
bpy.app.handlers.load_post.remove(ensure_svn_of_current_file)
bpy.app.handlers.save_post.remove(ensure_svn_of_current_file)
bpy.app.handlers.save_post.remove(mark_current_file_as_modified)
Processes.kill('Status')
registry = [SVN_OT_explain_status]
@@ -0,0 +1,93 @@
# SPDX-FileCopyrightText: 2023 Blender Studio Tools Authors
#
# SPDX-License-Identifier: GPL-3.0-or-later
from typing import List, Dict, Union, Any, Set, Optional, Tuple
from .execute_subprocess import execute_svn_command
from .background_process import BackgroundProcess, Processes
class BGP_SVN_Update(BackgroundProcess):
name = "Update"
needs_authentication = True
timeout = 5*60
repeat_delay = 0.01 # 0 means don't repeat
debug = False
def __init__(self, revision=0):
super().__init__()
self.revision = revision
self.message = "Updating..."
def set_predicted_file_status(self, file):
if self.revision != 0:
# File status prediction is not supported for reverting the entire
# repository. It would be complicated to implement, and not really useful.
return
file.status_prediction_type = "SVN_UP"
if file.repos_status == 'modified' and file.status == 'normal':
# Modified on remote, exists on local.
file.repos_status = 'none'
elif file.repos_status == 'added' and file.status == 'none':
# Added on remote, doesn't exist on local.
file.status = 'normal'
elif file.repos_status == 'deleted' and file.status == 'normal':
# Deleted on remote, exists on local.
# NOTE: File entry should just be deleted.
file.status = 'none'
file.repos_status = 'none'
else:
file.status = 'conflicted'
def acquire_output(self, context, prefs):
Processes.kill('Status')
repo = context.scene.svn.get_repo(context)
files = [
f
for f in repo.external_files
if f.repos_status != 'none' or f.status_prediction_type == 'SVN_UP'
]
dirs = [f for f in files if f.is_dir]
if dirs:
dirs.sort(key=lambda d: len(d.svn_path))
file = dirs[0]
self.message = "Creating folder: " + file.svn_path
elif files:
file = files[0]
self.message = f"Updating file: {file.svn_path} ({file.file_size})"
else:
print("SVN Update complete.")
self.stop()
return
print(self.message)
self.set_predicted_file_status(file)
command = ["svn", "up", file.svn_path, "--accept", "postpone", "--depth", "empty"]
if self.revision > 0:
command.insert(2, f"-r{self.revision}")
self.output = execute_svn_command(context, command, use_cred=True)
file.status_prediction_type = 'SKIP_ONCE'
file.repos_status = 'none' # Without this, it would keep updating the same file.
def handle_error(self, context, error):
Processes.start('Status')
super().handle_error(context, error)
def process_output(self, context, prefs):
return
def get_ui_message(self, context) -> str:
"""Return a string that should be drawn in the UI for user feedback,
depending on the state of the process."""
if self.is_running:
return self.message + "..."
return ""
def stop(self):
super().stop()
Processes.start('Log')
Processes.start('Status')
+23
View File
@@ -0,0 +1,23 @@
# SPDX-FileCopyrightText: 2025 Blender Studio Tools Authors
#
# SPDX-License-Identifier: GPL-3.0-or-later
from . import (
ui_file_list,
ui_sidebar,
ui_filebrowser,
ui_log,
ui_repo_list,
ui_outdated_warning,
ui_context_menus
)
modules = [
ui_file_list,
ui_sidebar,
ui_filebrowser,
ui_log,
ui_repo_list,
ui_outdated_warning,
ui_context_menus
]
@@ -0,0 +1,70 @@
# SPDX-FileCopyrightText: 2023 Blender Studio Tools Authors
#
# SPDX-License-Identifier: GPL-3.0-or-later
import bpy
from bpy.types import Context, UIList, Operator
from bpy.props import StringProperty, BoolProperty
from pathlib import Path
def check_context_match(context: Context, uilayout_type: str, bl_idname: str) -> bool:
"""For example, when right-clicking on a UIList, the uilayout_type will
be `ui_list` and the bl_idname is that of the UIList being right-clicked.
"""
uilayout = getattr(context, uilayout_type, None)
return uilayout and uilayout.bl_idname == bl_idname
def svn_file_list_context_menu(self: UIList, context: Context) -> None:
if not check_context_match(context, 'ui_list', 'SVN_UL_file_list'):
return
layout = self.layout
layout.separator()
repo = context.scene.svn.get_repo(context)
active_file = repo.active_file
file_abs_path = repo.get_file_abspath(active_file)
if active_file.name.endswith("blend"):
op = layout.operator("wm.open_mainfile",
text=f"Open {active_file.name}")
op.filepath = str(file_abs_path)
op.display_file_selector = False
op.load_ui = True
op = layout.operator("wm.open_mainfile",
text=f"Open {active_file.name} (Keep UI)")
op.filepath = str(file_abs_path)
op.display_file_selector = False
op.load_ui = False
else:
layout.operator("wm.path_open",
text=f"Open {active_file.name}").filepath = str(file_abs_path)
layout.operator("wm.path_open",
text=f"Open Containing Folder").filepath = Path(file_abs_path).parent.as_posix()
layout.separator()
def svn_log_list_context_menu(self: UIList, context: Context) -> None:
if not check_context_match(context, 'ui_list', 'SVN_UL_log'):
return
layout = self.layout
layout.separator()
repo = context.scene.svn.get_repo(context)
active_log = repo.active_log
layout.operator("svn.update_all",
text=f"Revert Repository To r{active_log.revision_number}").revision = active_log.revision_number
layout.separator()
def register():
bpy.types.UI_MT_list_item_context_menu.append(svn_file_list_context_menu)
bpy.types.UI_MT_list_item_context_menu.append(svn_log_list_context_menu)
def unregister():
bpy.types.UI_MT_list_item_context_menu.remove(svn_file_list_context_menu)
bpy.types.UI_MT_list_item_context_menu.remove(svn_log_list_context_menu)
@@ -0,0 +1,233 @@
# SPDX-FileCopyrightText: 2023 Blender Studio Tools Authors
#
# SPDX-License-Identifier: GPL-3.0-or-later
import bpy
from bpy.types import UIList
from bpy.props import BoolProperty
from .. import constants
from ..util import get_addon_prefs, dots
from ..threaded.background_process import Processes
class SVN_UL_file_list(UIList):
# Value that indicates that this item has passed the filter process successfully. See rna_ui.c.
UILST_FLT_ITEM = 1 << 30
show_file_paths: BoolProperty(
name="Show File Paths",
description="Show file paths relative to the SVN root, instead of just the file name"
)
def draw_item(self, context, layout, data, item, icon, active_data, active_propname):
# As long as there are any items, always draw the filters.
self.use_filter_show = True
if self.layout_type != 'DEFAULT':
raise NotImplemented
file_entry = item
prefs = get_addon_prefs(context)
main_row = layout.row()
split = main_row.split(factor=0.6)
filepath_ui = split.row()
split = split.split(factor=0.4)
status_ui = split.row(align=True)
ops_ui = split.row(align=True)
ops_ui.alignment = 'RIGHT'
ops_ui.enabled = file_entry.status_prediction_type == 'NONE' and not prefs.is_busy
if self.show_file_paths:
filepath_ui.prop(file_entry, 'name', text="",
emboss=False, icon=file_entry.file_icon)
else:
filepath_ui.label(text=file_entry.file_name, icon=file_entry.file_icon)
statuses = [file_entry.status]
# SVN operations
ops = []
if file_entry.status in ['missing', 'deleted']:
ops.append(ops_ui.operator(
'svn.restore_file', text="", icon='LOOP_BACK'))
if file_entry.status == 'missing':
ops.append(ops_ui.operator(
'svn.remove_file', text="", icon='TRASH'))
elif file_entry.status == 'added':
ops.append(ops_ui.operator(
'svn.unadd_file', text="", icon='REMOVE'))
elif file_entry.status == 'unversioned':
ops.append(ops_ui.operator('svn.add_file', text="", icon='ADD'))
ops.append(ops_ui.operator(
'svn.trash_file', text="", icon='TRASH'))
elif file_entry.status == 'modified':
ops.append(ops_ui.operator(
'svn.revert_file', text="", icon='LOOP_BACK'))
if file_entry.repos_status == 'modified':
# The file isn't actually `conflicted` yet, by SVN's definition,
# but it will be as soon as we try to commit or update.
# I think it's better to let the user know in advance.
statuses.append('conflicted')
# Updating the file will create an actual conflict.
ops.append(ops_ui.operator(
'svn.update_single', text="", icon='IMPORT'))
elif file_entry.status == 'conflicted':
ops.append(ops_ui.operator('svn.resolve_conflict',
text="", icon='TRACKING_CLEAR_FORWARDS'))
elif file_entry.status in ['incomplete', 'obstructed']:
ops.append(ops_ui.operator(
'svn.cleanup', text="", icon='BRUSH_DATA'))
elif file_entry.status == 'none':
if file_entry.repos_status == 'added':
# From user POV it makes a bit more sense to call a file that doesn't
# exist yet "added" instead of "outdated".
statuses.append('added')
ops.append(ops_ui.operator(
'svn.update_single', text="", icon='IMPORT'))
elif file_entry.status == 'normal' and file_entry.repos_status == 'modified':
# From user POV, this file is outdated, not 'normal'.
statuses = ['none']
ops.append(ops_ui.operator(
'svn.update_single', text="", icon='IMPORT'))
elif file_entry.status in ['normal', 'external', 'ignored']:
pass
else:
print("Unknown file status: ", file_entry.svn_path,
file_entry.status, file_entry.repos_status)
for op in ops:
if hasattr(op, 'file_rel_path'):
op.file_rel_path = file_entry.svn_path
# Populate the status icons.
for status in statuses:
icon = constants.SVN_STATUS_DATA[status][0]
explainer = status_ui.operator(
'svn.explain_status', text="", icon=icon, emboss=False)
explainer.status = status
explainer.file_rel_path = file_entry.svn_path
@classmethod
def cls_filter_items(cls, context, data, propname):
"""By moving all of this logic to a classmethod (and all the filter
properties to the addon preferences) we can find a visible entry
from other UI code, allowing us to avoid situations where the active
element becomes hidden."""
flt_neworder = []
list_items = getattr(data, propname)
flt_flags = [file.show_in_filelist *
cls.UILST_FLT_ITEM for file in list_items]
helper_funcs = bpy.types.UI_UL_list
# This list should ALWAYS be sorted alphabetically.
flt_neworder = helper_funcs.sort_items_by_name(list_items, "name")
repo = context.scene.svn.get_repo(context)
if not repo:
return flt_flags, flt_neworder
return flt_flags, flt_neworder
def filter_items(self, context, data, propname):
return type(self).cls_filter_items(context, data, propname)
def draw_filter(self, context, layout):
"""Custom filtering UI.
Toggles are stored in addon preferences, see cls_filter_items().
"""
main_row = layout.row()
row = main_row.row(align=True)
row.prop(self, 'show_file_paths', text="",
toggle=True, icon="FILE_FOLDER")
repo = context.scene.svn.get_repo(context)
if repo:
row.prop(repo, 'file_search_filter', text="")
def draw_process_info(context, layout):
prefs = get_addon_prefs(context)
process_message = ""
any_error = False
col = layout.column()
for process in Processes.processes.values():
if process.name not in {'Commit', 'Update', 'Log', 'Status', 'Authenticate'}:
continue
if process.error:
row = col.row()
row.alert = True
warning = row.operator(
'svn.clear_error', text=f"SVN {process.name}: Error Occurred. Hover to view", icon='ERROR')
warning.process_id = process.name
any_error = True
break
if process.is_running:
message = process.get_ui_message(context)
if message:
message = message.replace("...", dots())
process_message = f"SVN: {message}"
if not any_error and process_message:
col.label(text=process_message)
if prefs.debug_mode:
col.label(text="Processes: " +
", ".join([p.name for p in Processes.running_processes]))
def draw_file_list(context, layout):
prefs = get_addon_prefs(context)
repo = prefs.active_repo
if not repo:
return
if not repo.authenticated:
row = layout.row()
row.alert=True
row.label(text="Repository is not authenticated.", icon='ERROR')
return
main_col = layout.column()
main_row = main_col.row()
split = main_row.split(factor=0.6)
filepath_row = split.row()
filepath_row.label(text=" Filepath")
status_row = split.row()
status_row.label(text=" Status")
ops_row = main_row.row()
ops_row.alignment = 'RIGHT'
ops_row.label(text="Operations")
row = main_col.row()
row.template_list(
"SVN_UL_file_list",
"svn_file_list",
repo,
"external_files",
repo,
"external_files_active_index",
)
col = row.column()
col.separator()
col.operator("svn.commit", icon='EXPORT', text="")
col.operator("svn.update_all", icon='IMPORT', text="").revision = 0
col.separator()
col.operator("svn.cleanup", icon='BRUSH_DATA', text="")
registry = [
SVN_UL_file_list,
]
@@ -0,0 +1,59 @@
# SPDX-FileCopyrightText: 2022 Blender Studio Tools Authors
#
# SPDX-License-Identifier: GPL-3.0-or-later
from bpy.types import Panel
from bl_ui.space_filebrowser import FileBrowserPanel
from .ui_log import draw_svn_log, is_log_useful
from .ui_file_list import draw_file_list
from ..util import get_addon_prefs
class FILEBROWSER_PT_SVN_files(FileBrowserPanel, Panel):
bl_space_type = 'FILE_BROWSER'
bl_region_type = 'TOOLS'
bl_category = "Bookmarks"
bl_label = "SVN Files"
@classmethod
def poll(cls, context):
if not super().poll(context):
return False
prefs = get_addon_prefs(context)
return prefs.active_repo and prefs.active_repo.authenticated
def draw(self, context):
layout = self.layout
layout.use_property_split = True
layout.use_property_decorate = False
draw_file_list(context, layout)
class FILEBROWSER_PT_SVN_log(FileBrowserPanel, Panel):
bl_space_type = 'FILE_BROWSER'
bl_region_type = 'TOOLS'
bl_category = "Bookmarks"
bl_parent_id = "FILEBROWSER_PT_SVN_files"
bl_label = "Revision History"
@classmethod
def poll(cls, context):
if not super().poll(context):
return False
return is_log_useful(context)
def draw(self, context):
layout = self.layout
layout.use_property_split = True
layout.use_property_decorate = False
draw_svn_log(context, layout)
registry = [
FILEBROWSER_PT_SVN_files,
FILEBROWSER_PT_SVN_log
]
+279
View File
@@ -0,0 +1,279 @@
# SPDX-FileCopyrightText: 2023 Blender Studio Tools Authors
#
# SPDX-License-Identifier: GPL-3.0-or-later
from bpy.props import IntProperty, BoolProperty
from bpy.types import UIList, Panel, Operator
from ..util import get_addon_prefs
class SVN_UL_log(UIList):
show_all_logs: BoolProperty(
name='Show All Logs',
description='Show the complete SVN Log, instead of only entries that affected the currently selected file',
default=False
)
def draw_item(self, context, layout, data, item, icon, active_data, active_propname):
if self.layout_type != 'DEFAULT':
raise NotImplemented
svn = data
log_entry = item
num, auth, date, msg = layout_log_split(layout.row())
active_file = svn.active_file
num.label(text=str(log_entry.revision_number))
if item.revision_number == active_file.revision:
num.operator('svn.tooltip_log', text="", icon='LAYER_ACTIVE',
emboss=False).log_rev = log_entry.revision_number
elif log_entry.changes_file(active_file):
get_older = num.operator(
'svn.download_file_revision', text="", icon='IMPORT', emboss=False)
get_older.revision = log_entry.revision_number
get_older.file_rel_path = active_file.svn_path
auth.label(text=log_entry.revision_author)
date.label(text=log_entry.revision_date_simple)
commit_msg = log_entry.commit_message
commit_msg = commit_msg.split(
"\n")[0] if "\n" in commit_msg else commit_msg
commit_msg = commit_msg[:50] + \
"..." if len(commit_msg) > 52 else commit_msg
msg.alignment = 'LEFT'
msg.operator("svn.display_commit_message", text=commit_msg,
emboss=False).log_rev = log_entry.revision_number
def filter_items(self, context, data, propname):
"""Custom filtering functionality:
- Always sort by descending revision number
- Allow searching for various criteria
"""
svn = data
log_entries = getattr(data, propname)
# Start off with all entries flagged as visible.
flt_flags = [self.bitflag_filter_item] * len(log_entries)
# Always sort by descending revision number
flt_neworder = sorted(range(len(log_entries)),
key=lambda i: log_entries[i].revision_number)
flt_neworder.reverse()
if not self.show_all_logs:
flt_flags = [
log_entry.affects_active_file * self.bitflag_filter_item
for log_entry in log_entries
]
if self.filter_name:
# Filtering: Allow comma-separated keywords.
# ALL keywords must be found somewhere in the log entry for it to show up.
filter_words = [word.strip().lower()
for word in self.filter_name.split(",")]
for idx, log_entry in enumerate(log_entries):
for filter_word in filter_words:
if filter_word not in log_entry.text_to_search:
flt_flags[idx] = 0
break
return flt_flags, flt_neworder
def draw_filter(self, context, layout):
"""Custom filtering UI.
"""
main_row = layout.row()
main_row.prop(self, 'filter_name', text="")
main_row.prop(self, 'show_all_logs', text="",
toggle=True, icon='ALIGN_JUSTIFY')
def is_log_useful(context) -> bool:
"""Return whether the log has any useful info to display."""
prefs = get_addon_prefs(context)
repo = prefs.active_repo
if not repo or not repo.authenticated:
return False
if len(repo.log) == 0 or len(repo.external_files) == 0:
return False
active_file = repo.active_file
if active_file.status in ['unversioned', 'added']:
return False
any_visible = any([file.show_in_filelist for file in repo.external_files])
if not any_visible:
return False
return True
class VIEW3D_PT_svn_log(Panel):
"""Display the revision history of the selected file."""
bl_space_type = 'VIEW_3D'
bl_region_type = 'UI'
bl_category = 'SVN'
bl_label = 'Revision History'
bl_parent_id = "VIEW3D_PT_svn_files"
bl_options = {'DEFAULT_CLOSED'}
@classmethod
def poll(cls, context):
return is_log_useful(context)
def draw(self, context):
layout = self.layout
layout.use_property_split = True
layout.use_property_decorate = False
draw_svn_log(context, layout)
def layout_log_split(layout):
main = layout.split(factor=0.4)
num_and_auth = main.row()
date_and_msg = main.row()
num_and_auth_split = num_and_auth.split(factor=0.5)
num = num_and_auth_split.row()
auth = num_and_auth_split.row()
date_and_msg_split = date_and_msg.split(factor=0.3)
date = date_and_msg_split.row()
msg = date_and_msg_split.row()
return num, auth, date, msg
def draw_svn_log(context, layout):
num, auth, date, msg = layout_log_split(layout.row())
num.label(text="Rev. #")
auth.label(text="Author")
date.label(text="Date")
msg.label(text="Message")
prefs = get_addon_prefs(context)
repo = prefs.active_repo
layout.template_list(
"SVN_UL_log",
"svn_log",
repo,
"log",
repo,
"log_active_index",
)
active_log = repo.active_log
if not active_log:
return
layout.label(text="Revision Date: " + active_log.revision_date)
layout.label(
text=f"Files changed in revision `r{active_log.revision_number}`:")
col = layout.column(align=True)
row = col.row()
split = row.split(factor=0.80)
split.label(text=" Filepath")
row = split.row()
row.alignment = 'RIGHT'
row.label(text="Action")
for f in active_log.changed_files:
row = col.row()
split = row.split(factor=0.90)
split.prop(f, 'name', emboss=False, text="", icon=f.file_icon)
row = split.row()
row.alignment = 'RIGHT'
row.operator('svn.explain_status', text="",
icon=f.status_icon, emboss=False).status = f.status
def execute_tooltip_log(self, context):
"""Set the index on click, to act as if this operator button was
click-through in the UIList."""
repo = context.scene.svn.get_repo(context)
tup = repo.get_log_by_revision(self.log_rev)
if tup:
repo.log_active_index = tup[0]
return {'FINISHED'}
class SVN_OT_log_tooltip(Operator):
bl_idname = "svn.tooltip_log"
bl_label = "" # Don't want the first line of the tooltip on mouse hover.
# bl_description = "An operator to be drawn in the log list, that can display a dynamic tooltip"
bl_options = {'INTERNAL'}
log_rev: IntProperty(
description="Revision number of the log entry to show in the tooltip"
)
@classmethod
def description(cls, context, properties):
return "This is the currently checked out version of the file"
execute = execute_tooltip_log
class SVN_OT_log_show_commit_msg(Operator):
bl_idname = "svn.display_commit_message"
bl_label = "" # Don't want the first line of the tooltip on mouse hover.
# bl_description = "Show the currently active commit, using a dynamic tooltip"
bl_options = {'INTERNAL'}
log_rev: IntProperty(
description="Revision number of the log entry to show in the tooltip"
)
@classmethod
def description(cls, context, properties):
log_entry = context.scene.svn.get_repo(context).get_log_by_revision(properties.log_rev)[
1]
commit_msg = log_entry.commit_message
# Prettify the tooltips.
pretty_msg = ""
for line in commit_msg.split("\n"):
# Remove leading/trailing whitespace
line = line.strip()
# Add punctuation mark
if not (line.endswith(".") or line.endswith("!") or line.endswith("?")):
line = line + "."
# Split long lines into several
limit = 300
if len(line) > limit:
words = line.split(" ")
sub_lines = []
new_line = ""
for word in words:
if len(new_line) + len(word) < limit:
new_line += " "+word
else:
sub_lines.append(new_line)
new_line = word
else:
sub_lines.append(new_line)
line = "\n".join(sub_lines)
pretty_msg += "\n"+line
# Remove last period because Blender adds it.
if pretty_msg.endswith("."):
pretty_msg = pretty_msg[:-1]
return pretty_msg
execute = execute_tooltip_log
registry = [
VIEW3D_PT_svn_log,
SVN_UL_log,
SVN_OT_log_tooltip,
SVN_OT_log_show_commit_msg
]
@@ -0,0 +1,39 @@
# SPDX-FileCopyrightText: 2023 Blender Studio Tools Authors
#
# SPDX-License-Identifier: GPL-3.0-or-later
import bpy
def draw_outdated_file_warning(self, context):
repo = context.scene.svn.get_repo(context)
current_file = None
if not repo:
return
try:
current_file = repo.current_blend_file
except ValueError:
# This can happen if the svn_directory property wasn't updated yet (not enough time has passed since opening the file)
pass
if not current_file:
# If the current file is not in an SVN repository.
return
layout = self.layout
row = layout.row()
row.alert = True
if current_file.status == 'conflicted':
row.operator('svn.resolve_conflict',
text="SVN: This .blend file is conflicted.", icon='ERROR')
elif current_file.repos_status != 'none' or context.scene.svn.file_is_outdated:
op = row.operator('svn.revert_and_update_file', text="SVN: This .blend file may be outdated.", icon='ERROR')
op.file_rel_path = repo.current_blend_file.svn_path
def register():
bpy.types.TOPBAR_MT_editor_menus.append(draw_outdated_file_warning)
def unregister():
bpy.types.TOPBAR_MT_editor_menus.remove(draw_outdated_file_warning)
@@ -0,0 +1,276 @@
# SPDX-FileCopyrightText: 2023 Blender Studio Tools Authors
#
# SPDX-License-Identifier: GPL-3.0-or-later
import platform
from bpy.types import UIList, Operator, Menu
from bpy_extras.io_utils import ImportHelper
from ..util import get_addon_prefs
from .ui_log import draw_svn_log, is_log_useful
from .ui_file_list import draw_file_list, draw_process_info
from ..threaded.background_process import Processes
from pathlib import Path
class SVN_UL_repositories(UIList):
def draw_item(
self, context, layout, data, item, icon, active_data, active_propname
):
repo = item
row = layout.row()
row.label(text=repo.display_name)
if not repo.dir_exists:
row.alert = True
row.prop(repo, 'directory', text="")
class SVN_OT_repo_add(Operator, ImportHelper):
"""Add a repository to the list"""
bl_options = {'REGISTER', 'UNDO', 'INTERNAL'}
bl_idname = "svn.repo_add"
bl_label = "Add Repository"
def execute(self, context):
prefs = get_addon_prefs(context)
repos = prefs.repositories
path = Path(self.filepath)
if not path.exists():
# It's unlikely that a path that the user JUST BROWSED doesn't exist.
# So, this actually happens when the user leaves a filename in the
# file browser text box while trying to select the folder...
# Basically, Blender is dumb, and it will add that filename to the
# end of the browsed path. We need to discard that.
path = path.parent
if path.is_file():
# Maybe the user actually did select an existing file in the repo.
# We still want to discard the filename.
path = path.parent
existing_repos = repos[:]
try:
repo = prefs.init_repo(context, path)
except Exception as e:
self.report(
{'ERROR'},
"Failed to initialize repository. Ensure you have SVN installed, and that the selected directory is the root of a repository.",
)
print(e)
return {'CANCELLED'}
if not repo:
self.report({'ERROR'}, "Failed to initialize repository.")
return {'CANCELLED'}
if repo in existing_repos:
self.report({'INFO'}, "Repository already present.")
else:
self.report({'INFO'}, "Repository added.")
prefs.active_repo_idx = repos.find(repo.directory)
prefs.save_repo_info_to_file()
return {'FINISHED'}
class SVN_OT_repo_remove(Operator):
"""Remove a repository from the list"""
bl_options = {'REGISTER', 'UNDO', 'INTERNAL'}
bl_idname = "svn.repo_remove"
bl_label = "Remove Repository"
@classmethod
def poll(cls, context):
return len(get_addon_prefs(context).repositories) > 0
def execute(self, context):
prefs = get_addon_prefs(context)
active_index = prefs.active_repo_idx
repos = prefs.repositories
prefs.repositories.remove(prefs.active_repo_idx)
to_index = min(active_index, len(repos) - 1)
prefs.active_repo_idx = to_index
prefs.save_repo_info_to_file()
return {'FINISHED'}
class SVN_MT_add_repo(Menu):
bl_idname = "SVN_MT_add_repo"
bl_label = "Add Repo"
def draw(self, context):
layout = self.layout
layout.operator(
"svn.repo_add", text="Browse Existing Checkout", icon='FILE_FOLDER'
)
layout.operator(
"svn.checkout_initiate", text="Create New Checkout", icon='URL'
).create = True
def draw_repo_list(self, context) -> None:
layout = self.layout
auth_in_progress = False
auth_error = False
auth_proc = Processes.get('Authenticate')
if auth_proc:
auth_in_progress = auth_proc.is_running
auth_error = auth_proc.error
repo_col = layout.column()
split = repo_col.row().split()
split.row().label(text="SVN Repositories:")
# Secret debug toggle (invisible, to the right of the SVN Repositories label.)
row = split.row()
row.alignment = 'RIGHT'
row.prop(self, 'debug_mode', text="", icon='BLANK1', emboss=False)
repo_col.enabled = not auth_in_progress
list_row = repo_col.row()
col = list_row.column()
col.template_list(
"SVN_UL_repositories",
"svn_repo_list",
self,
"repositories",
self,
"active_repo_idx",
)
op_col = list_row.column()
op_col.menu('SVN_MT_add_repo', icon='ADD', text="")
op_col.operator('svn.repo_remove', icon='REMOVE', text="")
if len(self.repositories) == 0:
return
if self.active_repo_idx - 1 > len(self.repositories):
return
if not self.active_repo:
return
repo_col.prop(self.active_repo, 'display_name', icon='FILE_TEXT')
repo_col.prop(self.active_repo, 'url', icon='URL')
repo_col.prop(self.active_repo, 'username', icon='USER')
repo_col.prop(self.active_repo, 'password', icon='LOCKED')
draw_process_info(context, layout.row())
if not self.active_repo.dir_exists:
draw_repo_error(layout, "Repository not found on file system.")
return
if not self.active_repo.is_valid_svn:
draw_repo_error(layout, "Directory is not an SVN repository.")
split = layout.split(factor=0.24)
split.row()
split.row().operator(
"svn.checkout_initiate", text="Create New Checkout", icon='URL'
).create = False
return
if not self.active_repo.authenticated and not auth_in_progress and not auth_error:
draw_repo_error(layout, "Repository not authenticated. Enter your credentials.")
return
if len(self.repositories) > 0 and self.active_repo.authenticated:
layout.separator()
layout.label(text="SVN Files: ")
draw_file_list(context, layout)
if is_log_useful(context):
layout.separator()
layout.label(text="Revision History: ")
draw_svn_log(context, layout)
def draw_repo_error(layout, message):
split = layout.split(factor=0.24)
split.row()
col = split.column()
col.alert = True
col.label(text=message, icon='ERROR')
def draw_checkout(self, context):
def get_terminal_howto():
msg_windows = "If you don't, cancel this operation and toggle it using Window->Toggle System Console."
msg_linux = "If you don't, quit Blender and re-launch it from a terminal."
msg_mac = msg_linux
system = platform.system()
if system == "Windows":
return msg_windows
elif system == "Linux":
return msg_linux
elif system == "Darwin":
return msg_mac
layout = self.layout
col = layout.column()
col.alert = True
col.label(text="IMPORTANT! ", icon='ERROR')
col.label(text="Make sure you have Blender's terminal open!")
col.label(text=get_terminal_howto())
col.separator()
col.label(
text="Downloading a repository can take a long time, and the UI will be locked."
)
col.label(
text="Without a terminal, you won't be able to track the progress of the checkout."
)
col.separator()
col = layout.column()
col.label(
text="To interrupt the checkout, you can press Ctrl+C in the terminal.",
icon='INFO',
)
col.label(
text="You can resume it by re-running this operation, or with the SVN Update button.",
icon='INFO',
)
col.separator()
prefs = get_addon_prefs(context)
repo = prefs.repositories[-1]
col.prop(repo, 'directory')
for other_repo in prefs.repositories:
if other_repo == repo:
continue
if other_repo.directory == repo.directory:
row = col.row()
row.alert = True
row.label(
text="A repository at this filepath is already specified.", icon='ERROR'
)
break
col.prop(repo, 'display_name', text="Folder Name", icon='NEWFOLDER')
col.prop(repo, 'url', icon='URL')
for other_repo in prefs.repositories:
if other_repo == repo:
continue
if other_repo.url == repo.url:
sub = col.column()
sub.alert = True
sub.label(text="A repository with this URL is already specified.")
sub.label(
text="If you're sure you want to checkout another copy of the repo, feel free to proceed."
)
break
col.prop(repo, 'username', icon='USER')
col.prop(repo, 'password', icon='LOCKED')
op_row = layout.row()
op_row.operator('svn.checkout_finalize', text="Checkout", icon='CHECKMARK')
op_row.operator('svn.checkout_cancel', text="Cancel", icon="X")
registry = [SVN_UL_repositories, SVN_OT_repo_add, SVN_OT_repo_remove, SVN_MT_add_repo]
@@ -0,0 +1,63 @@
# SPDX-FileCopyrightText: 2022 Blender Studio Tools Authors
#
# SPDX-License-Identifier: GPL-3.0-or-later
from bpy.types import Panel
from .ui_file_list import draw_file_list, draw_process_info
class VIEW3D_PT_svn_credentials(Panel):
"""Prompt the user to enter their username and password for the remote repository of the current .blend file."""
bl_space_type = 'VIEW_3D'
bl_region_type = 'UI'
bl_category = 'SVN'
bl_label = 'SVN Credentials'
@classmethod
def poll(cls, context):
repo = context.scene.svn.get_repo(context)
return repo and not repo.authenticated
def draw(self, context):
layout = self.layout
layout.use_property_split = True
layout.use_property_decorate = False
col = layout.column(align=True)
repo = context.scene.svn.get_repo(context)
row = col.row()
row.prop(repo, 'display_name', text="Repo Name", icon='FILE_TEXT')
url = row.operator('svn.custom_tooltip', text="", icon='URL')
url.tooltip = repo.url
url.copy_on_click = True
col.prop(repo, 'username', icon='USER')
col.prop(repo, 'password', icon='UNLOCKED')
draw_process_info(context, layout)
class VIEW3D_PT_svn_files(Panel):
"""Display a list of files in the SVN repository of the current .blend file."""
bl_space_type = 'VIEW_3D'
bl_region_type = 'UI'
bl_category = 'SVN'
bl_label = 'SVN Files'
@classmethod
def poll(cls, context):
repo = context.scene.svn.get_repo(context)
return repo and repo.authenticated
def draw(self, context):
layout = self.layout
layout.use_property_split = True
layout.use_property_decorate = False
draw_process_info(context, layout)
draw_file_list(context, layout)
registry = [
VIEW3D_PT_svn_credentials,
VIEW3D_PT_svn_files,
]
+27
View File
@@ -0,0 +1,27 @@
# SPDX-FileCopyrightText: 2021 Blender Studio Tools Authors
#
# SPDX-License-Identifier: GPL-3.0-or-later
from time import time
import bpy
package_name = __package__
def get_addon_prefs(context):
return context.preferences.addons[__package__].preferences
def dots():
return "." * int((time() % 10) + 3)
def redraw_viewport(context=None) -> None:
"""This causes the sidebar UI to refresh without having to mouse-hover it."""
context = bpy.context
if not context:
return
for area in context.screen.areas:
if area.type in {'VIEW_3D', 'FILE_BROWSER'}:
area.tag_redraw()
@@ -0,0 +1,144 @@
# SPDX-FileCopyrightText: 2025 Blender Studio Tools Authors
#
# SPDX-License-Identifier: GPL-3.0-or-later
# NOTE: The original author of this file is Sybren Stüvel. This file is copied from the
# Flamenco project: https://developer.blender.org/diffusion/F/browse/main/addon/flamenco/wheels/__init__.py
"""External dependencies loader."""
import contextlib
from pathlib import Path
import sys
import logging
from types import ModuleType
from typing import Iterator
_my_dir = Path(__file__).parent
_log = logging.getLogger(__name__)
def load_wheel(module_name: str, fname_prefix: str) -> ModuleType:
"""Loads a wheel from 'fname_prefix*.whl', unless the named module can be imported.
This allows us to use system-installed packages before falling back to the shipped wheels.
This is useful for development, less so for deployment.
"""
try:
module = __import__(module_name)
except ImportError as ex:
_log.debug("Unable to import %s directly, will try wheel: %s", module_name, ex)
else:
_log.debug(
"Was able to load %s from %s, no need to load wheel %s",
module_name,
module.__file__,
fname_prefix,
)
assert isinstance(module, ModuleType)
return module
wheel = _wheel_filename(fname_prefix)
# Load the module from the wheel file. Keep a backup of sys.path so that it
# can be restored later. This should ensure that future import statements
# cannot find this wheel file, increasing the separation of dependencies of
# this add-on from other add-ons.
with _sys_path_mod_backup(wheel):
try:
module = __import__(module_name)
except ImportError as ex:
raise ImportError(
"Unable to load %r from %s: %s" % (module_name, wheel, ex)
) from None
_log.debug("Loaded %s from %s", module_name, module.__file__)
assert isinstance(module, ModuleType)
return module
def load_wheel_global(module_name: str, fname_prefix: str) -> ModuleType:
"""Loads a wheel from 'fname_prefix*.whl', unless the named module can be imported.
This allows us to use system-installed packages before falling back to the shipped wheels.
This is useful for development, less so for deployment.
"""
try:
module = __import__(module_name)
except ImportError as ex:
_log.debug("Unable to import %s directly, will try wheel: %s", module_name, ex)
else:
_log.debug(
"Was able to load %s from %s, no need to load wheel %s",
module_name,
module.__file__,
fname_prefix,
)
return module
wheel = _wheel_filename(fname_prefix)
wheel_filepath = str(wheel)
if wheel_filepath not in sys.path:
sys.path.insert(0, wheel_filepath)
try:
module = __import__(module_name)
except ImportError as ex:
raise ImportError(
"Unable to load %r from %s: %s" % (module_name, wheel, ex)
) from None
_log.debug("Globally loaded %s from %s", module_name, module.__file__)
return module
@contextlib.contextmanager
def _sys_path_mod_backup(wheel_file: Path) -> Iterator[None]:
old_syspath = sys.path[:]
try:
sys.path.insert(0, str(wheel_file))
yield
finally:
# Restore without assigning new instances. That way references held by
# other code will stay valid.
sys.path[:] = old_syspath
def _wheel_filename(fname_prefix: str) -> Path:
path_pattern = "%s*.whl" % fname_prefix
wheels: list[Path] = list(_my_dir.glob(path_pattern))
if not wheels:
raise RuntimeError("Unable to find wheel at %r" % path_pattern)
# If there are multiple wheels that match, load the last-modified one.
# Alphabetical sorting isn't going to cut it since BAT 1.10 was released.
def modtime(filepath: Path) -> float:
return filepath.stat().st_mtime
wheels.sort(key=modtime)
return wheels[-1]
def preload_dependencies() -> None:
"""Pre-load the datetime module from a wheel so that the API can find it."""
module= load_wheel_global("six", "six")
_log.debug("Loaded wheel: %s", module.__name__)
module= load_wheel_global("dateutil", "python_dateutil")
_log.debug("Loaded wheel: %s", module.__name__)
module = load_wheel_global("send2trash", "Send2Trash")
_log.debug("Loaded wheel: %s", module.__name__)
module = load_wheel_global("xmltodict", "xmltodict")
_log.debug("Loaded wheel: %s", module.__name__)
if __name__ == "__main__":
logging.basicConfig(level=logging.DEBUG)
wheel = _wheel_filename("python_dateutil")
print(f"Wheel: {wheel}")
module = load_wheel("dateutil", "python_dateutil")
print(f"module: {module}")