Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
dedadbc9ac | ||
|
|
cda399f11a | ||
|
|
ec42c45204 | ||
|
|
c98d3d1655 | ||
|
|
5e96bd8b6a | ||
|
|
2b4a985d85 | ||
|
|
56a51a3800 | ||
|
|
0982c8cc62 | ||
|
|
682e78c256 | ||
|
|
d90a9e7fc4 | ||
|
|
9d6b6cf103 | ||
|
|
bad88da2fe | ||
|
|
1e9ea8e85e | ||
|
|
c5bc000b56 | ||
|
|
42d288c0e2 | ||
|
|
935c1da30f | ||
|
|
612005c4f6 | ||
|
|
ee1f9029d1 | ||
|
|
1d8cf86215 | ||
|
|
b8283b2499 | ||
|
|
da0f1fa3c8 | ||
|
|
0d18ca421b | ||
|
|
48dd2657e9 | ||
|
|
62f2d11f8b | ||
|
|
93bbedae86 | ||
|
|
40fe74ef45 | ||
|
|
043b213a96 | ||
|
|
6db57122b4 | ||
|
|
d0eca800fb | ||
|
|
a6c24e174d | ||
|
|
a52a5ca338 | ||
|
|
acc85127c5 | ||
|
|
454f16a7c3 | ||
|
|
a731f748d9 | ||
|
|
9a7bddd530 | ||
|
|
83f66e133e | ||
|
|
ab97abf13e | ||
|
|
7820c17d08 | ||
|
|
9ed79adb8d | ||
|
|
b98348de02 | ||
|
|
a5094d403a | ||
|
|
6b0dee26e5 | ||
|
|
a44eb43f0f | ||
|
|
b6a5cb47a1 | ||
|
|
65efcec008 | ||
|
|
37730616c1 | ||
|
|
a53195d2a0 | ||
|
|
084fd8d433 | ||
|
|
33306b6787 | ||
|
|
b4cb0dec87 | ||
|
|
063251fe03 | ||
|
|
9b3ef8b693 | ||
|
|
a5ce071939 | ||
|
|
e8fa2e44e0 | ||
|
|
e223341ece | ||
|
|
5c8d9007f6 | ||
|
|
91163dc4f4 | ||
|
|
2a8e084b51 | ||
|
|
ce00a069fa | ||
|
|
bdadab6993 | ||
|
|
05d6cac67a | ||
|
|
528192b3c0 | ||
|
|
729d23b2c0 | ||
|
|
2e566c5ee1 | ||
|
|
e875d042a7 | ||
|
|
f05f850175 | ||
|
|
9ce9af28c3 | ||
|
|
57bf457d97 | ||
|
|
adf39cdf21 |
No files matched your search
+4
-1
@@ -6,4 +6,7 @@ python:
|
||||
install:
|
||||
- pip install -e .[develop]
|
||||
script:
|
||||
- nosetests tests/
|
||||
- nosetests --with-doctest
|
||||
sudo: false
|
||||
git:
|
||||
depth: 250
|
||||
+8
-7
@@ -10,13 +10,14 @@
|
||||
# master shall not use the lookup table, only tags
|
||||
master
|
||||
|
||||
# maintenance is currently the branch for preparation of maintenance release 1.2.7
|
||||
# so are any fix/... branches
|
||||
maintenance 1.2.7-dev 536bb31965db17b969e7c1c53e241ddac4ae1814
|
||||
fix/.* 1.2.7-dev 536bb31965db17b969e7c1c53e241ddac4ae1814
|
||||
|
||||
# Special case disconnected checkouts, e.g. 'git checkout <tag>'
|
||||
# neither should disconnected checkouts, e.g. 'git checkout <tag>'
|
||||
HEAD
|
||||
\(detached.*
|
||||
|
||||
# maintenance is currently the branch for preparation of maintenance release 1.2.8
|
||||
# so are any fix/... branches
|
||||
maintenance 1.2.8 6c622f7c4332b71c6ece59552ffc87c146155c84 pep440-dev
|
||||
fix/.* 1.2.8 6c622f7c4332b71c6ece59552ffc87c146155c84 pep440-dev
|
||||
|
||||
# every other branch is a development branch and thus gets resolved to 1.3.0-dev for now
|
||||
.* 1.3.0-dev 198d3450d94be1a2
|
||||
.* 1.3.0 198d3450d94be1a2 pep440-dev
|
||||
@@ -53,6 +53,8 @@ date of first contribution):
|
||||
* [Andrew Erickson](https://github.com/aerickson)
|
||||
* [Nicanor Romero Venier](https://github.com/nicanor-romero)
|
||||
* [Thomas Hou](https://github.com/masterhou)
|
||||
* [Mark Bastiaans](https://github.com/markbastiaans)
|
||||
* [Kevin Murphy](https://github.com/kevingelion)
|
||||
|
||||
OctoPrint started off as a fork of [Cura](https://github.com/daid/Cura) by
|
||||
[Daid Braam](https://github.com/daid). Parts of its communication layer and
|
||||
|
||||
+124
-1
@@ -1,5 +1,128 @@
|
||||
# OctoPrint Changelog
|
||||
|
||||
## 1.2.8 (2015-12-07)
|
||||
|
||||
### Notes for Upgraders
|
||||
|
||||
#### A bug in 1.2.7 prevents directly updating to 1.2.8, here's what to do
|
||||
|
||||
A bug in OctoPrint 1.2.7 (fixed in 1.2.8) prevents updating OctoPrint to version
|
||||
1.2.8. If you try to perform the update, you will simply be told that "the update
|
||||
was successful", but the update won't actually have taken place. To solve this
|
||||
hen-egg-problem, a plugin has been made available that fixes said bug (through
|
||||
monkey patching).
|
||||
|
||||
The plugin is called "Updatefix 1.2.7" and can be found
|
||||
[in the plugin repository](http://plugins.octoprint.org/plugins/updatefix127/)
|
||||
and [on Github](https://github.com/OctoPrint/OctoPrint-Updatefix-1.2.7/).
|
||||
|
||||
Before attempting to update your installation from version 1.2.7 to version 1.2.8,
|
||||
please install the plugin via your plugin manager and restart your server. Note that
|
||||
you will only see it in the Plugin Manager if you need it, since it's only compatible with
|
||||
OctoPrint version 1.2.7. After you installed the plugin and restarted your server
|
||||
you can update as usual. The plugin will self-uninstall once it detects that it's
|
||||
running under OctoPrint 1.2.8. After the self-uninstall another restart of your server
|
||||
will be triggered (if you have setup your server's restart command, defaults to
|
||||
`sudo service octoprint restart` on OctoPi) in order to really get rid of any
|
||||
left-overs, so don't be alarmed when that happens, it is intentional.
|
||||
|
||||
**If you cannot or don't want to use the plugin**, alternatively you can switch
|
||||
OctoPrint to "Commit" based tracking via the settings of the Software Update plugin,
|
||||
update, then switch back to "Release" based tracking (see [this screenshot](https://i.imgur.com/wvkgiGJ.png)).
|
||||
|
||||
#### Bed temperatures are now only displayed if printer profile has a heated bed configured
|
||||
|
||||
This release fixes a [bug](https://github.com/foosel/OctoPrint/issues/1125)
|
||||
that caused bed temperature display and controls to be available even if the
|
||||
selected printer profile didn't have a heated bed configured.
|
||||
|
||||
If your printer does have a heated bed but you are not seeing its temperature
|
||||
in the "Temperature" tab after updating to 1.2.8, please make sure to check
|
||||
the "Heated Bed" option in your printer profile (under Settings > Printer Profiles)
|
||||
as shown [in this short GIF](http://i.imgur.com/wp1j9bs.gif).
|
||||
|
||||
### Improvements
|
||||
|
||||
* Version numbering now follows [PEP440](https://www.python.org/dev/peps/pep-0440/).
|
||||
* Prepared some things for publishing OctoPrint on [PyPi](https://pypi.python.org/pypi)
|
||||
in the future.
|
||||
* [BlueprintPlugin mixin](http://docs.octoprint.org/en/master/plugins/mixins.html#blueprintplugin)
|
||||
now has an `errorhandler` decorator that serves the same purpose as
|
||||
[Flask's](http://flask.pocoo.org/docs/0.10/patterns/errorpages/#error-handlers)
|
||||
([#1059](https://github.com/foosel/OctoPrint/pull/1059))
|
||||
* Interpret `M25` in a GCODE file that is being streamed from OctoPrint as
|
||||
indication to pause, like `M0` and `M1`.
|
||||
* Cache rendered page and translation files indefinitely. That should
|
||||
significantly improve performance on reloads of the web interface.
|
||||
* Added the string "unknown command" to the list of ignored printer errors.
|
||||
This should help with general firmware compatibility in case a firmware
|
||||
lacks features.
|
||||
* Added the strings "cannot open" and "cannot enter" to the list of ignored
|
||||
printer errors. Those are errors that Marlin may report if there is an issue
|
||||
with the printer's SD card.
|
||||
* The "CuraEngine" plugin now makes it more obvious that it only targets
|
||||
CuraEngine versions up to and including 15.04 and also links to the plugin's
|
||||
homepage with more information right within the settings dialog.
|
||||
* Browser tab visibility is now tracked by the web interface, disabling the
|
||||
webcam and the GCODE viewer if the tab containing OctoPrint is not active.
|
||||
That should reduce the amount of resource utilized by the web interface on
|
||||
the client when it is not actively monitored. Might also help to mitigate
|
||||
[#1065](https://github.com/foosel/OctoPrint/issues/1065), the final verdict
|
||||
on that one is still out though.
|
||||
* The printer log in the terminal tab will now be cut off after 3000 lines
|
||||
even if autoscroll is disabled. If the limit is reached, no more log lines
|
||||
will be added to the client's buffer. That ensures that the log will not
|
||||
scroll and the current log excerpt will stay put while also not causing
|
||||
the browser to run into memory errors due to trying to buffer an endless
|
||||
amount of log lines.
|
||||
* Increased timeout of "waiting for restart" after an update from 20 to 60sec
|
||||
(20sec turned out to be too little for OctoPi for whatever reason).
|
||||
* Added a couple of unit tests
|
||||
|
||||
### Bug Fixes
|
||||
|
||||
* [#1120](https://github.com/foosel/OctoPrint/issues/1120) - Made the watchdog
|
||||
that monitors and handles the `watched` folder more resilient towards errors.
|
||||
* [#1125](https://github.com/foosel/OctoPrint/issues/1125) - Fixed OctoPrint
|
||||
displaying bed temperature and controls and allowing the sending of GCODE
|
||||
commands targeting the bed (`M140`, `M190`) if the printer profile doesn't
|
||||
have a heated bed configured.
|
||||
* Fixed an issue that stopped the software updater working for OctoPrint. The
|
||||
updater reports success updating, but no update has actually taken place. A
|
||||
fix can be applied for this issue to OctoPrint version 1.2.7 via
|
||||
[the Updatefix 1.2.7 plugin](https://github.com/OctoPrint/OctoPrint-Updatefix-1.2.7).
|
||||
For more information please refer to the [Important information for people updating from version 1.2.7](#important-information-for-people-updating-from-version-127)
|
||||
above.
|
||||
* Fix: Current filename in job data should never be prefixed with `/`
|
||||
* Only persist plugin settings that differ from the defaults. This way the
|
||||
`config.yaml` won't be filled with lots of redundant data. It's the
|
||||
responsibility of the plugin authors to responsibly handle changes in default
|
||||
settings of their plugins and add data migration where necessary.
|
||||
* Fixed a documentation bug ([#1067](https://github.com/foosel/OctoPrint/pull/1067))
|
||||
* Fixed a conflict with bootstrap-responsive, e.g. when using the
|
||||
[ScreenSquish Plugin](http://plugins.octoprint.org/plugins/screensquish/)
|
||||
([#1103](https://github.com/foosel/OctoPrint/pull/1067))
|
||||
* Fixed OctoPrint still sending SD card related commands to the printer even
|
||||
if SD card support is disabled (e.g. `M21`).
|
||||
* Hidden files are no longer visible to the template engine, neither as (GCODE)
|
||||
scripts nor as interface templates.
|
||||
* The hostname and URL prefix via which the OctoPrint web interface is accessed
|
||||
is now part of the cache key. Without that being the case the cache could
|
||||
be created referring to something like `/octoprint/prefix/api/` for its API
|
||||
endpoint (if accessed via `http://somehost:someport/octoprint/prefix/` first
|
||||
time), which would then cause the interface to not work if accessed later
|
||||
via another route (e.g. `http://someotherhost/`).
|
||||
* Fixed a JavaScript error on finishing streaming of a file to SD.
|
||||
* Fixed version reporting on detached HEADs (when the branch detection
|
||||
reported "HEAD" instead of "(detached"
|
||||
* Fixed some path checks for systems with symlinked paths
|
||||
([#1051](https://github.com/foosel/OctoPrint/pull/1051))
|
||||
* Fixed a bug causing the "Server Offline" overlay to pop _under_ the
|
||||
"Please reload" overlay, which could lead to "Connection refused" browser
|
||||
messages when clicking "Reload now" in the wrong moment.
|
||||
|
||||
([Commits](https://github.com/foosel/OctoPrint/compare/1.2.7...1.2.8))
|
||||
|
||||
## 1.2.7 (2015-10-20)
|
||||
|
||||
### Improvements
|
||||
@@ -386,7 +509,7 @@
|
||||
changed under "Temperatures" in the Settings ([#343](https://github.com/foosel/OctoPrint/issues/343)).
|
||||
* High-DPI support for the GCode viewer ([#837](https://github.com/foosel/OctoPrint/issues/837)).
|
||||
* Stop websocket connections from multiplying ([#888](https://github.com/foosel/OctoPrint/pull/888)).
|
||||
* New setting to rotate webcam by 90° counter clockwise ([#895](https://github.com/foosel/OctoPrint/issues/895) and
|
||||
* New setting to rotate webcam by 90° counter clockwise ([#895](https://github.com/foosel/OctoPrint/issues/895) and
|
||||
[#906](https://github.com/foosel/OctoPrint/pull/906))
|
||||
* System commands now be set to a) run asynchronized by setting their `async` property to `true` and b) to ignore their
|
||||
result by setting their `ignore` property to `true`.
|
||||
|
||||
+255
-42
@@ -1,51 +1,264 @@
|
||||
Issues, Tickets, however you may call them
|
||||
------------------------------------------
|
||||
# Contribution Guidelines
|
||||
|
||||
Read the following short instructions **fully** and **follow them** if you want your ticket to be taken care of and not closed again directly! They are linked on top of every new issue form, so don't say nobody warned you afterwards.
|
||||
This document outlines what you need to know before **[creating tickets](#issues-tickets-however-you-may-call-them)**
|
||||
or **[creating pull requests](#pull-requests)**.
|
||||
|
||||
- **Read the [FAQ](https://github.com/foosel/OctoPrint/wiki/FAQ)**
|
||||
- Always create **one ticket for one purpose**. So don't mix two or more feature requests, support requests, bugs etc into one ticket. If you do, your ticket will be closed!
|
||||
- If you want to report a bug, **READ AND FOLLOW [How to file a bug report](https://github.com/foosel/OctoPrint/wiki/How-to-file-a-bug-report)!** Tickets will be automatically checked if they comply with the requirements outlined in that wiki node! Other then what's written in there (**and really EVERYTHING that is written in there!**) you don't have to do anything special with your ticket. Listen to what GitIssueBot might have to say to you!
|
||||
- If you want to post a **request** of any kind (feature request, documentation request, ...), **add [Request] to your issue's title!**
|
||||
- If you need **support** with a problem of your installation (e.g. if you have problems getting the webcam to work) or have a general **question**, the issue tracker is not the right place. Consult the [Mailinglist](https://groups.google.com/group/octoprint) or the [Google+ Community](https://plus.google.com/communities/102771308349328485741) instead!
|
||||
- If you are a developer that wants to brainstorm a pull request or possible changes to the plugin system, **add [Brainstorming] to your issue's title!** (see below).
|
||||
- If you have another reason for creating a ticket that doesn't fit any of the above categories, it's something better suited for the [Mailinglist](https://groups.google.com/group/octoprint) or the [Google+ Community](https://plus.google.com/communities/102771308349328485741).
|
||||
## Contents
|
||||
|
||||
Following these guidelines (**especially EVERYTHING mentioned in ["How to file a bug report"](https://github.com/foosel/OctoPrint/wiki/How-to-file-a-bug-report)**) is necessary so the tickets stay manageable - you are not the only one with an open issue, so please respect that you have to **play by the rules** so that your problem can be taken care of. Tickets not playing by the rules **will be closed without further investigation!**.
|
||||
* [Issues, Tickets, however you may call them](#issues-tickets-however-you-may-call-them)
|
||||
* [How to file a bug report](#how-to-file-a-bug-report)
|
||||
* [What should I do before submitting a bug report?](#what-should-i-do-before-submitting-a-bug-report)
|
||||
* [What should I include in a bug report?](#what-should-i-include-in-a-bug-report)
|
||||
* [Where can I find which version and branch I'm on?](#where-can-i-find-which-version-and-branch-im-on)
|
||||
* [Where can I find those log files you keep talking about?](#where-can-i-find-those-log-files-you-keep-talking-about)
|
||||
* [Where can I find my browser's error console?](#where-can-i-find-my-browsers-error-console)
|
||||
* [Pull requests](#pull-requests)
|
||||
* [History](#history)
|
||||
* [Footnotes](#footnotes)
|
||||
|
||||
Pull Requests
|
||||
-------------
|
||||
## Issues, Tickets, however you may call them
|
||||
|
||||
1. If you want to add a new feature to OctoPrint, **please always first consider if it wouldn't be better suited for a
|
||||
plugin.** As a general rule of thumb, any feature that is only of interest to a small sub group should be moved into a
|
||||
plugin. If the current plugin system doesn't allow you to implement your feature as a plugin, create a "Brainstorming"
|
||||
ticket to get the discussion going how best to solve *this* in OctoPrint's plugin system - maybe that's the actual PR
|
||||
you have been waiting for to contribute :)
|
||||
2. If you plan to make **any large changes to the code or appearance, please open a "Brainstorming" ticket first** so that
|
||||
we can determine if it's a good time for your specific pull request. It might be that I'm currently in the process of
|
||||
making heavy changes to the code locations you'd target as well, or your approach doesn't fit the general "project
|
||||
vision", and that would just cause unnecessary work and frustration for everyone or possibly get the PR rejected.
|
||||
3. When adding code to OctoPrint, make sure you **follow the current coding style**. That means tabs instead of spaces in the
|
||||
python files (yes, I know that this goes against PEP-8, I don't care) and space instead of tabs in the Javascript sources,
|
||||
english language (that means code, variables, comments!), comments where necessary (tell why the code does something like
|
||||
it does it, structure your code), following the general architecture. If your PR needs to make changes to the Stylesheets,
|
||||
change the ``.less`` files from which the CSS is compiled. PRs that contain direct changes to the compiled
|
||||
CSS will be closed.
|
||||
4. **Test your changes thoroughly**. That also means testing with usage scenarios you don't normally use, e.g. if you only
|
||||
use access control, test without and vice versa. If you only test with your printer, test with the virtual printer and
|
||||
vice versa. State in your pull request how your tested your changes.
|
||||
5. Please create all pull requests **against the `devel` branch**.
|
||||
6. Create **one pull request per feature/bug fix**.
|
||||
7. Create a **custom branch** for your feature/bug fix and use that as base for your pull request. Pull requests directly
|
||||
against your version of `devel` will be closed.
|
||||
8. In your pull request's description, **state what your pull request is doing**, as in, what feature does it implement, what
|
||||
bug does it fix. The more thoroughly you explain your intent behind the PR here, the higher the chances it will get merged
|
||||
fast.
|
||||
9. Don't forget to **add yourself to the [AUTHORS](../AUTHORS.md) file** :)
|
||||
Please read the following short instructions fully and follow them. You can
|
||||
help the project tremendously this way: not only do you help the maintainers
|
||||
to **address problems in a timely manner** but also keep it possible for them
|
||||
to **fix bugs, add new and improve on existing functionality** instead of doing
|
||||
nothing but ticket management.
|
||||
|
||||
History
|
||||
-------
|
||||

|
||||
|
||||
* 2015-01-23: More guidelines for creating pull requests, support/questions redirected to Mailinglist/G+ community
|
||||
- **[Read the FAQ](https://github.com/foosel/OctoPrint/wiki/FAQ)**
|
||||
- If you want to report a **bug**, [read "How to file a bug report" below](#how-to-file-a-bug-report)
|
||||
and *[use the provided template](#what-should-i-include-in-a-ticket)*.
|
||||
You do not need to do anything else with your ticket.
|
||||
- If you want to post a **request** of any kind (feature request, documentation
|
||||
request, ...), add `[Request]` to your issue's title (e.g. `[Request] Awesome new feature`).
|
||||
- If you are a **developer** that wants to brainstorm a pull request or possible
|
||||
changes to the plugin system, add [Brainstorming] to your issue's title (e.g.
|
||||
`[Brainstorming] New plugin hook for doing some cool stuff`).
|
||||
- If you need **support**, have a **question** or some **other reason** that
|
||||
doesn't fit any of the above categories, the issue tracker is not the right place.
|
||||
Consult the [Mailinglist](https://groups.google.com/group/octoprint) or the
|
||||
[Google+ Community](https://plus.google.com/communities/102771308349328485741) instead.
|
||||
|
||||
No matter what kind of ticket you create, never mix two or more "ticket reasons"
|
||||
into one ticket: One ticket per bug, request, brainstorming thread please.
|
||||
|
||||
----
|
||||
|
||||
**Note**: A bot is in place that monitors new tickets, automatically
|
||||
categorizes them and checks new bug reports for usage of the provided template.
|
||||
That bot will only bother you if you open a ticket that appears to be a bug (no
|
||||
`[Request]` or `[Brainstorming]` in the title) without the template, and it
|
||||
will do that only to ensure that all information needed to solve the issue is
|
||||
available for the maintainers to directly start tackling that problem.
|
||||
|
||||
----
|
||||
|
||||
## How to file a bug report
|
||||
|
||||
If you encounter an issue with OctoPrint, you are welcome to
|
||||
[submit a bug report](https://goo.gl/GzkGv9).
|
||||
|
||||
Before you do that for the first time though please take a moment to read the
|
||||
following section *completely*. Thank you! :)
|
||||
|
||||
### What should I do before submitting a bug report?
|
||||
|
||||
1. **Make sure you are at the right location**. This is the Github repository
|
||||
of the official version of OctoPrint, which is the 3D print server and
|
||||
corresponding web interface itself.
|
||||
|
||||
**This is not the Github respository of OctoPi**, which is the preconfigured
|
||||
Raspberry Pi image including OctoPrint among other things - that one can be found
|
||||
[here](https://github.com/guysoft/OctoPi). Please note that while we do have
|
||||
some entries regarding OctoPi in the FAQ, any bugs should be reported in the
|
||||
[proper bug tracker](https://github.com/guysoft/OctoPi/issues) which - again -
|
||||
is not here.
|
||||
|
||||
**This is also not the Github repository of any OctoPrint Plugins you
|
||||
might have installed**. Report any issues with those in their corresponding
|
||||
bug tracker (probably linked to from the plugin's homepage).
|
||||
|
||||
Finally, **this is also not the right issue tracker if you are running an
|
||||
forked version of OctoPrint**. Seek help for such unofficial versions from
|
||||
the people maintaining them instead.
|
||||
|
||||
2. Please make sure to **test out the current version** of OctoPrint to see
|
||||
whether the problem you are encountering still exists.
|
||||
|
||||
If you are feeling up to it you might also want to try the current development
|
||||
version of OctoPrint (if you aren't already). Refer to the [FAQ](https://github.com/foosel/OctoPrint/wiki/FAQ)
|
||||
for information on how to do this.
|
||||
|
||||
3. The problem still exists? Then please **look through the
|
||||
[existing tickets](https://github.com/foosel/OctoPrint/issues?state=open)
|
||||
(use the [search](https://github.com/foosel/OctoPrint/search?q=&ref=cmdform&type=Issues))**
|
||||
to check if there already exists a report of the issue you are encountering.
|
||||
Sorting through duplicates of the same issue sometimes causes more work than
|
||||
fixing it. Take the time to filter through possible duplicates and be really
|
||||
sure that your problem definitely is a new one. Try more than one search query
|
||||
(e.g. do not only search for "webcam" if you happen to run into an issue
|
||||
with your webcam, also search for "timelapse" etc).
|
||||
|
||||
### What should I include in a bug report?
|
||||
|
||||
Always use the following template (you can remove what's within `[...]`, that's
|
||||
only provided here as some additional information for you):
|
||||
|
||||
#### What were you doing?
|
||||
|
||||
[Please be as specific as possible here. The maintainers will need to reproduce
|
||||
your issue in order to fix it and that is not possible if they don't know
|
||||
what you did to get it to happen in the first place. If you encountered
|
||||
a problem with specific files of any sorts, make sure to also include a link to a file
|
||||
with which to reproduce the problem.]
|
||||
|
||||
#### What did you expect to happen?
|
||||
|
||||
#### What happened instead?
|
||||
|
||||
#### Branch & Commit or Version of OctoPrint
|
||||
|
||||
[Can be found in the lower left corner of the web interface.]
|
||||
|
||||
#### Printer model & used firmware incl. version
|
||||
|
||||
[If applicable, always include if unsure.]
|
||||
|
||||
#### Browser and Version of Browser, Operating System running Browser
|
||||
|
||||
[If applicable, always include if unsure.]
|
||||
|
||||
#### Link to octoprint.log
|
||||
|
||||
[On gist.github.com or pastebin.com. Always include and never truncate.]
|
||||
|
||||
#### Link to contents of terminal tab or serial.log
|
||||
|
||||
[On gist.github.com or pastebin.com. If applicable, always include if unsure or
|
||||
reporting communication issues. Never truncate.]
|
||||
|
||||
#### Link to contents of Javascript console in the browser
|
||||
|
||||
[On gist.github.com or pastebin.com or alternatively a screenshot. If applicable -
|
||||
always include if unsure or reporting UI issues.]
|
||||
|
||||
#### Screenshot(s) showing the problem:
|
||||
|
||||
[If applicable. Always include if unsure or reporting UI issues.]
|
||||
|
||||
I have read the FAQ.
|
||||
|
||||
### Where can I find which version and branch I'm on?
|
||||
|
||||
You can find out all of them by taking a look into the lower left corner of the
|
||||
OctoPrint UI:
|
||||
|
||||

|
||||
|
||||
If you don't have access to the UI you can find out that information via the
|
||||
command line as well. Either `octoprint --version` or `python setup.py version`
|
||||
in OctoPrint's folder will tell you the version of OctoPrint you are running
|
||||
(note: if it doesn't then you are running a version older than 1.1.0,
|
||||
*upgrade now*). A `git branch` in your OctoPrint installation folder will mark
|
||||
the branch you are on with a little *. `git rev-parse HEAD` will tell you the
|
||||
current commit.
|
||||
|
||||
### Where can I find those log files you keep talking about?
|
||||
|
||||
OctoPrint by default provides two log outputs, a third one can be enabled if
|
||||
more information is needed.
|
||||
|
||||
One is contained in the **"Terminal" tab** within OctoPrint's UI and is a log
|
||||
of the last 300 lines of communication with the printer. Please copy-paste
|
||||
this somewhere (disable auto scroll to make copying the contents easier) -
|
||||
e.g. http://pastebin.com or http://gist.github.com - and include a link in
|
||||
your bug report.
|
||||
|
||||
There is also **OctoPrint's application log file** or in short `octoprint.log`,
|
||||
which is by default located at `~/.octoprint/logs/octoprint.log` on Linux,
|
||||
`%APPDATA%\OctoPrint\logs\octoprint.log` on Windows and
|
||||
`~/Library/Application Support/OctoPrint/logs/octoprint.log` on MacOS. Please
|
||||
copy-paste this to pastebin or gist as well and include a link in your bug
|
||||
report.
|
||||
|
||||
It might happen that you are asked to provide a more **thorough log of the
|
||||
communication with the printer** if you haven't already done so, the `serial.log`.
|
||||
This is not written by default due to performance reasons, but you can enable
|
||||
it in the settings dialog. After enabling that log, please reproduce the problem
|
||||
again (connect to the printer, do whatever triggers it), then copy-paste
|
||||
`~/.octoprint/logs/serial.log` (Windows: `%APPDATA%\OctoPrint\logs\serial.log`,
|
||||
MacOS: `~/Library/Application Support/OctoPrint/logs/serial.log`) to pastebin
|
||||
or gist and include the link in the bug report.
|
||||
|
||||
You might also be asked to provide a log with an increased log level. You can
|
||||
find information on how to do just that in the
|
||||
[docs](http://docs.octoprint.org/en/master/configuration/logging_yaml.html).
|
||||
|
||||
### Where can I find my browser's error console?
|
||||
|
||||
See [How to open the Javascript Console in different browsers](https://webmasters.stackexchange.com/questions/8525/how-to-open-the-javascript-console-in-different-browsers)
|
||||
|
||||
## Pull requests
|
||||
|
||||
1. If you want to add a new feature to OctoPrint, **please always first
|
||||
consider if it wouldn't be better suited for a plugin.** As a general rule
|
||||
of thumb, any feature that is only of interest to a small sub group should
|
||||
be moved into a plugin. If the current plugin system doesn't allow you to
|
||||
implement your feature as a plugin, create a "Brainstorming" ticket to get
|
||||
the discussion going on how best to solve *this* in OctoPrint's plugin
|
||||
system - maybe that's the actual PR you have been waiting for to contribute :)
|
||||
2. If you plan to make **any large changes to the code or appearance, please
|
||||
open a "Brainstorming" ticket first** so that we can determine if it's a
|
||||
good time for your specific pull request. It might be that we're currently
|
||||
in the process of making heavy changes to the code locations you'd target
|
||||
as well, or your approach doesn't fit the general "project vision", and
|
||||
that would just cause unnecessary work and frustration for everyone or
|
||||
possibly get the PR rejected.
|
||||
3. Create your pull request **from a custom branch** on your end (e.g.
|
||||
`dev/myNewFeature`)[1] **against the `devel` branch**. Create **one pull request
|
||||
per feature/bug fix**. If your PR contains an important bug fix, we will
|
||||
make sure to backport it to the `maintenance` branch to also include it in
|
||||
the next release.
|
||||
4. Make sure you **follow the current coding style**. This means:
|
||||
* Tabs instead of spaces in the Python files[2]
|
||||
* Spaces instead of tabs in the Javascript sources
|
||||
* English language (code, variables, comments, ...)
|
||||
* Comments where necessary: Tell why the code does something like it does
|
||||
it, structure your code
|
||||
* Following the general architecture
|
||||
If your PR needs to make changes to the Stylesheets, change the ``.less`` files
|
||||
from which the CSS is compiled.
|
||||
5. **Test your changes thoroughly**. That also means testing with usage
|
||||
scenarios you don't normally use, e.g. if you only use access control, test
|
||||
without and vice versa. If you only test with your printer, test with the
|
||||
virtual printer and vice versa. State in your pull request how your tested
|
||||
your changes. Ideally **add unit tests** - OctoPrint severly lacks in that
|
||||
department, but we are trying to change that, so any new code already covered
|
||||
with a test suite helps a lot!
|
||||
6. In your pull request's description, **state what your pull request is doing**,
|
||||
as in, what feature does it implement, what bug does it fix. The more
|
||||
thoroughly you explain your intent behind the PR here, the higher the
|
||||
chances it will get merged fast.
|
||||
7. Important: Don't forget to **add yourself to the [AUTHORS](./AUTHORS.md)
|
||||
file** :)
|
||||
|
||||
## History
|
||||
|
||||
* 2015-01-23: More guidelines for creating pull requests, support/questions
|
||||
redirected to Mailinglist/G+ community
|
||||
* 2015-01-27: Added another explicit link to the FAQ
|
||||
* 2015-07-07: Added step to add yourself to AUTHORS when creating a PR :)
|
||||
* 2015-12-01: Heavily reworked to include examples, better structure and
|
||||
all information in one document.
|
||||
|
||||
## Footnotes
|
||||
* [1] - If you are wondering why, the problem is that anything that you add
|
||||
to your PR's branch will also become part of your PR, so if you create a
|
||||
PR from your version of `devel` chances are high you'll add changes to the
|
||||
PR that do not belong to the PR.
|
||||
* [2] - Yes, we know that this goes against PEP-8. OctoPrint started out as
|
||||
a fork of Cura and hence stuck to the coding style found therein. Changing
|
||||
it now would make the history and especially `git blame` completely
|
||||
unusable, so for now we'll have to deal with it (this decision might be
|
||||
revisited in the future).
|
||||
+4
-4
@@ -37,7 +37,7 @@ Issue a job command
|
||||
|
||||
.. sourcecode:: http
|
||||
|
||||
POST /api/control/job HTTP/1.1
|
||||
POST /api/job HTTP/1.1
|
||||
Host: example.com
|
||||
Content-Type: application/json
|
||||
X-Api-Key: abcdef...
|
||||
@@ -54,7 +54,7 @@ Issue a job command
|
||||
|
||||
.. sourcecode:: http
|
||||
|
||||
POST /api/control/job HTTP/1.1
|
||||
POST /api/job HTTP/1.1
|
||||
Host: example.com
|
||||
Content-Type: application/json
|
||||
X-Api-Key: abcdef...
|
||||
@@ -71,7 +71,7 @@ Issue a job command
|
||||
|
||||
.. sourcecode:: http
|
||||
|
||||
POST /api/control/job HTTP/1.1
|
||||
POST /api/job HTTP/1.1
|
||||
Host: example.com
|
||||
Content-Type: application/json
|
||||
X-Api-Key: abcdef...
|
||||
@@ -88,7 +88,7 @@ Issue a job command
|
||||
|
||||
.. sourcecode:: http
|
||||
|
||||
POST /api/control/job HTTP/1.1
|
||||
POST /api/job HTTP/1.1
|
||||
Host: example.com
|
||||
Content-Type: application/json
|
||||
X-Api-Key: abcdef...
|
||||
|
||||
+15
-5
@@ -25,7 +25,8 @@ Tool
|
||||
See :ref:`sec-api-printer-toolcommand`.
|
||||
Bed
|
||||
Bed commands allow setting the temperature and temperature offset for the printer's heated bed. Querying the
|
||||
corresponding resource returns temperature information including an optional history.
|
||||
corresponding resource returns temperature information including an optional history. Note that Bed commands
|
||||
are only available if the currently selected printer profile has a heated bed.
|
||||
See :ref:`sec-api-printer-bedcommand`.
|
||||
SD card
|
||||
SD commands allow initialization, refresh and release of the printer's SD card (if available). Querying the
|
||||
@@ -564,6 +565,9 @@ Issue a bed command
|
||||
|
||||
Upon success, a status code of :http:statuscode:`204` and an empty body is returned.
|
||||
|
||||
If no heated bed is configured for the currently selected printer profile, the resource will return
|
||||
an :http:statuscode:`409`.
|
||||
|
||||
**Example Target Temperature Request**
|
||||
|
||||
Set the target temperature for the printer's heated bed to 75°C.
|
||||
@@ -610,7 +614,8 @@ Issue a bed command
|
||||
:statuscode 204: No error
|
||||
:statuscode 400: If ``target`` or ``offset`` is not a valid number or outside of the supported range, or if the
|
||||
request is otherwise invalid.
|
||||
:statuscode 409: If the printer is not operational.
|
||||
:statuscode 409: If the printer is not operational or the selected printer profile
|
||||
does not have a heated bed.
|
||||
|
||||
.. _sec-api-printer-bedstate:
|
||||
|
||||
@@ -627,6 +632,9 @@ Retrieve the current bed state
|
||||
|
||||
Returns a :http:statuscode:`200` with a Temperature Response in the body upon success.
|
||||
|
||||
If no heated bed is configured for the currently selected printer profile, the resource will return
|
||||
an :http:statuscode:`409`.
|
||||
|
||||
.. note::
|
||||
If you want both tool and bed temperature information at the same time, take a look at
|
||||
:ref:`Retrieve the current printer state <sec-api-printer-state>`.
|
||||
@@ -675,7 +683,8 @@ Retrieve the current bed state
|
||||
:query limit: If set to an integer (``n``), only the last ``n`` data points from the printer's temperature history
|
||||
will be returned. Will be ignored if ``history`` is not enabled.
|
||||
:statuscode 200: No error
|
||||
:statuscode 409: If the printer is not operational.
|
||||
:statuscode 409: If the printer is not operational or the selected printer profile
|
||||
does not have a heated bed.
|
||||
|
||||
.. _sec-api-printer-sdcommand:
|
||||
|
||||
@@ -856,7 +865,7 @@ Send an arbitrary command to the printer
|
||||
.. sourcecode:: http
|
||||
|
||||
HTTP/1.1 204 No Content
|
||||
|
||||
|
||||
:json string command: Single command to send to the printer, mutually exclusive with ``commands``.
|
||||
:json string commands: List of commands to send to the printer, mutually exclusive with ``command``.
|
||||
:statuscode 204: No error
|
||||
@@ -913,7 +922,8 @@ Temperature State
|
||||
* - ``bed``
|
||||
- 0..1
|
||||
- :ref:`Temperature Data <sec-api-datamodel-printer-tempdata>`
|
||||
- Current temperature stats for the printer's heated bed. Not included if querying only tool state.
|
||||
- Current temperature stats for the printer's heated bed. Not included if querying only tool state or if
|
||||
the currently selected printer profile does not have a heated bed.
|
||||
* - ``history``
|
||||
- 0..1
|
||||
- List of :ref:`Historic Temperature Datapoint <sec-api-datamodel-printer-temphistory>`
|
||||
|
||||
@@ -86,7 +86,7 @@ Out of the box, OctoPrint defaults to the following script setup for ``afterPrin
|
||||
|
||||
;disable all heaters
|
||||
{% snippet 'disable_hotends' %}
|
||||
M140 S0
|
||||
[% snippet 'disable_bed' %}
|
||||
|
||||
;disable fan
|
||||
M106 S0
|
||||
@@ -100,8 +100,19 @@ The ``disable_hotends`` snippet is defined as follows:
|
||||
M104 T{{ tool }} S0
|
||||
{% endfor %}
|
||||
|
||||
As you can see, the ``disable_hotends`` snippet utilizes the ``printer_profile`` context variable in order to
|
||||
iterate through all available extruders and set their temperature to 0.
|
||||
The ``disable_bed`` snippet is defined as follows:
|
||||
|
||||
.. code-block:: jinja
|
||||
:caption: Default ``disable_bed`` snippet
|
||||
|
||||
{% if printer_profile.heatedBed %}
|
||||
M140 S0
|
||||
{% endif %}
|
||||
|
||||
As you can see, the ``disable_hotends`` and ``disable_bed`` snippets utilize the
|
||||
``printer_profile`` context variable in order to iterate through all available
|
||||
extruders and set their temperature to 0, and to also set the bed temperature
|
||||
to 0 if a heated bed is configured.
|
||||
|
||||
.. seealso::
|
||||
|
||||
|
||||
@@ -0,0 +1,11 @@
|
||||
[metadata]
|
||||
description-file = README.md
|
||||
|
||||
[versioneer]
|
||||
VCS = git
|
||||
style = pep440-post
|
||||
versionfile_source = src/octoprint/_version.py
|
||||
versionfile_build = octoprint/_version.py
|
||||
tag_prefix =
|
||||
parentdir_prefix =
|
||||
lookupfile = .versioneer-lookup
|
||||
@@ -47,7 +47,10 @@ EXTRA_REQUIRES = dict(
|
||||
# Documentation dependencies
|
||||
"sphinx>=1.3",
|
||||
"sphinxcontrib-httpdomain",
|
||||
"sphinx_rtd_theme"
|
||||
"sphinx_rtd_theme",
|
||||
|
||||
# PyPi upload related
|
||||
"pypandoc"
|
||||
],
|
||||
|
||||
# Dependencies for developing OctoPrint plugins
|
||||
@@ -56,17 +59,12 @@ EXTRA_REQUIRES = dict(
|
||||
]
|
||||
)
|
||||
|
||||
# Additional requirements for setup
|
||||
SETUP_REQUIRES = []
|
||||
|
||||
# Dependency links for any of the aforementioned dependencies
|
||||
DEPENDENCY_LINKS = []
|
||||
|
||||
# Versioneer configuration
|
||||
versioneer.VCS = 'git'
|
||||
versioneer.versionfile_source = 'src/octoprint/_version.py'
|
||||
versioneer.versionfile_build = 'octoprint/_version.py'
|
||||
versioneer.tag_prefix = ''
|
||||
versioneer.parentdir_prefix = ''
|
||||
versioneer.lookupfile = '.versioneer-lookup'
|
||||
|
||||
#-----------------------------------------------------------------------------------------------------------------------
|
||||
# Anything below here is just command setup and general setup configuration
|
||||
|
||||
@@ -90,8 +88,22 @@ def params():
|
||||
version = versioneer.get_version()
|
||||
cmdclass = get_cmdclass()
|
||||
|
||||
description = "A responsive web interface for 3D printers"
|
||||
description = "A snappy web interface for 3D printers"
|
||||
long_description = open("README.md").read()
|
||||
|
||||
install_requires = INSTALL_REQUIRES
|
||||
extras_require = EXTRA_REQUIRES
|
||||
dependency_links = DEPENDENCY_LINKS
|
||||
setup_requires = SETUP_REQUIRES
|
||||
|
||||
try:
|
||||
import pypandoc
|
||||
setup_requires += ["setuptools-markdown"]
|
||||
long_description_markdown_filename = "README.md"
|
||||
del pypandoc
|
||||
except:
|
||||
pass
|
||||
|
||||
classifiers = [
|
||||
"Development Status :: 4 - Beta",
|
||||
"Environment :: Web Environment",
|
||||
@@ -126,9 +138,6 @@ def params():
|
||||
|
||||
include_package_data = True
|
||||
zip_safe = False
|
||||
install_requires = INSTALL_REQUIRES
|
||||
extras_require = EXTRA_REQUIRES
|
||||
dependency_links = DEPENDENCY_LINKS
|
||||
|
||||
if os.environ.get('READTHEDOCS', None) == 'True':
|
||||
# we can't tell read the docs to please perform a pip install -e .[develop], so we help
|
||||
|
||||
+539
-157
@@ -1,28 +1,81 @@
|
||||
|
||||
# This file helps to compute a version number in source trees obtained from
|
||||
# git-archive tarball (such as those provided by githubs download-from-tag
|
||||
# feature). Distribution tarballs (build by setup.py sdist) and build
|
||||
# feature). Distribution tarballs (built by setup.py sdist) and build
|
||||
# directories (produced by setup.py build) will contain a much shorter file
|
||||
# that just contains the computed version number.
|
||||
|
||||
# This file is released into the public domain. Generated by
|
||||
# versioneer-0.10 (https://github.com/warner/python-versioneer)
|
||||
|
||||
# these strings will be replaced by git during git-archive
|
||||
git_refnames = "$Format:%d$"
|
||||
git_full = "$Format:%H$"
|
||||
# versioneer-0.15+dev (https://github.com/warner/python-versioneer)
|
||||
|
||||
"""Git implementation of _version.py."""
|
||||
|
||||
import errno
|
||||
import os
|
||||
import re
|
||||
import subprocess
|
||||
import sys
|
||||
import errno
|
||||
|
||||
|
||||
def get_keywords():
|
||||
"""Get the keywords needed to look up the version information."""
|
||||
# these strings will be replaced by git during git-archive.
|
||||
# setup.py/versioneer.py will grep for the variable names, so they must
|
||||
# each be defined on a line of their own. _version.py will just call
|
||||
# get_keywords().
|
||||
git_refnames = "$Format:%d$"
|
||||
git_full = "$Format:%H$"
|
||||
keywords = {"refnames": git_refnames, "full": git_full}
|
||||
return keywords
|
||||
|
||||
|
||||
class VersioneerConfig:
|
||||
|
||||
"""Container for Versioneer configuration parameters."""
|
||||
|
||||
|
||||
def get_config():
|
||||
"""Create, populate and return the VersioneerConfig() object."""
|
||||
# these strings are filled in when 'setup.py versioneer' creates
|
||||
# _version.py
|
||||
cfg = VersioneerConfig()
|
||||
cfg.VCS = "git"
|
||||
cfg.style = "pep440"
|
||||
cfg.tag_prefix = ""
|
||||
cfg.parentdir_prefix = ""
|
||||
cfg.versionfile_source = "src/octoprint/_version.py"
|
||||
cfg.lookupfile = None
|
||||
cfg.verbose = False
|
||||
return cfg
|
||||
|
||||
|
||||
class NotThisMethod(Exception):
|
||||
|
||||
"""Exception raised if a method is not valid for the current scenario."""
|
||||
|
||||
|
||||
LONG_VERSION_PY = {}
|
||||
HANDLERS = {}
|
||||
|
||||
|
||||
def register_vcs_handler(vcs, method): # decorator
|
||||
"""Decorator to mark a method as the handler for a particular VCS."""
|
||||
def decorate(f):
|
||||
"""Store f in HANDLERS[vcs][method]."""
|
||||
if vcs not in HANDLERS:
|
||||
HANDLERS[vcs] = {}
|
||||
HANDLERS[vcs][method] = f
|
||||
return f
|
||||
return decorate
|
||||
|
||||
|
||||
def run_command(commands, args, cwd=None, verbose=False, hide_stderr=False):
|
||||
"""Call the given command(s)."""
|
||||
assert isinstance(commands, list)
|
||||
p = None
|
||||
for c in commands:
|
||||
try:
|
||||
dispcmd = str([c] + args)
|
||||
# remember shell=False, so use git.cmd on windows, not just git
|
||||
p = subprocess.Popen([c] + args, cwd=cwd, stdout=subprocess.PIPE,
|
||||
stderr=(subprocess.PIPE if hide_stderr
|
||||
@@ -33,7 +86,7 @@ def run_command(commands, args, cwd=None, verbose=False, hide_stderr=False):
|
||||
if e.errno == errno.ENOENT:
|
||||
continue
|
||||
if verbose:
|
||||
print("unable to run %s" % args[0])
|
||||
print("unable to run %s" % dispcmd)
|
||||
print(e)
|
||||
return None
|
||||
else:
|
||||
@@ -41,59 +94,67 @@ def run_command(commands, args, cwd=None, verbose=False, hide_stderr=False):
|
||||
print("unable to find command, tried %s" % (commands,))
|
||||
return None
|
||||
stdout = p.communicate()[0].strip()
|
||||
if sys.version >= '3':
|
||||
if sys.version_info[0] >= 3:
|
||||
stdout = stdout.decode()
|
||||
if p.returncode != 0:
|
||||
if verbose:
|
||||
print("unable to run %s (error)" % args[0])
|
||||
print("unable to run %s (error)" % dispcmd)
|
||||
return None
|
||||
return stdout
|
||||
|
||||
|
||||
import sys
|
||||
import re
|
||||
import os.path
|
||||
def versions_from_parentdir(parentdir_prefix, root, verbose):
|
||||
"""Try to determine the version from the parent directory name.
|
||||
|
||||
def get_gits(root, verbose=False):
|
||||
if not os.path.exists(os.path.join(root, ".git")):
|
||||
Source tarballs conventionally unpack into a directory that includes
|
||||
both the project name and a version string.
|
||||
"""
|
||||
dirname = os.path.basename(root)
|
||||
if not dirname.startswith(parentdir_prefix):
|
||||
if verbose:
|
||||
print("no .git in %s" % root)
|
||||
return None
|
||||
|
||||
GITS = ["git"]
|
||||
if sys.platform == "win32":
|
||||
GITS = ["git.cmd", "git.exe"]
|
||||
return GITS
|
||||
print("guessing rootdir is '%s', but '%s' doesn't start with "
|
||||
"prefix '%s'" % (root, dirname, parentdir_prefix))
|
||||
raise NotThisMethod("rootdir doesn't start with parentdir_prefix")
|
||||
return {"version": dirname[len(parentdir_prefix):],
|
||||
"full-revisionid": None,
|
||||
"dirty": False, "error": None}
|
||||
|
||||
|
||||
def get_expanded_variables(versionfile_abs):
|
||||
@register_vcs_handler("git", "get_keywords")
|
||||
def git_get_keywords(versionfile_abs):
|
||||
"""Extract version information from the given file."""
|
||||
# the code embedded in _version.py can just fetch the value of these
|
||||
# variables. When used from setup.py, we don't want to import
|
||||
# _version.py, so we do it with a regexp instead. This function is not
|
||||
# used from _version.py.
|
||||
variables = {}
|
||||
# keywords. When used from setup.py, we don't want to import _version.py,
|
||||
# so we do it with a regexp instead. This function is not used from
|
||||
# _version.py.
|
||||
keywords = {}
|
||||
try:
|
||||
f = open(versionfile_abs,"r")
|
||||
f = open(versionfile_abs, "r")
|
||||
for line in f.readlines():
|
||||
if line.strip().startswith("git_refnames ="):
|
||||
mo = re.search(r'=\s*"(.*)"', line)
|
||||
if mo:
|
||||
variables["refnames"] = mo.group(1)
|
||||
keywords["refnames"] = mo.group(1)
|
||||
if line.strip().startswith("git_full ="):
|
||||
mo = re.search(r'=\s*"(.*)"', line)
|
||||
if mo:
|
||||
variables["full"] = mo.group(1)
|
||||
keywords["full"] = mo.group(1)
|
||||
f.close()
|
||||
except EnvironmentError:
|
||||
pass
|
||||
return variables
|
||||
return keywords
|
||||
|
||||
def versions_from_expanded_variables(variables, tag_prefix, verbose=False):
|
||||
refnames = variables["refnames"].strip()
|
||||
|
||||
@register_vcs_handler("git", "keywords")
|
||||
def git_versions_from_keywords(keywords, tag_prefix, verbose):
|
||||
"""Get version information from git keywords."""
|
||||
if not keywords:
|
||||
raise NotThisMethod("no keywords at all, weird")
|
||||
refnames = keywords["refnames"].strip()
|
||||
if refnames.startswith("$Format"):
|
||||
if verbose:
|
||||
print("variables are unexpanded, not using")
|
||||
return {} # unexpanded, so not in an unpacked git-archive tarball
|
||||
print("keywords are unexpanded, not using")
|
||||
raise NotThisMethod("unexpanded keywords, not a git-archive tarball")
|
||||
refs = set([r.strip() for r in refnames.strip("()").split(",")])
|
||||
# starting in git-1.8.3, tags are listed as "tag: foo-1.0" instead of
|
||||
# just "foo-1.0". If we see a "tag: " prefix, prefer those.
|
||||
@@ -110,6 +171,15 @@ def versions_from_expanded_variables(variables, tag_prefix, verbose=False):
|
||||
tags = set([r for r in refs if re.search(r'\d', r)])
|
||||
if verbose:
|
||||
print("discarding '%s', no digits" % ",".join(refs-tags))
|
||||
|
||||
branches = [r for r in refs if not r.startswith(TAG)
|
||||
and r != "HEAD" and not r.startswith("refs/")]
|
||||
if verbose:
|
||||
print("likely branches: %s" % ",".join(sorted(branches)))
|
||||
branch = None
|
||||
if branches:
|
||||
branch = branches[0]
|
||||
|
||||
if verbose:
|
||||
print("likely tags: %s" % ",".join(sorted(tags)))
|
||||
for ref in sorted(tags):
|
||||
@@ -118,161 +188,473 @@ def versions_from_expanded_variables(variables, tag_prefix, verbose=False):
|
||||
r = ref[len(tag_prefix):]
|
||||
if verbose:
|
||||
print("picking %s" % r)
|
||||
return { "version": r,
|
||||
"full": variables["full"].strip() }
|
||||
# no suitable tags, so we use the full revision id
|
||||
|
||||
result = {"version": r,
|
||||
"full-revisionid": keywords["full"].strip(),
|
||||
"dirty": False, "error": None}
|
||||
if branch is not None:
|
||||
result["branch"] = branch
|
||||
return result
|
||||
# no suitable tags, so version is "0+unknown", but full hex is still there
|
||||
if verbose:
|
||||
print("no suitable tags, using full revision id")
|
||||
return { "version": variables["full"].strip(),
|
||||
"full": variables["full"].strip() }
|
||||
print("no suitable tags, using unknown + full revision id")
|
||||
return {"version": "0+unknown",
|
||||
"full-revisionid": keywords["full"].strip(),
|
||||
"dirty": False, "error": "no suitable tags"}
|
||||
|
||||
def versions_from_lookup(lookup, root, verbose=False):
|
||||
GITS = get_gits(root, verbose=verbose)
|
||||
if GITS is None:
|
||||
return {}
|
||||
|
||||
stdout = run_command(GITS, ["rev-parse", "--abbrev-ref", "HEAD"],
|
||||
cwd=root)
|
||||
if stdout is None:
|
||||
return {}
|
||||
@register_vcs_handler("git", "pieces_from_vcs")
|
||||
def git_pieces_from_vcs(tag_prefix, root, verbose, run_command=run_command):
|
||||
"""Get version from 'git describe' in the root of the source tree.
|
||||
|
||||
current_branch = stdout.strip()
|
||||
for matcher, tag, ref_commit in lookup:
|
||||
if matcher.match(current_branch):
|
||||
if tag is None or ref_commit is None:
|
||||
return {}
|
||||
|
||||
stdout = run_command(GITS, ["rev-list", "%s..HEAD" % ref_commit, "--count"], cwd=root)
|
||||
if stdout is None:
|
||||
return {}
|
||||
num_commits = stdout.strip()
|
||||
|
||||
stdout =run_command(GITS, ["rev-parse", "--short", "HEAD"], cwd=root)
|
||||
if stdout is None:
|
||||
return {}
|
||||
short_hash = stdout.strip()
|
||||
|
||||
stdout = run_command(GITS, ["describe", "--tags", "--dirty", "--always"], cwd=root)
|
||||
if stdout is None:
|
||||
return {}
|
||||
dirty = stdout.strip().endswith("-dirty")
|
||||
|
||||
stdout = run_command(GITS, ["rev-parse", "HEAD"], cwd=root)
|
||||
if stdout is None:
|
||||
return {}
|
||||
full = stdout.strip()
|
||||
|
||||
version = "%s-%s-g%s" % (tag, num_commits, short_hash)
|
||||
if dirty:
|
||||
version += "-dirty"
|
||||
full += "-dirty"
|
||||
return {"version": version, "full": full, "branch": current_branch}
|
||||
|
||||
return {}
|
||||
|
||||
def versions_from_vcs(tag_prefix, root, verbose=False):
|
||||
# this runs 'git' from the root of the source tree. This only gets called
|
||||
# if the git-archive 'subst' variables were *not* expanded, and
|
||||
# _version.py hasn't already been rewritten with a short version string,
|
||||
# meaning we're inside a checked out source tree.
|
||||
|
||||
GITS = get_gits(root, verbose=verbose)
|
||||
if GITS is None:
|
||||
return {}
|
||||
|
||||
stdout = run_command(GITS, ["describe", "--tags", "--dirty", "--always"],
|
||||
cwd=root)
|
||||
if stdout is None:
|
||||
return {}
|
||||
if not stdout.startswith(tag_prefix):
|
||||
This only gets called if the git-archive 'subst' keywords were *not*
|
||||
expanded, and _version.py hasn't already been rewritten with a short
|
||||
version string, meaning we're inside a checked out source tree.
|
||||
"""
|
||||
if not os.path.exists(os.path.join(root, ".git")):
|
||||
if verbose:
|
||||
print("tag '%s' doesn't start with prefix '%s'" % (stdout, tag_prefix))
|
||||
return {}
|
||||
tag = stdout[len(tag_prefix):]
|
||||
stdout = run_command(GITS, ["rev-parse", "HEAD"], cwd=root)
|
||||
if stdout is None:
|
||||
return {}
|
||||
full = stdout.strip()
|
||||
if tag.endswith("-dirty"):
|
||||
full += "-dirty"
|
||||
print("no .git in %s" % root)
|
||||
raise NotThisMethod("no .git directory")
|
||||
|
||||
GITS = ["git"]
|
||||
if sys.platform == "win32":
|
||||
GITS = ["git.cmd", "git.exe"]
|
||||
# if there is a tag matching tag_prefix, this yields TAG-NUM-gHEX[-dirty]
|
||||
# if there isn't one, this yields HEX[-dirty] (no NUM)
|
||||
describe_out = run_command(GITS, ["describe", "--tags", "--dirty",
|
||||
"--always", "--long",
|
||||
"--match", "%s*" % tag_prefix],
|
||||
cwd=root)
|
||||
# --long was added in git-1.5.5
|
||||
if describe_out is None:
|
||||
raise NotThisMethod("'git describe' failed")
|
||||
describe_out = describe_out.strip()
|
||||
full_out = run_command(GITS, ["rev-parse", "HEAD"], cwd=root)
|
||||
if full_out is None:
|
||||
raise NotThisMethod("'git rev-parse' failed")
|
||||
full_out = full_out.strip()
|
||||
|
||||
pieces = {}
|
||||
pieces["long"] = full_out
|
||||
pieces["short"] = full_out[:7] # maybe improved later
|
||||
pieces["error"] = None
|
||||
|
||||
# parse describe_out. It will be like TAG-NUM-gHEX[-dirty] or HEX[-dirty]
|
||||
# TAG might have hyphens.
|
||||
git_describe = describe_out
|
||||
|
||||
# look for -dirty suffix
|
||||
dirty = git_describe.endswith("-dirty")
|
||||
pieces["dirty"] = dirty
|
||||
if dirty:
|
||||
git_describe = git_describe[:git_describe.rindex("-dirty")]
|
||||
|
||||
# figure out our branch
|
||||
abbrev_ref_out = run_command(GITS,
|
||||
["rev-parse", "--abbrev-ref", "HEAD"],
|
||||
cwd=root)
|
||||
if abbrev_ref_out is not None:
|
||||
pieces["branch"] = abbrev_ref_out.strip()
|
||||
|
||||
# now we have TAG-NUM-gHEX or HEX
|
||||
|
||||
if "-" in git_describe:
|
||||
# TAG-NUM-gHEX
|
||||
mo = re.search(r'^(.+)-(\d+)-g([0-9a-f]+)$', git_describe)
|
||||
if not mo:
|
||||
# unparseable. Maybe git-describe is misbehaving?
|
||||
pieces["error"] = ("unable to parse git-describe output: '%s'"
|
||||
% describe_out)
|
||||
return pieces
|
||||
|
||||
# tag
|
||||
full_tag = mo.group(1)
|
||||
if not full_tag.startswith(tag_prefix):
|
||||
if verbose:
|
||||
fmt = "tag '%s' doesn't start with prefix '%s'"
|
||||
print(fmt % (full_tag, tag_prefix))
|
||||
pieces["error"] = ("tag '%s' doesn't start with prefix '%s'"
|
||||
% (full_tag, tag_prefix))
|
||||
return pieces
|
||||
pieces["closest-tag"] = full_tag[len(tag_prefix):]
|
||||
|
||||
# distance: number of commits since tag
|
||||
pieces["distance"] = int(mo.group(2))
|
||||
|
||||
# commit: short hex revision ID
|
||||
pieces["short"] = mo.group(3)
|
||||
|
||||
stdout = run_command(GITS, ["rev-parse", "--abbrev-ref", "HEAD"],
|
||||
cwd=root)
|
||||
if stdout is None:
|
||||
branch = None
|
||||
else:
|
||||
branch = stdout.strip()
|
||||
return {"version": tag, "full": full, "branch": branch}
|
||||
# HEX: no tags
|
||||
pieces["closest-tag"] = None
|
||||
count_out = run_command(GITS, ["rev-list", "HEAD", "--count"],
|
||||
cwd=root)
|
||||
pieces["distance"] = int(count_out) # total number of commits
|
||||
|
||||
return pieces
|
||||
|
||||
|
||||
def versions_from_parentdir(parentdir_prefix, root, verbose=False):
|
||||
# Source tarballs conventionally unpack into a directory that includes
|
||||
# both the project name and a version string.
|
||||
dirname = os.path.basename(root)
|
||||
if not dirname.startswith(parentdir_prefix):
|
||||
if verbose:
|
||||
print("guessing rootdir is '%s', but '%s' doesn't start with prefix '%s'" %
|
||||
(root, dirname, parentdir_prefix))
|
||||
return None
|
||||
return {"version": dirname[len(parentdir_prefix):], "full": "", "branch": ""}
|
||||
@register_vcs_handler("git", "parse_lookup_file")
|
||||
def git_parse_lookup_file(path):
|
||||
"""Parse a versioneer lookup file.
|
||||
|
||||
tag_prefix = ""
|
||||
parentdir_prefix = ""
|
||||
versionfile_source = "src/octoprint/_version.py"
|
||||
lookupfile = ".versioneer-lookup"
|
||||
|
||||
def parse_lookup_file(root, lookup_path=None):
|
||||
if not lookup_path:
|
||||
lookup_path = lookupfile
|
||||
if not lookup_path:
|
||||
return []
|
||||
|
||||
path = os.path.join(root, lookup_path)
|
||||
This file allows definition of branch specific data like virtual tags or
|
||||
custom styles to use for version rendering.
|
||||
"""
|
||||
if not os.path.exists(path):
|
||||
return []
|
||||
|
||||
import re
|
||||
lookup = []
|
||||
with open(os.path.join(root, lookup_path), "r") as f:
|
||||
with open(path, "r") as f:
|
||||
for line in f:
|
||||
if '#' in line:
|
||||
line = line[:line.rindex('#')]
|
||||
line = line[:line.rindex("#")]
|
||||
line = line.strip()
|
||||
if not line:
|
||||
continue
|
||||
|
||||
try:
|
||||
split_line = line.split()
|
||||
if len(split_line) == 3:
|
||||
pattern, tag, ref_commit = split_line
|
||||
lookup.append([re.compile(pattern), tag, ref_commit])
|
||||
elif len(split_line) >= 1:
|
||||
lookup.append([re.compile(split_line[0]), None, None])
|
||||
split_line = map(lambda x: x.strip(), line.split())
|
||||
if not len(split_line):
|
||||
continue
|
||||
|
||||
matcher = re.compile(split_line[0])
|
||||
|
||||
if len(split_line) == 1:
|
||||
entry = [matcher, None, None, None]
|
||||
elif len(split_line) == 2:
|
||||
render = split_line[1]
|
||||
entry = [matcher, render, None, None]
|
||||
elif len(split_line) == 3:
|
||||
tag, ref_commit = split_line[1:]
|
||||
entry = [matcher, None, tag, ref_commit]
|
||||
elif len(split_line) == 4:
|
||||
tag, ref_commit, render = split_line[1:]
|
||||
entry = [matcher, render, tag, ref_commit]
|
||||
else:
|
||||
continue
|
||||
|
||||
lookup.append(entry)
|
||||
except:
|
||||
break
|
||||
return lookup
|
||||
|
||||
def get_versions(default={"version": "unknown", "full": "", "branch": "unknown"}, lookup_path=None, verbose=False):
|
||||
|
||||
@register_vcs_handler("git", "pieces_from_lookup")
|
||||
def git_pieces_from_lookup(lookup, root, verbose, run_command=run_command):
|
||||
"""Extract version information based on provided lookup data."""
|
||||
GITS = ["git"]
|
||||
if sys.platform == "win32":
|
||||
GITS = ["git.cmd", "git.exe"]
|
||||
|
||||
stdout = run_command(GITS, ["rev-parse", "--abbrev-ref", "HEAD"],
|
||||
cwd=root)
|
||||
if stdout is None:
|
||||
raise NotThisMethod("git rev-parse --abbrev-ref HEAD failed")
|
||||
|
||||
current_branch = stdout.strip()
|
||||
for matcher, render, tag, ref_commit in lookup:
|
||||
if matcher.match(current_branch):
|
||||
if tag is None or ref_commit is None:
|
||||
raise NotThisMethod("tag or ref_commit is unset for "
|
||||
"this branch")
|
||||
|
||||
stdout = run_command(GITS,
|
||||
["rev-list", "%s..HEAD" % ref_commit,
|
||||
"--count"],
|
||||
cwd=root)
|
||||
if stdout is None:
|
||||
raise NotThisMethod("git rev-list %s..HEAD "
|
||||
"--count failed" % ref_commit)
|
||||
try:
|
||||
num_commits = int(stdout.strip())
|
||||
except ValueError:
|
||||
raise NotThisMethod("git rev-list %s..HEAD --count didn't "
|
||||
"return a valid number" % ref_commit)
|
||||
|
||||
stdout = run_command(GITS,
|
||||
["rev-parse", "--short", "HEAD"],
|
||||
cwd=root)
|
||||
if stdout is None:
|
||||
raise NotThisMethod("git describe rev-parse "
|
||||
"--short HEAD failed")
|
||||
short_hash = stdout.strip()
|
||||
|
||||
stdout = run_command(GITS,
|
||||
["describe", "--tags",
|
||||
"--dirty", "--always"],
|
||||
cwd=root)
|
||||
if stdout is None:
|
||||
raise NotThisMethod("git describe --tags --dirty "
|
||||
"--always failed")
|
||||
dirty = stdout.strip().endswith("-dirty")
|
||||
|
||||
stdout = run_command(GITS, ["rev-parse", "HEAD"], cwd=root)
|
||||
if stdout is None:
|
||||
raise NotThisMethod("git rev-parse HEAD failed")
|
||||
full = stdout.strip()
|
||||
|
||||
return {
|
||||
"long": full,
|
||||
"short": short_hash,
|
||||
"dirty": dirty,
|
||||
"branch": current_branch,
|
||||
"closest-tag": tag,
|
||||
"distance": num_commits,
|
||||
"error": None,
|
||||
"render": render
|
||||
}
|
||||
|
||||
raise NotThisMethod("no matching lookup definition found")
|
||||
|
||||
|
||||
def plus_or_dot(pieces):
|
||||
"""Return a + if we don't already have one, else return a ."""
|
||||
if "+" in pieces.get("closest-tag", ""):
|
||||
return "."
|
||||
return "+"
|
||||
|
||||
|
||||
def render_pep440(pieces):
|
||||
"""Build up version string, with post-release "local version identifier".
|
||||
|
||||
Our goal: TAG[+DISTANCE.gHEX[.dirty]] . Note that if you
|
||||
get a tagged build and then dirty it, you'll get TAG+0.gHEX.dirty
|
||||
|
||||
Exceptions:
|
||||
1: no tags. git_describe was just HEX. 0+untagged.DISTANCE.gHEX[.dirty]
|
||||
"""
|
||||
if pieces["closest-tag"]:
|
||||
rendered = pieces["closest-tag"]
|
||||
if pieces["distance"] or pieces["dirty"]:
|
||||
rendered += plus_or_dot(pieces)
|
||||
rendered += "%d.g%s" % (pieces["distance"], pieces["short"])
|
||||
if pieces["dirty"]:
|
||||
rendered += ".dirty"
|
||||
else:
|
||||
# exception #1
|
||||
rendered = "0+untagged.%d.g%s" % (pieces["distance"],
|
||||
pieces["short"])
|
||||
if pieces["dirty"]:
|
||||
rendered += ".dirty"
|
||||
return rendered
|
||||
|
||||
|
||||
def render_pep440_pre(pieces):
|
||||
"""TAG[.post.devDISTANCE] -- No -dirty.
|
||||
|
||||
Exceptions:
|
||||
1: no tags. 0.post.devDISTANCE
|
||||
"""
|
||||
if pieces["closest-tag"]:
|
||||
rendered = pieces["closest-tag"]
|
||||
if pieces["distance"]:
|
||||
rendered += ".post.dev%d" % pieces["distance"]
|
||||
else:
|
||||
# exception #1
|
||||
rendered = "0.post.dev%d" % pieces["distance"]
|
||||
return rendered
|
||||
|
||||
|
||||
def render_pep440_post(pieces):
|
||||
"""TAG[.postDISTANCE[.dev0]+gHEX] .
|
||||
|
||||
The ".dev0" means dirty. Note that .dev0 sorts backwards
|
||||
(a dirty tree will appear "older" than the corresponding clean one),
|
||||
but you shouldn't be releasing software with -dirty anyways.
|
||||
|
||||
Exceptions:
|
||||
1: no tags. 0.postDISTANCE[.dev0]
|
||||
"""
|
||||
if pieces["closest-tag"]:
|
||||
rendered = pieces["closest-tag"]
|
||||
if pieces["distance"] or pieces["dirty"]:
|
||||
rendered += ".post%d" % pieces["distance"]
|
||||
if pieces["dirty"]:
|
||||
rendered += ".dev0"
|
||||
rendered += plus_or_dot(pieces)
|
||||
rendered += "g%s" % pieces["short"]
|
||||
else:
|
||||
# exception #1
|
||||
rendered = "0.post%d" % pieces["distance"]
|
||||
if pieces["dirty"]:
|
||||
rendered += ".dev0"
|
||||
rendered += "+g%s" % pieces["short"]
|
||||
return rendered
|
||||
|
||||
|
||||
def render_pep440_dev(pieces):
|
||||
"""TAG[.devDISTANCE]+gHEX[.dirty] .
|
||||
|
||||
Exceptions:
|
||||
1: no tags. 0.devDISTANCE+gHEX[.dirty]
|
||||
"""
|
||||
if pieces["closest-tag"]:
|
||||
rendered = pieces["closest-tag"]
|
||||
if pieces["distance"]:
|
||||
rendered += ".dev%d" % pieces["distance"]
|
||||
rendered += plus_or_dot(pieces)
|
||||
else:
|
||||
# exception #1
|
||||
rendered = "0.dev%d" % pieces["distance"]
|
||||
rendered += "+"
|
||||
rendered += "g%s" % pieces["short"]
|
||||
if pieces["dirty"]:
|
||||
rendered += ".dirty"
|
||||
return rendered
|
||||
|
||||
|
||||
def render_pep440_old(pieces):
|
||||
"""TAG[.postDISTANCE[.dev0]] .
|
||||
|
||||
The ".dev0" means dirty.
|
||||
|
||||
Eexceptions:
|
||||
1: no tags. 0.postDISTANCE[.dev0]
|
||||
"""
|
||||
if pieces["closest-tag"]:
|
||||
rendered = pieces["closest-tag"]
|
||||
if pieces["distance"] or pieces["dirty"]:
|
||||
rendered += ".post%d" % pieces["distance"]
|
||||
if pieces["dirty"]:
|
||||
rendered += ".dev0"
|
||||
else:
|
||||
# exception #1
|
||||
rendered = "0.post%d" % pieces["distance"]
|
||||
if pieces["dirty"]:
|
||||
rendered += ".dev0"
|
||||
return rendered
|
||||
|
||||
|
||||
def render_git_describe(pieces):
|
||||
"""TAG[-DISTANCE-gHEX][-dirty].
|
||||
|
||||
Like 'git describe --tags --dirty --always'.
|
||||
|
||||
Exceptions:
|
||||
1: no tags. HEX[-dirty] (note: no 'g' prefix)
|
||||
"""
|
||||
if pieces["closest-tag"]:
|
||||
rendered = pieces["closest-tag"]
|
||||
if pieces["distance"]:
|
||||
rendered += "-%d-g%s" % (pieces["distance"], pieces["short"])
|
||||
else:
|
||||
# exception #1
|
||||
rendered = pieces["short"]
|
||||
if pieces["dirty"]:
|
||||
rendered += "-dirty"
|
||||
return rendered
|
||||
|
||||
|
||||
def render_git_describe_long(pieces):
|
||||
"""TAG-DISTANCE-gHEX[-dirty].
|
||||
|
||||
Like 'git describe --tags --dirty --always -long'.
|
||||
The distance/hash is unconditional.
|
||||
|
||||
Exceptions:
|
||||
1: no tags. HEX[-dirty] (note: no 'g' prefix)
|
||||
"""
|
||||
if pieces["closest-tag"]:
|
||||
rendered = pieces["closest-tag"]
|
||||
rendered += "-%d-g%s" % (pieces["distance"], pieces["short"])
|
||||
else:
|
||||
# exception #1
|
||||
rendered = pieces["short"]
|
||||
if pieces["dirty"]:
|
||||
rendered += "-dirty"
|
||||
return rendered
|
||||
|
||||
|
||||
def render(pieces, style):
|
||||
"""Render the given version pieces into the requested style."""
|
||||
if pieces["error"]:
|
||||
return {"version": "unknown",
|
||||
"full-revisionid": pieces.get("long"),
|
||||
"dirty": None,
|
||||
"error": pieces["error"]}
|
||||
|
||||
if "render" in pieces and pieces["render"] is not None:
|
||||
style = pieces["render"]
|
||||
|
||||
if not style or style == "default":
|
||||
style = "pep440" # the default
|
||||
|
||||
if style == "pep440":
|
||||
rendered = render_pep440(pieces)
|
||||
elif style == "pep440-pre":
|
||||
rendered = render_pep440_pre(pieces)
|
||||
elif style == "pep440-post":
|
||||
rendered = render_pep440_post(pieces)
|
||||
elif style == "pep440-old":
|
||||
rendered = render_pep440_old(pieces)
|
||||
elif style == "pep440-dev":
|
||||
rendered = render_pep440_dev(pieces)
|
||||
elif style == "git-describe":
|
||||
rendered = render_git_describe(pieces)
|
||||
elif style == "git-describe-long":
|
||||
rendered = render_git_describe_long(pieces)
|
||||
else:
|
||||
raise ValueError("unknown style '%s'" % style)
|
||||
|
||||
result = {"version": rendered, "full-revisionid": pieces["long"],
|
||||
"dirty": pieces["dirty"], "error": None}
|
||||
if "branch" in pieces and pieces["branch"] is not None:
|
||||
result["branch"] = pieces["branch"]
|
||||
return result
|
||||
|
||||
|
||||
def get_versions():
|
||||
"""Get version information or return default if unable to do so."""
|
||||
# I am in _version.py, which lives at ROOT/VERSIONFILE_SOURCE. If we have
|
||||
# __file__, we can work backwards from there to the root. Some
|
||||
# py2exe/bbfreeze/non-CPython implementations don't do __file__, in which
|
||||
# case we can only use expanded variables.
|
||||
# case we can only use expanded keywords.
|
||||
|
||||
variables = { "refnames": git_refnames, "full": git_full }
|
||||
ver = versions_from_expanded_variables(variables, tag_prefix, verbose)
|
||||
if ver:
|
||||
return ver
|
||||
cfg = get_config()
|
||||
verbose = cfg.verbose
|
||||
|
||||
try:
|
||||
root = os.path.abspath(__file__)
|
||||
return git_versions_from_keywords(get_keywords(), cfg.tag_prefix,
|
||||
verbose)
|
||||
except NotThisMethod:
|
||||
pass
|
||||
|
||||
try:
|
||||
root = os.path.realpath(__file__)
|
||||
# versionfile_source is the relative path from the top of the source
|
||||
# tree (where the .git directory might live) to this file. Invert
|
||||
# this to find the root from __file__.
|
||||
for i in range(len(versionfile_source.split("/"))):
|
||||
for i in cfg.versionfile_source.split('/'):
|
||||
root = os.path.dirname(root)
|
||||
except NameError:
|
||||
return default
|
||||
return {"version": "0+unknown", "full-revisionid": None,
|
||||
"dirty": None,
|
||||
"error": "unable to find root of source tree"}
|
||||
|
||||
lookup = parse_lookup_file(root, lookup_path=lookup_path)
|
||||
return (versions_from_lookup(lookup, root, verbose)
|
||||
or versions_from_vcs(tag_prefix, root, verbose)
|
||||
or versions_from_parentdir(parentdir_prefix, root, verbose)
|
||||
or default)
|
||||
lookupfile = cfg.lookupfile if cfg.lookupfile is not None else ".versioneer-lookup"
|
||||
lookuppath = os.path.join(root, lookupfile)
|
||||
if os.path.exists(lookuppath):
|
||||
try:
|
||||
lookup_data = git_parse_lookup_file(lookuppath)
|
||||
pieces = git_pieces_from_lookup(lookup_data, root, verbose)
|
||||
return render(pieces, cfg.style)
|
||||
except NotThisMethod:
|
||||
pass
|
||||
|
||||
try:
|
||||
pieces = git_pieces_from_vcs(cfg.tag_prefix, root, verbose)
|
||||
return render(pieces, cfg.style)
|
||||
except NotThisMethod:
|
||||
pass
|
||||
|
||||
try:
|
||||
if cfg.parentdir_prefix:
|
||||
return versions_from_parentdir(cfg.parentdir_prefix, root, verbose)
|
||||
except NotThisMethod:
|
||||
pass
|
||||
|
||||
return {"version": "0+unknown", "full-revisionid": None,
|
||||
"dirty": None,
|
||||
"error": "unable to compute version"}
|
||||
@@ -13,6 +13,8 @@ import tempfile
|
||||
|
||||
import octoprint.filemanager
|
||||
|
||||
from octoprint.util import is_hidden_path
|
||||
|
||||
class StorageInterface(object):
|
||||
"""
|
||||
Interface of storage adapters for OctoPrint.
|
||||
@@ -357,7 +359,7 @@ class LocalFileStorage(StorageInterface):
|
||||
if not metadata:
|
||||
metadata = dict()
|
||||
for entry in os.listdir(path):
|
||||
if entry.startswith(".") or not octoprint.filemanager.valid_file_type(entry):
|
||||
if is_hidden_path(entry) or not octoprint.filemanager.valid_file_type(entry):
|
||||
continue
|
||||
|
||||
absolute_path = os.path.join(path, entry)
|
||||
@@ -584,24 +586,6 @@ class LocalFileStorage(StorageInterface):
|
||||
Note that for a ``path`` without a trailing slash the last part will be considered a file name and
|
||||
hence be returned at second position. If you only need to convert a folder path, be sure to
|
||||
include a trailing slash for a string ``path`` or an empty last element for a list ``path``.
|
||||
|
||||
Examples::
|
||||
|
||||
>>> storage = LocalFileStorage("/some/base/folder")
|
||||
>>> storage.sanitize("some/folder/and/some file.gco")
|
||||
("/some/base/folder/some/folder/and", "some_file.gco")
|
||||
>>> storage.sanitize(("some", "folder", "and", "some file.gco"))
|
||||
("/some/base/folder/some/folder/and", "some_file.gco")
|
||||
>>> storage.sanitize("some file.gco")
|
||||
("/some/base/folder", "some_file.gco")
|
||||
>>> storage.sanitize(("some file.gco",))
|
||||
("/some/base/folder", "some_file.gco")
|
||||
>>> storage.sanitize("")
|
||||
("/some/base/folder", "")
|
||||
>>> storage.sanitize("some/folder/with/trailing/slash/")
|
||||
("/some/base/folder/some/folder/with/trailing/slash", "")
|
||||
>>> storage.sanitize("some", "folder", "")
|
||||
("/some/base/folder/some/folder", "")
|
||||
"""
|
||||
name = None
|
||||
if isinstance(path, (str, unicode, basestring)):
|
||||
@@ -628,24 +612,6 @@ class LocalFileStorage(StorageInterface):
|
||||
Raises a :class:`ValueError` for a ``name`` containing ``/`` or ``\``. Otherwise strips any characters from the
|
||||
given ``name`` that are not any of the ASCII characters, digits, ``-``, ``_``, ``.``, ``(``, ``)`` or space and
|
||||
replaces and spaces with ``_``.
|
||||
|
||||
Examples::
|
||||
|
||||
>>> storage = LocalFileStorage("/some/base/folder")
|
||||
>>> storage.sanitize_name("some_file.gco")
|
||||
"some_file.gco"
|
||||
>>> storage.sanitize_name("some_file with (parentheses) and ümläuts and digits 123.gco")
|
||||
"some_file_with_(parentheses)_and_mluts_and_digits_123.gco"
|
||||
>>> storage.sanitize_name("pengüino pequeño.stl")
|
||||
"pengino_pequeo.stl"
|
||||
>>> storage.sanitize_name("some/folder/still/left.gco")
|
||||
Traceback (most recent call last):
|
||||
File "<stdin>", line 1, in <module>
|
||||
ValueError: name must not contain / or \
|
||||
>>> storage.sanitize_name("also\\no\\backslashes.gco")
|
||||
Traceback (most recent call last):
|
||||
File "<stdin>", line 1, in <module>
|
||||
ValueError: name must not contain / or \
|
||||
"""
|
||||
if name is None:
|
||||
return None
|
||||
@@ -664,22 +630,6 @@ class LocalFileStorage(StorageInterface):
|
||||
Ensures that the on disk representation of ``path`` is located under the configured basefolder. Resolves all
|
||||
relative path elements (e.g. ``..``) and sanitizes folder names using :func:`sanitize_name`. Final path is the
|
||||
absolute path including leading ``basefolder`` path.
|
||||
|
||||
Examples::
|
||||
|
||||
>>> storage = LocalFileStorage("/some/base/folder")
|
||||
>>> storage.sanitize_path("folder/with/subfolder")
|
||||
"/some/base/folder/folder/with/subfolder"
|
||||
>>> storage.sanitize_path("folder/with/subfolder/../other/folder")
|
||||
"/some/base/folder/folder/with/other/folder"
|
||||
>>> storage.sanitize_path("/folder/with/leading/slash")
|
||||
"/some/base/folder/folder/with/leading/slash"
|
||||
>>> storage.sanitize_path(".folder/with/leading/dot")
|
||||
"/some/base/folder/folder/with/leading/dot
|
||||
>>> storage.sanitize_path("../../folder/out/of/the/basefolder")
|
||||
Traceback (most recent call last):
|
||||
File "<stdin>", line 1, in <module>
|
||||
ValueError: path not contained in base folder: /some/folder/out/of/the/basefolder
|
||||
"""
|
||||
if path[0] == "/" or path[0] == ".":
|
||||
path = path[1:]
|
||||
@@ -939,7 +889,7 @@ class LocalFileStorage(StorageInterface):
|
||||
|
||||
result = dict()
|
||||
for entry in os.listdir(path):
|
||||
if entry.startswith("."):
|
||||
if is_hidden_path(entry):
|
||||
# no hidden files and folders
|
||||
continue
|
||||
|
||||
|
||||
@@ -293,19 +293,16 @@ class PluginSettings(object):
|
||||
self.set_preprocessors = dict(plugins=dict())
|
||||
self.set_preprocessors["plugins"][plugin_key] = set_preprocessors
|
||||
|
||||
def prefix_path(path):
|
||||
return ['plugins', self.plugin_key] + path
|
||||
|
||||
def prefix_path_in_args(args, index=0):
|
||||
result = []
|
||||
if index == 0:
|
||||
result.append(prefix_path(args[0]))
|
||||
result.append(self._prefix_path(args[0]))
|
||||
result.extend(args[1:])
|
||||
else:
|
||||
args_before = args[:index - 1]
|
||||
args_after = args[index + 1:]
|
||||
result.extend(args_before)
|
||||
result.append(prefix_path(args[index]))
|
||||
result.append(self._prefix_path(args[index]))
|
||||
result.extend(args_after)
|
||||
return result
|
||||
|
||||
@@ -324,6 +321,7 @@ class PluginSettings(object):
|
||||
return kwargs
|
||||
|
||||
self.access_methods = dict(
|
||||
has =("has", prefix_path_in_args, add_getter_kwargs),
|
||||
get =("get", prefix_path_in_args, add_getter_kwargs),
|
||||
get_int =("getInt", prefix_path_in_args, add_getter_kwargs),
|
||||
get_float =("getFloat", prefix_path_in_args, add_getter_kwargs),
|
||||
@@ -331,7 +329,8 @@ class PluginSettings(object):
|
||||
set =("set", prefix_path_in_args, add_setter_kwargs),
|
||||
set_int =("setInt", prefix_path_in_args, add_setter_kwargs),
|
||||
set_float =("setFloat", prefix_path_in_args, add_setter_kwargs),
|
||||
set_boolean=("setBoolean", prefix_path_in_args, add_setter_kwargs)
|
||||
set_boolean=("setBoolean", prefix_path_in_args, add_setter_kwargs),
|
||||
remove =("remove", prefix_path_in_args)
|
||||
)
|
||||
self.deprecated_access_methods = dict(
|
||||
getInt ="get_int",
|
||||
@@ -342,6 +341,17 @@ class PluginSettings(object):
|
||||
setBoolean="set_boolean"
|
||||
)
|
||||
|
||||
def _prefix_path(self, path=None):
|
||||
if path is None:
|
||||
path = list()
|
||||
return ['plugins', self.plugin_key] + path
|
||||
|
||||
def global_has(self, path, **kwargs):
|
||||
return self.settings.has(path, **kwargs)
|
||||
|
||||
def global_remove(self, path, **kwargs):
|
||||
return self.settings.remove(path, **kwargs)
|
||||
|
||||
def global_get(self, path, **kwargs):
|
||||
"""
|
||||
Getter for retrieving settings not managed by the plugin itself from the core settings structure. Use this
|
||||
@@ -435,6 +445,24 @@ class PluginSettings(object):
|
||||
os.makedirs(path)
|
||||
return path
|
||||
|
||||
def get_all_data(self, **kwargs):
|
||||
merged = kwargs.get("merged", True)
|
||||
asdict = kwargs.get("asdict", True)
|
||||
defaults = kwargs.get("defaults", self.defaults)
|
||||
preprocessors = kwargs.get("preprocessors", self.get_preprocessors)
|
||||
|
||||
kwargs.update(dict(
|
||||
merged=merged,
|
||||
asdict=asdict,
|
||||
defaults=defaults,
|
||||
preprocessors=preprocessors
|
||||
))
|
||||
|
||||
return self.settings.get(self._prefix_path(), **kwargs)
|
||||
|
||||
def clean_all_data(self):
|
||||
self.settings.remove(self._prefix_path())
|
||||
|
||||
def __getattr__(self, item):
|
||||
all_access_methods = self.access_methods.keys() + self.deprecated_access_methods.keys()
|
||||
if item in all_access_methods:
|
||||
|
||||
@@ -651,6 +651,24 @@ class BlueprintPlugin(OctoPrintPlugin, RestartNeedingPlugin):
|
||||
return f
|
||||
return decorator
|
||||
|
||||
@staticmethod
|
||||
def errorhandler(code_or_exception):
|
||||
"""
|
||||
A decorator to mark errorhandlings methods in your BlueprintPlugin subclass. Works just the same as Flask's
|
||||
own ``errorhandler`` decorator available on blueprints.
|
||||
|
||||
See `the documentation for flask.Blueprint.errorhandler <http://flask.pocoo.org/docs/0.10/api/#flask.Blueprint.errorhandler>`_
|
||||
and `the documentation for flask.Flask.errorhandler <http://flask.pocoo.org/docs/0.10/api/#flask.Flask.errorhandler>`_ for more
|
||||
information.
|
||||
"""
|
||||
from collections import defaultdict
|
||||
def decorator(f):
|
||||
if not hasattr(f, "_blueprint_error_handler") or f._blueprint_error_handler is None:
|
||||
f._blueprint_error_handler = defaultdict(list)
|
||||
f._blueprint_error_handler[f.__name__].append(code_or_exception)
|
||||
return f
|
||||
return decorator
|
||||
|
||||
def get_blueprint(self):
|
||||
"""
|
||||
Creates and returns the blueprint for your plugin. Override this if you want to define and handle your blueprint yourself.
|
||||
@@ -660,15 +678,34 @@ class BlueprintPlugin(OctoPrintPlugin, RestartNeedingPlugin):
|
||||
:return: the blueprint ready to be registered with Flask
|
||||
"""
|
||||
|
||||
if hasattr(self, "_blueprint"):
|
||||
# if we already constructed the blueprint and hence have it cached,
|
||||
# return that instance - we don't want to instance it multiple times
|
||||
return self._blueprint
|
||||
|
||||
import flask
|
||||
kwargs = self.get_blueprint_kwargs()
|
||||
blueprint = flask.Blueprint("plugin." + self._identifier, self._identifier, **kwargs)
|
||||
|
||||
# we now iterate over all members of ourselves and look if we find an attribute
|
||||
# that has data originating from one of our decorators - we ignore anything
|
||||
# starting with a _ to only handle public stuff
|
||||
for member in [member for member in dir(self) if not member.startswith("_")]:
|
||||
f = getattr(self, member)
|
||||
|
||||
if hasattr(f, "_blueprint_rules") and member in f._blueprint_rules:
|
||||
# this attribute was annotated with our @route decorator
|
||||
for blueprint_rule in f._blueprint_rules[member]:
|
||||
rule, options = blueprint_rule
|
||||
blueprint.add_url_rule(rule, options.pop("endpoint", f.__name__), view_func=f, **options)
|
||||
|
||||
if hasattr(f, "_blueprint_error_handler") and member in f._blueprint_error_handler:
|
||||
# this attribute was annotated with our @error_handler decorator
|
||||
for code_or_exception in f._blueprint_error_handler[member]:
|
||||
blueprint.errorhandler(code_or_exception)(f)
|
||||
|
||||
# cache and return the blueprint object
|
||||
self._blueprint = blueprint
|
||||
return blueprint
|
||||
|
||||
def get_blueprint_kwargs(self):
|
||||
@@ -764,6 +801,9 @@ class SettingsPlugin(OctoPrintPlugin):
|
||||
the plugin core system upon initialization of the implementation.
|
||||
"""
|
||||
|
||||
config_version_key = "_config_version"
|
||||
"""Key of the field in the settings that holds the configuration format version."""
|
||||
|
||||
def on_settings_load(self):
|
||||
"""
|
||||
Loads the settings for the plugin, called by the Settings API view in order to retrieve all settings from
|
||||
@@ -781,9 +821,9 @@ class SettingsPlugin(OctoPrintPlugin):
|
||||
|
||||
:return: the current settings of the plugin, as a dictionary
|
||||
"""
|
||||
data = self._settings.get([], asdict=True, merged=True)
|
||||
if "_config_version" in data:
|
||||
del data["_config_version"]
|
||||
data = self._settings.get_all_data()
|
||||
if self.config_version_key in data:
|
||||
del data[self.config_version_key]
|
||||
return data
|
||||
|
||||
def on_settings_save(self, data):
|
||||
@@ -795,7 +835,8 @@ class SettingsPlugin(OctoPrintPlugin):
|
||||
.. note::
|
||||
|
||||
The default implementation will persist your plugin's settings as is, so just in the structure and in the
|
||||
types that were received by the Settings API view.
|
||||
types that were received by the Settings API view. Values identical to the default settings values
|
||||
will *not* be persisted.
|
||||
|
||||
If you need more granular control here, e.g. over the used data types, you'll need to override this method
|
||||
and iterate yourself over all your settings, retrieving them (if set) from the supplied received ``data``
|
||||
@@ -803,15 +844,38 @@ class SettingsPlugin(OctoPrintPlugin):
|
||||
|
||||
Arguments:
|
||||
data (dict): The settings dictionary to be saved for the plugin
|
||||
|
||||
Returns:
|
||||
dict: The settings that differed from the defaults and were actually saved.
|
||||
"""
|
||||
import octoprint.util
|
||||
|
||||
if "_config_version" in data:
|
||||
del data["_config_version"]
|
||||
# get the current data
|
||||
current = self._settings.get_all_data()
|
||||
if current is None:
|
||||
current = dict()
|
||||
|
||||
current = self._settings.get([], asdict=True, merged=True)
|
||||
merged = octoprint.util.dict_merge(current, data)
|
||||
self._settings.set([], merged)
|
||||
# merge our new data on top of it
|
||||
new_current = octoprint.util.dict_merge(current, data)
|
||||
if self.config_version_key in new_current:
|
||||
del new_current[self.config_version_key]
|
||||
|
||||
# determine diff dict that contains minimal set of changes against the
|
||||
# default settings - we only want to persist that, not everything
|
||||
diff = octoprint.util.dict_minimal_mergediff(self.get_settings_defaults(), new_current)
|
||||
|
||||
version = self.get_settings_version()
|
||||
|
||||
to_persist = dict(diff)
|
||||
if version:
|
||||
to_persist[self.config_version_key] = version
|
||||
|
||||
if to_persist:
|
||||
self._settings.set([], to_persist)
|
||||
else:
|
||||
self._settings.clean_all_data()
|
||||
|
||||
return diff
|
||||
|
||||
def get_settings_defaults(self):
|
||||
"""
|
||||
@@ -894,6 +958,49 @@ class SettingsPlugin(OctoPrintPlugin):
|
||||
"""
|
||||
pass
|
||||
|
||||
def on_settings_cleanup(self):
|
||||
"""
|
||||
Called after migration and initialization but before call to :func:`on_settings_initialized`.
|
||||
|
||||
Plugins may overwrite this method to perform additional clean up tasks.
|
||||
|
||||
The default implementation just minimizes the data persisted on disk to only contain
|
||||
the differences to the defaults (in case the current data was persisted with an older
|
||||
version of OctoPrint that still duplicated default data).
|
||||
"""
|
||||
import octoprint.util
|
||||
from octoprint.settings import NoSuchSettingsPath
|
||||
|
||||
try:
|
||||
# let's fetch the current persisted config (so only the data on disk,
|
||||
# without the defaults)
|
||||
config = self._settings.get_all_data(merged=False, incl_defaults=False, error_on_path=True)
|
||||
except NoSuchSettingsPath:
|
||||
# no config persisted, nothing to do => get out of here
|
||||
return
|
||||
|
||||
if config is None:
|
||||
# config is set to None, that doesn't make sense, kill it and leave
|
||||
self._settings.clean_all_data()
|
||||
return
|
||||
|
||||
if self.config_version_key in config and config[self.config_version_key] is None:
|
||||
# delete None entries for config version - it's the default, no need
|
||||
del config[self.config_version_key]
|
||||
|
||||
# calculate a minimal diff between the settings and the current config -
|
||||
# anything already in the settings will be removed from the persisted
|
||||
# config, no need to duplicate it
|
||||
defaults = self.get_settings_defaults()
|
||||
diff = octoprint.util.dict_minimal_mergediff(defaults, config)
|
||||
|
||||
if not diff:
|
||||
# no diff to defaults, no need to have anything persisted
|
||||
self._settings.clean_all_data()
|
||||
else:
|
||||
# diff => persist only that
|
||||
self._settings.set([], diff)
|
||||
|
||||
def on_settings_initialized(self):
|
||||
"""
|
||||
Called after the settings have been initialized and - if necessary - also been migrated through a call to
|
||||
|
||||
@@ -37,11 +37,10 @@ class CuraPlugin(octoprint.plugin.SlicerPlugin,
|
||||
|
||||
##~~ TemplatePlugin API
|
||||
|
||||
def get_template_configs(self):
|
||||
from flask.ext.babel import gettext
|
||||
return [
|
||||
dict(type="settings", name=gettext("CuraEngine"))
|
||||
]
|
||||
def get_template_vars(self):
|
||||
return dict(
|
||||
homepage=__plugin_url__
|
||||
)
|
||||
|
||||
##~~ StartupPlugin API
|
||||
|
||||
@@ -413,9 +412,9 @@ def _sanitize_name(name):
|
||||
sanitized_name = sanitized_name.replace(" ", "_")
|
||||
return sanitized_name.lower()
|
||||
|
||||
__plugin_name__ = "CuraEngine"
|
||||
__plugin_name__ = "CuraEngine (<= 15.04)"
|
||||
__plugin_author__ = "Gina Häußge"
|
||||
__plugin_url__ = "https://github.com/foosel/OctoPrint/wiki/Plugin:-Cura"
|
||||
__plugin_description__ = "Adds support for slicing via CuraEngine from within OctoPrint"
|
||||
__plugin_description__ = "Adds support for slicing via CuraEngine versions up to and including version 15.04 from within OctoPrint"
|
||||
__plugin_license__ = "AGPLv3"
|
||||
__plugin_implementation__ = CuraPlugin()
|
||||
@@ -1,5 +1,12 @@
|
||||
<h4>{{ _('General') }}</h4>
|
||||
|
||||
<p>{% trans %}
|
||||
Specify the path to the CuraEngine binary. Note that only
|
||||
<strong>versions up to and including 15.04</strong> are supported.
|
||||
CuraEngine version 15.06 or newer is <strong>not</strong>
|
||||
compatible with this plugin.
|
||||
{% endtrans %}</p>
|
||||
|
||||
<form class="form-horizontal">
|
||||
<div class="control-group">
|
||||
<label class="control-label" for="settings-cura-path">{{ _('Path to CuraEngine') }}</label>
|
||||
@@ -10,7 +17,7 @@
|
||||
<div class="control-group">
|
||||
<div class="controls">
|
||||
<label class="checkbox">
|
||||
<input type="checkbox" data-bind="checked: settings.plugins.cura.debug_logging"> {{ _('Log the output of CuraEngine to plugin_cura_engine.log') }}
|
||||
<input type="checkbox" data-bind="checked: settings.plugins.cura.debug_logging"> {{ _('Log the output of CuraEngine to <code>plugin_cura_engine.log</code>') }}
|
||||
</label>
|
||||
</div>
|
||||
</div>
|
||||
@@ -53,6 +60,10 @@
|
||||
|
||||
<button class="btn pull-right" data-bind="click: function() { $root.showImportProfileDialog() }">{{ _('Import Profile...') }}</button>
|
||||
|
||||
<div style="clear: both">
|
||||
<small>{% trans %}For more information on configuration and usage please <a href="{{ plugin_cura_homepage }}" target="_blank">see the Plugin's homepage</a>.{% endtrans %}</small>
|
||||
</div>
|
||||
|
||||
<div id="settings_plugin_cura_import" class="modal hide fade">
|
||||
<div class="modal-header">
|
||||
<a href="#" class="close" data-dismiss="modal" aria-hidden="true">×</a>
|
||||
@@ -98,6 +109,13 @@
|
||||
</div>
|
||||
</div>
|
||||
</form>
|
||||
|
||||
<small>{% trans %}
|
||||
You can import your existing profile <code>.ini</code> files from Cura (version up to and
|
||||
including 15.04) here. Please be aware that neither the <code>.json</code> profile format
|
||||
from Cura versions starting with 15.06 is supported, nor are the custom Cura profile formats
|
||||
that third party tools like e.g. Repetier create.
|
||||
{% endtrans %}</small>
|
||||
</div>
|
||||
<div class="modal-footer">
|
||||
<button class="btn" data-dismiss="modal" aria-hidden="true">{{ _('Abort') }}</button>
|
||||
|
||||
@@ -503,19 +503,28 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin,
|
||||
"""
|
||||
|
||||
checks = self._get_configured_checks()
|
||||
populated_checks = dict()
|
||||
for target, check in checks.items():
|
||||
try:
|
||||
populated_checks[target] = self._populated_check(target, check)
|
||||
except exceptions.UnknownCheckType:
|
||||
self._logger.debug("Ignoring unknown check type for target {}".format(target))
|
||||
except:
|
||||
self._logger.exception("Error while populating check prior to update for target {}".format(target))
|
||||
|
||||
if check_targets is None:
|
||||
check_targets = checks.keys()
|
||||
to_be_updated = sorted(set(check_targets) & set(checks.keys()))
|
||||
check_targets = populated_checks.keys()
|
||||
to_be_updated = sorted(set(check_targets) & set(populated_checks.keys()))
|
||||
if "octoprint" in to_be_updated:
|
||||
to_be_updated.remove("octoprint")
|
||||
tmp = ["octoprint"] + to_be_updated
|
||||
to_be_updated = tmp
|
||||
|
||||
updater_thread = threading.Thread(target=self._update_worker, args=(checks, to_be_updated, force))
|
||||
updater_thread = threading.Thread(target=self._update_worker, args=(populated_checks, to_be_updated, force))
|
||||
updater_thread.daemon = False
|
||||
updater_thread.start()
|
||||
|
||||
return to_be_updated, dict((key, check["displayName"] if "displayName" in check else key) for key, check in checks.items() if key in to_be_updated)
|
||||
return to_be_updated, dict((key, check["displayName"] if "displayName" in check else key) for key, check in populated_checks.items() if key in to_be_updated)
|
||||
|
||||
def _update_worker(self, checks, check_targets, force):
|
||||
|
||||
|
||||
@@ -387,7 +387,7 @@ $(function() {
|
||||
}
|
||||
});
|
||||
self.waitingForRestart = false;
|
||||
}, 20000);
|
||||
}, 60000);
|
||||
|
||||
break;
|
||||
}
|
||||
|
||||
@@ -12,7 +12,7 @@ import re
|
||||
import logging
|
||||
|
||||
from octoprint.settings import settings
|
||||
from octoprint.util import dict_merge, dict_clean, dict_contains_keys
|
||||
from octoprint.util import dict_merge, dict_sanitize, dict_contains_keys, is_hidden_path
|
||||
|
||||
class SaveError(Exception):
|
||||
pass
|
||||
@@ -151,7 +151,7 @@ class PrinterProfileManager(object):
|
||||
formFactor = BedTypes.RECTANGULAR,
|
||||
origin = BedOrigin.LOWERLEFT
|
||||
),
|
||||
heatedBed = False,
|
||||
heatedBed = True,
|
||||
extruder=dict(
|
||||
count = 1,
|
||||
offsets = [
|
||||
@@ -214,7 +214,7 @@ class PrinterProfileManager(object):
|
||||
|
||||
identifier = self._sanitize(identifier)
|
||||
profile["id"] = identifier
|
||||
profile = dict_clean(profile, self.__class__.default)
|
||||
profile = dict_sanitize(profile, self.__class__.default)
|
||||
|
||||
if identifier == "_default":
|
||||
default_profile = dict_merge(self._load_default(), profile)
|
||||
@@ -289,7 +289,7 @@ class PrinterProfileManager(object):
|
||||
def _load_all_identifiers(self):
|
||||
results = dict(_default=None)
|
||||
for entry in os.listdir(self._folder):
|
||||
if entry.startswith(".") or not entry.endswith(".profile") or entry == "_default.profile":
|
||||
if is_hidden_path(entry) or not entry.endswith(".profile") or entry == "_default.profile":
|
||||
continue
|
||||
|
||||
path = os.path.join(self._folder, entry)
|
||||
@@ -408,7 +408,7 @@ class PrinterProfileManager(object):
|
||||
for path in (("volume", "width"), ("volume", "depth"), ("volume", "height"), ("extruder", "nozzleDiameter")):
|
||||
try:
|
||||
convert_value(profile, path, float)
|
||||
except:
|
||||
except Exception as e:
|
||||
self._logger.warn("Profile has invalid value for path {path!r}: {msg}".format(path=".".join(path), msg=str(e)))
|
||||
return False
|
||||
|
||||
@@ -416,7 +416,7 @@ class PrinterProfileManager(object):
|
||||
for path in (("axes", "x", "inverted"), ("axes", "y", "inverted"), ("axes", "z", "inverted")):
|
||||
try:
|
||||
convert_value(profile, path, bool)
|
||||
except:
|
||||
except Exception as e:
|
||||
self._logger.warn("Profile has invalid value for path {path!r}: {msg}".format(path=".".join(path), msg=str(e)))
|
||||
return False
|
||||
|
||||
|
||||
@@ -645,6 +645,8 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback):
|
||||
if filename is not None:
|
||||
if sd:
|
||||
path_in_storage = filename
|
||||
if path_in_storage.startswith("/"):
|
||||
path_in_storage = path_in_storage[1:]
|
||||
path_on_disk = None
|
||||
else:
|
||||
path_in_storage = self._fileManager.path_in_storage(FileDestinations.LOCAL, filename)
|
||||
|
||||
@@ -213,7 +213,7 @@ class Server():
|
||||
set_preprocessors=set_preprocessors)
|
||||
return dict(settings=plugin_settings)
|
||||
|
||||
def settings_plugin_config_migration(name, implementation):
|
||||
def settings_plugin_config_migration_and_cleanup(name, implementation):
|
||||
if not isinstance(implementation, octoprint.plugin.SettingsPlugin):
|
||||
return
|
||||
|
||||
@@ -221,11 +221,13 @@ class Server():
|
||||
settings_migrator = implementation.on_settings_migrate
|
||||
|
||||
if settings_version is not None and settings_migrator is not None:
|
||||
stored_version = implementation._settings.get_int(["_config_version"])
|
||||
stored_version = implementation._settings.get_int([octoprint.plugin.SettingsPlugin.config_version_key])
|
||||
if stored_version is None or stored_version < settings_version:
|
||||
settings_migrator(settings_version, stored_version)
|
||||
implementation._settings.set_int(["_config_version"], settings_version)
|
||||
implementation._settings.save()
|
||||
implementation._settings.set_int([octoprint.plugin.SettingsPlugin.config_version_key], settings_version)
|
||||
|
||||
implementation.on_settings_cleanup()
|
||||
implementation._settings.save()
|
||||
|
||||
implementation.on_settings_initialized()
|
||||
|
||||
@@ -235,11 +237,11 @@ class Server():
|
||||
settingsPlugins = pluginManager.get_implementations(octoprint.plugin.SettingsPlugin)
|
||||
for implementation in settingsPlugins:
|
||||
try:
|
||||
settings_plugin_config_migration(implementation._identifier, implementation)
|
||||
settings_plugin_config_migration_and_cleanup(implementation._identifier, implementation)
|
||||
except:
|
||||
self._logger.exception("Error while trying to migrate settings for plugin {}, ignoring it".format(implementation._identifier))
|
||||
|
||||
pluginManager.implementation_post_inits=[settings_plugin_config_migration]
|
||||
pluginManager.implementation_post_inits=[settings_plugin_config_migration_and_cleanup]
|
||||
|
||||
pluginManager.log_all_plugins()
|
||||
|
||||
@@ -340,7 +342,7 @@ class Server():
|
||||
)
|
||||
additional_mime_types=dict(mime_type_guesser=mime_type_guesser)
|
||||
admin_validator = dict(access_validation=util.tornado.access_validation_factory(app, loginManager, util.flask.user_validator))
|
||||
no_hidden_files_validator = dict(path_validation=util.tornado.path_validation_factory(lambda path: not os.path.basename(path).startswith("."), status_code=404))
|
||||
no_hidden_files_validator = dict(path_validation=util.tornado.path_validation_factory(lambda path: not octoprint.util.is_hidden_path(path), status_code=404))
|
||||
|
||||
def joined_dict(*dicts):
|
||||
if not len(dicts):
|
||||
@@ -647,7 +649,9 @@ class Server():
|
||||
|
||||
# configure additional template folders for jinja2
|
||||
import jinja2
|
||||
filesystem_loader = jinja2.FileSystemLoader([])
|
||||
import octoprint.util.jinja
|
||||
filesystem_loader = octoprint.util.jinja.FilteredFileSystemLoader([],
|
||||
path_filter=lambda x: not octoprint.util.is_hidden_path(x))
|
||||
filesystem_loader.searchpath = self._template_searchpaths
|
||||
|
||||
jinja_loader = jinja2.ChoiceLoader([
|
||||
|
||||
@@ -10,10 +10,9 @@ from werkzeug.exceptions import BadRequest
|
||||
import re
|
||||
|
||||
from octoprint.settings import settings, valid_boolean_trues
|
||||
from octoprint.server import printer, NO_CONTENT
|
||||
from octoprint.server import printer, printerProfileManager, NO_CONTENT
|
||||
from octoprint.server.api import api
|
||||
from octoprint.server.util.flask import restricted_access, get_json_command_from_request
|
||||
import octoprint.util as util
|
||||
|
||||
from octoprint.printer import UnknownScript
|
||||
|
||||
@@ -34,9 +33,13 @@ def printerState():
|
||||
|
||||
result = {}
|
||||
|
||||
processor = lambda x: x
|
||||
if not printerProfileManager.get_current_or_default()["heatedBed"]:
|
||||
processor = _delete_bed
|
||||
|
||||
# add temperature information
|
||||
if not "temperature" in excludes:
|
||||
result.update({"temperature": _getTemperatureData(lambda x: x)})
|
||||
result.update({"temperature": _get_temperature_data(processor)})
|
||||
|
||||
# add sd information
|
||||
if not "sd" in excludes and settings().getBoolean(["feature", "sdSupport"]):
|
||||
@@ -145,14 +148,7 @@ def printerToolState():
|
||||
if not printer.is_operational():
|
||||
return make_response("Printer is not operational", 409)
|
||||
|
||||
def deleteBed(x):
|
||||
data = dict(x)
|
||||
|
||||
if "bed" in data.keys():
|
||||
del data["bed"]
|
||||
return data
|
||||
|
||||
return jsonify(_getTemperatureData(deleteBed))
|
||||
return jsonify(_get_temperature_data(_delete_bed))
|
||||
|
||||
|
||||
##~~ Heated bed
|
||||
@@ -164,6 +160,9 @@ def printerBedCommand():
|
||||
if not printer.is_operational():
|
||||
return make_response("Printer is not operational", 409)
|
||||
|
||||
if not printerProfileManager.get_current_or_default()["heatedBed"]:
|
||||
return make_response("Printer does not have a heated bed", 409)
|
||||
|
||||
valid_commands = {
|
||||
"target": ["target"],
|
||||
"offset": ["offset"]
|
||||
@@ -204,15 +203,10 @@ def printerBedState():
|
||||
if not printer.is_operational():
|
||||
return make_response("Printer is not operational", 409)
|
||||
|
||||
def deleteTools(x):
|
||||
data = dict(x)
|
||||
if not printerProfileManager.get_current_or_default()["heatedBed"]:
|
||||
return make_response("Printer does not have a heated bed", 409)
|
||||
|
||||
for k in data.keys():
|
||||
if k.startswith("tool"):
|
||||
del data[k]
|
||||
return data
|
||||
|
||||
data = _getTemperatureData(deleteTools)
|
||||
data = _get_temperature_data(_delete_tools)
|
||||
if isinstance(data, Response):
|
||||
return data
|
||||
else:
|
||||
@@ -382,7 +376,7 @@ def getCustomControls():
|
||||
return jsonify(controls=customControls)
|
||||
|
||||
|
||||
def _getTemperatureData(filter):
|
||||
def _get_temperature_data(preprocessor):
|
||||
if not printer.is_operational():
|
||||
return make_response("Printer is not operational", 409)
|
||||
|
||||
@@ -399,8 +393,23 @@ def _getTemperatureData(filter):
|
||||
limit = min(limit, len(history))
|
||||
|
||||
tempData.update({
|
||||
"history": map(lambda x: filter(x), history[-limit:])
|
||||
"history": map(lambda x: preprocessor(x), history[-limit:])
|
||||
})
|
||||
|
||||
return filter(tempData)
|
||||
return preprocessor(tempData)
|
||||
|
||||
|
||||
def _delete_tools(x):
|
||||
return _delete_from_data(x, lambda k: k.startswith("tool"))
|
||||
|
||||
|
||||
def _delete_bed(x):
|
||||
return _delete_from_data(x, lambda k: k == "bed")
|
||||
|
||||
|
||||
def _delete_from_data(x, key_matcher):
|
||||
data = dict(x)
|
||||
for k in data.keys():
|
||||
if key_matcher(k):
|
||||
del data[k]
|
||||
return data
|
||||
@@ -26,7 +26,7 @@ import octoprint.server
|
||||
import octoprint.users
|
||||
import octoprint.plugin
|
||||
|
||||
from werkzeug.contrib.cache import SimpleCache
|
||||
from werkzeug.contrib.cache import BaseCache
|
||||
|
||||
|
||||
#~~ monkey patching
|
||||
@@ -259,9 +259,61 @@ def passive_login():
|
||||
|
||||
#~~ cache decorator for cacheable views
|
||||
|
||||
_cache = SimpleCache()
|
||||
class LessSimpleCache(BaseCache):
|
||||
"""
|
||||
Slightly improved version of :class:`SimpleCache`.
|
||||
|
||||
def cached(timeout=5 * 60, key=lambda: "view/%s" % flask.request.path, unless=None, refreshif=None, unless_response=None):
|
||||
Setting ``default_timeout`` or ``timeout`` to ``-1`` will have no timeout be applied at all.
|
||||
"""
|
||||
|
||||
def __init__(self, threshold=500, default_timeout=300):
|
||||
BaseCache.__init__(self, default_timeout=default_timeout)
|
||||
self._cache = {}
|
||||
self.clear = self._cache.clear
|
||||
self._threshold = threshold
|
||||
|
||||
def _prune(self):
|
||||
if self.over_threshold():
|
||||
now = time.time()
|
||||
for idx, (key, (expires, _)) in enumerate(self._cache.items()):
|
||||
if expires is not None and expires <= now or idx % 3 == 0:
|
||||
self._cache.pop(key, None)
|
||||
|
||||
def get(self, key):
|
||||
import pickle
|
||||
now = time.time()
|
||||
expires, value = self._cache.get(key, (0, None))
|
||||
if expires is None or expires > now:
|
||||
return pickle.loads(value)
|
||||
|
||||
def set(self, key, value, timeout=None):
|
||||
import pickle
|
||||
self._prune()
|
||||
self._cache[key] = (self.calculate_timeout(timeout=timeout),
|
||||
pickle.dumps(value, pickle.HIGHEST_PROTOCOL))
|
||||
|
||||
def add(self, key, value, timeout=None):
|
||||
self.set(key, value, timeout=None)
|
||||
self._cache.setdefault(key, self._cache[key])
|
||||
|
||||
def delete(self, key):
|
||||
self._cache.pop(key, None)
|
||||
|
||||
def calculate_timeout(self, timeout=None):
|
||||
if timeout is None:
|
||||
timeout = self.default_timeout
|
||||
if timeout is -1:
|
||||
return None
|
||||
return time.time() + timeout
|
||||
|
||||
def over_threshold(self):
|
||||
if self._threshold is None:
|
||||
return False
|
||||
return len(self._cache) > self._threshold
|
||||
|
||||
_cache = LessSimpleCache()
|
||||
|
||||
def cached(timeout=5 * 60, key=lambda: "view:%s" % flask.request.path, unless=None, refreshif=None, unless_response=None):
|
||||
def decorator(f):
|
||||
@functools.wraps(f)
|
||||
def decorated_function(*args, **kwargs):
|
||||
@@ -287,7 +339,7 @@ def cached(timeout=5 * 60, key=lambda: "view/%s" % flask.request.path, unless=No
|
||||
return rv
|
||||
|
||||
# get value from wrapped function
|
||||
logger.debug("No cache entry or refreshing cache for {path}, calling wrapped function".format(path=flask.request.path))
|
||||
logger.debug("No cache entry or refreshing cache for {path} (key: {key}), calling wrapped function".format(path=flask.request.path, key=cache_key))
|
||||
rv = f(*args, **kwargs)
|
||||
|
||||
# do not store if the "unless_response" condition is true
|
||||
|
||||
@@ -6,6 +6,7 @@ __license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agp
|
||||
__copyright__ = "Copyright (C) 2014 The OctoPrint Project - Released under terms of the AGPLv3 License"
|
||||
|
||||
import logging
|
||||
import os
|
||||
import watchdog.events
|
||||
|
||||
import octoprint.filemanager
|
||||
@@ -14,6 +15,7 @@ import octoprint.util
|
||||
|
||||
|
||||
class GcodeWatchdogHandler(watchdog.events.PatternMatchingEventHandler):
|
||||
|
||||
"""
|
||||
Takes care of automatically "uploading" files that get added to the watched folder.
|
||||
"""
|
||||
@@ -27,40 +29,42 @@ class GcodeWatchdogHandler(watchdog.events.PatternMatchingEventHandler):
|
||||
self._printer = printer
|
||||
|
||||
def _upload(self, path):
|
||||
import os
|
||||
file_wrapper = octoprint.filemanager.util.DiskFileWrapper(os.path.basename(path), path)
|
||||
|
||||
# determine current job
|
||||
currentFilename = None
|
||||
currentOrigin = None
|
||||
currentJob = self._printer.get_current_job()
|
||||
if currentJob is not None and "file" in currentJob.keys():
|
||||
currentJobFile = currentJob["file"]
|
||||
if "name" in currentJobFile.keys() and "origin" in currentJobFile.keys():
|
||||
currentFilename = currentJobFile["name"]
|
||||
currentOrigin = currentJobFile["origin"]
|
||||
|
||||
# determine future filename of file to be uploaded, abort if it can't be uploaded
|
||||
try:
|
||||
futureFilename = self._file_manager.sanitize_name(octoprint.filemanager.FileDestinations.LOCAL, file_wrapper.filename)
|
||||
except:
|
||||
futureFilename = None
|
||||
if futureFilename is None or (len(self._file_manager.registered_slicers) == 0 and not octoprint.filemanager.valid_file_type(futureFilename)):
|
||||
return
|
||||
file_wrapper = octoprint.filemanager.util.DiskFileWrapper(os.path.basename(path), path)
|
||||
|
||||
# prohibit overwriting currently selected file while it's being printed
|
||||
if futureFilename == currentFilename and currentOrigin == octoprint.filemanager.FileDestinations.LOCAL and self._printer.is_printing() or self._printer.is_paused():
|
||||
return
|
||||
# determine current job
|
||||
currentFilename = None
|
||||
currentOrigin = None
|
||||
currentJob = self._printer.get_current_job()
|
||||
if currentJob is not None and "file" in currentJob.keys():
|
||||
currentJobFile = currentJob["file"]
|
||||
if "name" in currentJobFile.keys() and "origin" in currentJobFile.keys():
|
||||
currentFilename = currentJobFile["name"]
|
||||
currentOrigin = currentJobFile["origin"]
|
||||
|
||||
self._file_manager.add_file(octoprint.filemanager.FileDestinations.LOCAL,
|
||||
file_wrapper.filename,
|
||||
file_wrapper,
|
||||
allow_overwrite=True)
|
||||
if os.path.exists(path):
|
||||
# determine future filename of file to be uploaded, abort if it can't be uploaded
|
||||
try:
|
||||
os.remove(path)
|
||||
futureFilename = self._file_manager.sanitize_name(octoprint.filemanager.FileDestinations.LOCAL, file_wrapper.filename)
|
||||
except:
|
||||
self._logger.exception("Error while trying to clear a file from the watched folder")
|
||||
futureFilename = None
|
||||
if futureFilename is None or (len(self._file_manager.registered_slicers) == 0 and not octoprint.filemanager.valid_file_type(futureFilename)):
|
||||
return
|
||||
|
||||
# prohibit overwriting currently selected file while it's being printed
|
||||
if futureFilename == currentFilename and currentOrigin == octoprint.filemanager.FileDestinations.LOCAL and self._printer.is_printing() or self._printer.is_paused():
|
||||
return
|
||||
|
||||
self._file_manager.add_file(octoprint.filemanager.FileDestinations.LOCAL,
|
||||
file_wrapper.filename,
|
||||
file_wrapper,
|
||||
allow_overwrite=True)
|
||||
if os.path.exists(path):
|
||||
try:
|
||||
os.remove(path)
|
||||
except:
|
||||
self._logger.exception("Error while trying to clear a file from the watched folder")
|
||||
except:
|
||||
self._logger.exception("There was an error while processing the file {} in the watched folder".format(path))
|
||||
|
||||
def on_created(self, event):
|
||||
self._upload(event.src_path)
|
||||
@@ -27,8 +27,9 @@ _valid_id_re = re.compile("[a-z_]+")
|
||||
_valid_div_re = re.compile("[a-zA-Z_-]+")
|
||||
|
||||
@app.route("/")
|
||||
@util.flask.cached(refreshif=lambda: util.flask.cache_check_headers() or "_refresh" in request.values,
|
||||
key=lambda: "view/%s/%s" % (request.path, g.locale),
|
||||
@util.flask.cached(timeout=-1,
|
||||
refreshif=lambda: util.flask.cache_check_headers() or "_refresh" in request.values,
|
||||
key=lambda: "view:{}:{}".format(request.base_url, g.locale),
|
||||
unless_response=util.flask.cache_check_response_headers)
|
||||
def index():
|
||||
|
||||
@@ -401,7 +402,9 @@ def robotsTxt():
|
||||
|
||||
|
||||
@app.route("/i18n/<string:locale>/<string:domain>.js")
|
||||
@util.flask.cached(refreshif=lambda: util.flask.cache_check_headers() or "_refresh" in request.values, key=lambda: "view/%s/%s" % (request.path, g.locale))
|
||||
@util.flask.cached(timeout=-1,
|
||||
refreshif=lambda: util.flask.cache_check_headers() or "_refresh" in request.values,
|
||||
key=lambda: "view:{}:{}".format(request.base_url, g.locale))
|
||||
def localeJs(locale, domain):
|
||||
messages = dict()
|
||||
plural_expr = None
|
||||
|
||||
+84
-29
@@ -30,7 +30,7 @@ import logging
|
||||
import re
|
||||
import uuid
|
||||
|
||||
from octoprint.util import atomic_write
|
||||
from octoprint.util import atomic_write, is_hidden_path
|
||||
|
||||
_APPNAME = "OctoPrint"
|
||||
|
||||
@@ -253,9 +253,10 @@ default_settings = {
|
||||
},
|
||||
"scripts": {
|
||||
"gcode": {
|
||||
"afterPrintCancelled": "; disable motors\nM84\n\n;disable all heaters\n{% snippet 'disable_hotends' %}\nM140 S0\n\n;disable fan\nM106 S0",
|
||||
"afterPrintCancelled": "; disable motors\nM84\n\n;disable all heaters\n{% snippet 'disable_hotends' %}\n{% snippet 'disable_bed' %}\n;disable fan\nM106 S0",
|
||||
"snippets": {
|
||||
"disable_hotends": "{% for tool in range(printer_profile.extruder.count) %}M104 T{{ tool }} S0\n{% endfor %}"
|
||||
"disable_hotends": "{% for tool in range(printer_profile.extruder.count) %}M104 T{{ tool }} S0\n{% endfor %}",
|
||||
"disable_bed": "{% if printer_profile.heatedBed %}M140 S0\n{% endif %}"
|
||||
}
|
||||
}
|
||||
},
|
||||
@@ -304,6 +305,11 @@ default_settings = {
|
||||
valid_boolean_trues = [True, "true", "yes", "y", "1"]
|
||||
""" Values that are considered to be equivalent to the boolean ``True`` value, used for type conversion in various places."""
|
||||
|
||||
|
||||
class NoSuchSettingsPath(BaseException):
|
||||
pass
|
||||
|
||||
|
||||
class Settings(object):
|
||||
"""
|
||||
The :class:`Settings` class allows managing all of OctoPrint's settings. It takes care of initializing the settings
|
||||
@@ -400,10 +406,12 @@ class Settings(object):
|
||||
return folder
|
||||
|
||||
def _init_script_templating(self):
|
||||
from jinja2 import Environment, BaseLoader, FileSystemLoader, ChoiceLoader, TemplateNotFound
|
||||
from jinja2.nodes import Include, Const
|
||||
from jinja2 import Environment, BaseLoader, ChoiceLoader, TemplateNotFound
|
||||
from jinja2.nodes import Include
|
||||
from jinja2.ext import Extension
|
||||
|
||||
from octoprint.util.jinja import FilteredFileSystemLoader
|
||||
|
||||
class SnippetExtension(Extension):
|
||||
tags = {"snippet"}
|
||||
fields = Include.fields
|
||||
@@ -492,10 +500,14 @@ class Settings(object):
|
||||
else:
|
||||
return template
|
||||
|
||||
file_system_loader = FileSystemLoader(self.getBaseFolder("scripts"))
|
||||
path_filter = lambda path: not is_hidden_path(path)
|
||||
file_system_loader = FilteredFileSystemLoader(self.getBaseFolder("scripts"),
|
||||
path_filter=path_filter)
|
||||
settings_loader = SettingsScriptLoader(self)
|
||||
choice_loader = ChoiceLoader([file_system_loader, settings_loader])
|
||||
select_loader = SelectLoader(choice_loader, dict(bundled=settings_loader, file=file_system_loader))
|
||||
select_loader = SelectLoader(choice_loader,
|
||||
dict(bundled=settings_loader,
|
||||
file=file_system_loader))
|
||||
return RelEnvironment(loader=select_loader, extensions=[SnippetExtension])
|
||||
|
||||
def _get_script_template(self, script_type, name, source=False):
|
||||
@@ -810,13 +822,13 @@ class Settings(object):
|
||||
stat = os.stat(self._configfile)
|
||||
return stat.st_mtime
|
||||
|
||||
#~~ getter
|
||||
##~~ Internal getter
|
||||
|
||||
def get(self, path, asdict=False, config=None, defaults=None, preprocessors=None, merged=False, incl_defaults=True):
|
||||
def _get_value(self, path, asdict=False, config=None, defaults=None, preprocessors=None, merged=False, incl_defaults=True):
|
||||
import octoprint.util as util
|
||||
|
||||
if len(path) == 0:
|
||||
return None
|
||||
raise NoSuchSettingsPath()
|
||||
|
||||
if config is None:
|
||||
config = self._config
|
||||
@@ -834,7 +846,7 @@ class Settings(object):
|
||||
config = {}
|
||||
defaults = defaults[key]
|
||||
else:
|
||||
return None
|
||||
raise NoSuchSettingsPath()
|
||||
|
||||
if preprocessors and isinstance(preprocessors, dict) and key in preprocessors:
|
||||
preprocessors = preprocessors[key]
|
||||
@@ -858,7 +870,7 @@ class Settings(object):
|
||||
elif incl_defaults and key in defaults:
|
||||
value = defaults[key]
|
||||
else:
|
||||
value = None
|
||||
raise NoSuchSettingsPath()
|
||||
|
||||
if preprocessors and isinstance(preprocessors, dict) and key in preprocessors and callable(preprocessors[key]):
|
||||
value = preprocessors[key](value)
|
||||
@@ -876,8 +888,34 @@ class Settings(object):
|
||||
else:
|
||||
return results
|
||||
|
||||
def getInt(self, path, config=None, defaults=None, preprocessors=None, incl_defaults=True):
|
||||
value = self.get(path, config=config, defaults=defaults, preprocessors=preprocessors, incl_defaults=incl_defaults)
|
||||
#~~ has
|
||||
|
||||
def has(self, path, **kwargs):
|
||||
try:
|
||||
self._get_value(path, **kwargs)
|
||||
except NoSuchSettingsPath:
|
||||
return False
|
||||
else:
|
||||
return True
|
||||
|
||||
#~~ getter
|
||||
|
||||
def get(self, path, **kwargs):
|
||||
error_on_path = kwargs.get("error_on_path", False)
|
||||
new_kwargs = dict(kwargs)
|
||||
if "error_on_path" in new_kwargs:
|
||||
del new_kwargs["error_on_path"]
|
||||
|
||||
try:
|
||||
return self._get_value(path, **new_kwargs)
|
||||
except NoSuchSettingsPath:
|
||||
if error_on_path:
|
||||
raise
|
||||
else:
|
||||
return None
|
||||
|
||||
def getInt(self, path, **kwargs):
|
||||
value = self.get(path, **kwargs)
|
||||
if value is None:
|
||||
return None
|
||||
|
||||
@@ -887,8 +925,8 @@ class Settings(object):
|
||||
self._logger.warn("Could not convert %r to a valid integer when getting option %r" % (value, path))
|
||||
return None
|
||||
|
||||
def getFloat(self, path, config=None, defaults=None, preprocessors=None, incl_defaults=True):
|
||||
value = self.get(path, config=config, defaults=defaults, preprocessors=preprocessors, incl_defaults=incl_defaults)
|
||||
def getFloat(self, path, **kwargs):
|
||||
value = self.get(path, **kwargs)
|
||||
if value is None:
|
||||
return None
|
||||
|
||||
@@ -898,8 +936,8 @@ class Settings(object):
|
||||
self._logger.warn("Could not convert %r to a valid integer when getting option %r" % (value, path))
|
||||
return None
|
||||
|
||||
def getBoolean(self, path, config=None, defaults=None, preprocessors=None, incl_defaults=True):
|
||||
value = self.get(path, config=config, defaults=defaults, preprocessors=preprocessors, incl_defaults=incl_defaults)
|
||||
def getBoolean(self, path, **kwargs):
|
||||
value = self.get(path, **kwargs)
|
||||
if value is None:
|
||||
return None
|
||||
if isinstance(value, bool):
|
||||
@@ -952,6 +990,23 @@ class Settings(object):
|
||||
|
||||
return script
|
||||
|
||||
#~~ remove
|
||||
|
||||
def remove(self, path, config=None):
|
||||
if config is None:
|
||||
config = self._config
|
||||
|
||||
while len(path) > 1:
|
||||
key = path.pop(0)
|
||||
if not isinstance(config, dict) or key not in config:
|
||||
return
|
||||
config = config[key]
|
||||
|
||||
key = path.pop(0)
|
||||
if isinstance(config, dict) and key in config:
|
||||
del config[key]
|
||||
self._dirty = True
|
||||
|
||||
#~~ setter
|
||||
|
||||
def set(self, path, value, force=False, defaults=None, config=None, preprocessors=None):
|
||||
@@ -998,9 +1053,9 @@ class Settings(object):
|
||||
config[key] = value
|
||||
self._dirty = True
|
||||
|
||||
def setInt(self, path, value, force=False, defaults=None, config=None, preprocessors=None):
|
||||
def setInt(self, path, value, **kwargs):
|
||||
if value is None:
|
||||
self.set(path, None, config=config, force=force, defaults=defaults, preprocessors=preprocessors)
|
||||
self.set(path, None, **kwargs)
|
||||
return
|
||||
|
||||
try:
|
||||
@@ -1009,11 +1064,11 @@ class Settings(object):
|
||||
self._logger.warn("Could not convert %r to a valid integer when setting option %r" % (value, path))
|
||||
return
|
||||
|
||||
self.set(path, intValue, config=config, force=force, defaults=defaults, preprocessors=preprocessors)
|
||||
self.set(path, intValue, **kwargs)
|
||||
|
||||
def setFloat(self, path, value, force=False, defaults=None, config=None, preprocessors=None):
|
||||
def setFloat(self, path, value, **kwargs):
|
||||
if value is None:
|
||||
self.set(path, None, config=config, force=force, defaults=defaults, preprocessors=preprocessors)
|
||||
self.set(path, None, **kwargs)
|
||||
return
|
||||
|
||||
try:
|
||||
@@ -1022,15 +1077,15 @@ class Settings(object):
|
||||
self._logger.warn("Could not convert %r to a valid integer when setting option %r" % (value, path))
|
||||
return
|
||||
|
||||
self.set(path, floatValue, config=config, force=force, defaults=defaults, preprocessors=preprocessors)
|
||||
self.set(path, floatValue, **kwargs)
|
||||
|
||||
def setBoolean(self, path, value, force=False, defaults=None, config=None, preprocessors=None):
|
||||
def setBoolean(self, path, value, **kwargs):
|
||||
if value is None or isinstance(value, bool):
|
||||
self.set(path, value, config=config, force=force, defaults=defaults, preprocessors=preprocessors)
|
||||
self.set(path, value, **kwargs)
|
||||
elif value.lower() in valid_boolean_trues:
|
||||
self.set(path, True, config=config, force=force, defaults=defaults, preprocessors=preprocessors)
|
||||
self.set(path, True, **kwargs)
|
||||
else:
|
||||
self.set(path, False, config=config, force=force, defaults=defaults, preprocessors=preprocessors)
|
||||
self.set(path, False, **kwargs)
|
||||
|
||||
def setBaseFolder(self, type, path, force=False):
|
||||
if type not in default_settings["folder"].keys():
|
||||
@@ -1052,7 +1107,7 @@ class Settings(object):
|
||||
def saveScript(self, script_type, name, script):
|
||||
script_folder = self.getBaseFolder("scripts")
|
||||
filename = os.path.realpath(os.path.join(script_folder, script_type, name))
|
||||
if not filename.startswith(script_folder):
|
||||
if not filename.startswith(os.path.realpath(script_folder)):
|
||||
# oops, jail break, that shouldn't happen
|
||||
raise ValueError("Invalid script path to save to: {filename} (from {script_type}:{name})".format(**locals()))
|
||||
|
||||
|
||||
@@ -22,6 +22,7 @@ __copyright__ = "Copyright (C) 2014 The OctoPrint Project - Released under terms
|
||||
import os
|
||||
import octoprint.plugin
|
||||
import octoprint.events
|
||||
import octoprint.util
|
||||
from octoprint.settings import settings
|
||||
|
||||
import logging
|
||||
@@ -478,7 +479,7 @@ class SlicingManager(object):
|
||||
profiles = dict()
|
||||
slicer_profile_path = self.get_slicer_profile_path(slicer)
|
||||
for entry in os.listdir(slicer_profile_path):
|
||||
if not entry.endswith(".profile") or entry.startswith("."):
|
||||
if not entry.endswith(".profile") or octoprint.util.is_hidden_path(entry):
|
||||
# we are only interested in profiles and no hidden files
|
||||
continue
|
||||
|
||||
@@ -539,7 +540,7 @@ class SlicingManager(object):
|
||||
name = self._sanitize(name)
|
||||
|
||||
path = os.path.join(self.get_slicer_profile_path(slicer), "{name}.profile".format(name=name))
|
||||
if not os.path.realpath(path).startswith(self._profile_path):
|
||||
if not os.path.realpath(path).startswith(os.path.realpath(self._profile_path)):
|
||||
raise IOError("Path to profile {name} tried to break out of allows sub path".format(**locals()))
|
||||
if must_exist and not (os.path.exists(path) and os.path.isfile(path)):
|
||||
raise UnknownProfile(slicer, name)
|
||||
|
||||
@@ -1 +1 @@
|
||||
.btn{display:inline-block;*display:inline;*zoom:1;padding:4px 12px;margin-bottom:0;font-size:14px;line-height:20px;text-align:center;vertical-align:middle;cursor:pointer;color:#333;text-shadow:0 1px 1px rgba(255,255,255,0.75);background-color:#f5f5f5;background-image:-moz-linear-gradient(top,#fff,#e6e6e6);background-image:-webkit-gradient(linear,0 0,0 100%,from(#fff),to(#e6e6e6));background-image:-webkit-linear-gradient(top,#fff,#e6e6e6);background-image:-o-linear-gradient(top,#fff,#e6e6e6);background-image:linear-gradient(to bottom,#fff,#e6e6e6);background-repeat:repeat-x;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#ffffffff',endColorstr='#ffe6e6e6',GradientType=0);border-color:#e6e6e6 #e6e6e6 #bfbfbf;border-color:rgba(0,0,0,0.1) rgba(0,0,0,0.1) rgba(0,0,0,0.25);*background-color:#e6e6e6;filter:progid:DXImageTransform.Microsoft.gradient(enabled = false);border:1px solid #ccc;*border:0;border-bottom-color:#b3b3b3;-webkit-border-radius:4px;-moz-border-radius:4px;border-radius:4px;*margin-left:.3em;-webkit-box-shadow:inset 0 1px 0 rgba(255,255,255,.2),0 1px 2px rgba(0,0,0,.05);-moz-box-shadow:inset 0 1px 0 rgba(255,255,255,.2),0 1px 2px rgba(0,0,0,.05);box-shadow:inset 0 1px 0 rgba(255,255,255,.2),0 1px 2px rgba(0,0,0,.05)}.btn:hover,.btn:focus,.btn:active,.btn.active,.btn.disabled,.btn[disabled]{color:#333;background-color:#e6e6e6;*background-color:#d9d9d9}.btn:active,.btn.active{background-color:#ccc \9}.btn:first-child{*margin-left:0}.btn:hover,.btn:focus{color:#333;text-decoration:none;background-position:0 -15px;-webkit-transition:background-position .1s linear;-moz-transition:background-position .1s linear;-o-transition:background-position .1s linear;transition:background-position .1s linear}.btn:focus{outline:thin dotted #333;outline:5px auto -webkit-focus-ring-color;outline-offset:-2px}.btn.active,.btn:active{background-image:none;outline:0;-webkit-box-shadow:inset 0 2px 4px rgba(0,0,0,.15),0 1px 2px rgba(0,0,0,.05);-moz-box-shadow:inset 0 2px 4px rgba(0,0,0,.15),0 1px 2px rgba(0,0,0,.05);box-shadow:inset 0 2px 4px rgba(0,0,0,.15),0 1px 2px rgba(0,0,0,.05)}.btn.disabled,.btn[disabled]{cursor:default;background-image:none;opacity:.65;filter:alpha(opacity=65);-webkit-box-shadow:none;-moz-box-shadow:none;box-shadow:none}.btn-large{padding:11px 19px;font-size:17.5px;-webkit-border-radius:6px;-moz-border-radius:6px;border-radius:6px}.btn-large [class^="icon-"],.btn-large [class*=" icon-"]{margin-top:4px}.btn-small{padding:2px 10px;font-size:11.9px;-webkit-border-radius:3px;-moz-border-radius:3px;border-radius:3px}.btn-small [class^="icon-"],.btn-small [class*=" icon-"]{margin-top:0}.btn-mini [class^="icon-"],.btn-mini [class*=" icon-"]{margin-top:-1px}.btn-mini{padding:0 6px;font-size:10.5px;-webkit-border-radius:3px;-moz-border-radius:3px;border-radius:3px}.btn-block{display:block;width:100%;padding-left:0;padding-right:0;-webkit-box-sizing:border-box;-moz-box-sizing:border-box;box-sizing:border-box}.btn-block+.btn-block{margin-top:5px}input[type="submit"].btn-block,input[type="reset"].btn-block,input[type="button"].btn-block{width:100%}.btn-primary.active,.btn-warning.active,.btn-danger.active,.btn-success.active,.btn-info.active,.btn-inverse.active{color:rgba(255,255,255,0.75)}.btn-primary{color:#fff;text-shadow:0 -1px 0 rgba(0,0,0,0.25);background-color:#006dcc;background-image:-moz-linear-gradient(top,#08c,#04c);background-image:-webkit-gradient(linear,0 0,0 100%,from(#08c),to(#04c));background-image:-webkit-linear-gradient(top,#08c,#04c);background-image:-o-linear-gradient(top,#08c,#04c);background-image:linear-gradient(to bottom,#08c,#04c);background-repeat:repeat-x;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#ff0088cc',endColorstr='#ff0044cc',GradientType=0);border-color:#04c #04c #002a80;border-color:rgba(0,0,0,0.1) rgba(0,0,0,0.1) rgba(0,0,0,0.25);*background-color:#04c;filter:progid:DXImageTransform.Microsoft.gradient(enabled = false)}.btn-primary:hover,.btn-primary:focus,.btn-primary:active,.btn-primary.active,.btn-primary.disabled,.btn-primary[disabled]{color:#fff;background-color:#04c;*background-color:#003bb3}.btn-primary:active,.btn-primary.active{background-color:#039 \9}.btn-warning{color:#fff;text-shadow:0 -1px 0 rgba(0,0,0,0.25);background-color:#faa732;background-image:-moz-linear-gradient(top,#fbb450,#f89406);background-image:-webkit-gradient(linear,0 0,0 100%,from(#fbb450),to(#f89406));background-image:-webkit-linear-gradient(top,#fbb450,#f89406);background-image:-o-linear-gradient(top,#fbb450,#f89406);background-image:linear-gradient(to bottom,#fbb450,#f89406);background-repeat:repeat-x;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#fffbb450',endColorstr='#fff89406',GradientType=0);border-color:#f89406 #f89406 #ad6704;border-color:rgba(0,0,0,0.1) rgba(0,0,0,0.1) rgba(0,0,0,0.25);*background-color:#f89406;filter:progid:DXImageTransform.Microsoft.gradient(enabled = false)}.btn-warning:hover,.btn-warning:focus,.btn-warning:aLine truncated
|
||||
.btn{display:inline-block;*display:inline;*zoom:1;padding:4px 12px;margin-bottom:0;font-size:14px;line-height:20px;text-align:center;vertical-align:middle;cursor:pointer;color:#333;text-shadow:0 1px 1px rgba(255,255,255,0.75);background-color:#f5f5f5;background-image:-moz-linear-gradient(top,#fff,#e6e6e6);background-image:-webkit-gradient(linear,0 0,0 100%,from(#fff),to(#e6e6e6));background-image:-webkit-linear-gradient(top,#fff,#e6e6e6);background-image:-o-linear-gradient(top,#fff,#e6e6e6);background-image:linear-gradient(to bottom,#fff,#e6e6e6);background-repeat:repeat-x;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#ffffffff',endColorstr='#ffe6e6e6',GradientType=0);border-color:#e6e6e6 #e6e6e6 #bfbfbf;border-color:rgba(0,0,0,0.1) rgba(0,0,0,0.1) rgba(0,0,0,0.25);*background-color:#e6e6e6;filter:progid:DXImageTransform.Microsoft.gradient(enabled = false);border:1px solid #ccc;*border:0;border-bottom-color:#b3b3b3;-webkit-border-radius:4px;-moz-border-radius:4px;border-radius:4px;*margin-left:.3em;-webkit-box-shadow:inset 0 1px 0 rgba(255,255,255,.2),0 1px 2px rgba(0,0,0,.05);-moz-box-shadow:inset 0 1px 0 rgba(255,255,255,.2),0 1px 2px rgba(0,0,0,.05);box-shadow:inset 0 1px 0 rgba(255,255,255,.2),0 1px 2px rgba(0,0,0,.05)}.btn:hover,.btn:focus,.btn:active,.btn.active,.btn.disabled,.btn[disabled]{color:#333;background-color:#e6e6e6;*background-color:#d9d9d9}.btn:active,.btn.active{background-color:#ccc \9}.btn:first-child{*margin-left:0}.btn:hover,.btn:focus{color:#333;text-decoration:none;background-position:0 -15px;-webkit-transition:background-position .1s linear;-moz-transition:background-position .1s linear;-o-transition:background-position .1s linear;transition:background-position .1s linear}.btn:focus{outline:thin dotted #333;outline:5px auto -webkit-focus-ring-color;outline-offset:-2px}.btn.active,.btn:active{background-image:none;outline:0;-webkit-box-shadow:inset 0 2px 4px rgba(0,0,0,.15),0 1px 2px rgba(0,0,0,.05);-moz-box-shadow:inset 0 2px 4px rgba(0,0,0,.15),0 1px 2px rgba(0,0,0,.05);box-shadow:inset 0 2px 4px rgba(0,0,0,.15),0 1px 2px rgba(0,0,0,.05)}.btn.disabled,.btn[disabled]{cursor:default;background-image:none;opacity:.65;filter:alpha(opacity=65);-webkit-box-shadow:none;-moz-box-shadow:none;box-shadow:none}.btn-large{padding:11px 19px;font-size:17.5px;-webkit-border-radius:6px;-moz-border-radius:6px;border-radius:6px}.btn-large [class^="icon-"],.btn-large [class*=" icon-"]{margin-top:4px}.btn-small{padding:2px 10px;font-size:11.9px;-webkit-border-radius:3px;-moz-border-radius:3px;border-radius:3px}.btn-small [class^="icon-"],.btn-small [class*=" icon-"]{margin-top:0}.btn-mini [class^="icon-"],.btn-mini [class*=" icon-"]{margin-top:-1px}.btn-mini{padding:0 6px;font-size:10.5px;-webkit-border-radius:3px;-moz-border-radius:3px;border-radius:3px}.btn-block{display:block;width:100%;padding-left:0;padding-right:0;-webkit-box-sizing:border-box;-moz-box-sizing:border-box;box-sizing:border-box}.btn-block+.btn-block{margin-top:5px}input[type="submit"].btn-block,input[type="reset"].btn-block,input[type="button"].btn-block{width:100%}.btn-primary.active,.btn-warning.active,.btn-danger.active,.btn-success.active,.btn-info.active,.btn-inverse.active{color:rgba(255,255,255,0.75)}.btn-primary{color:#fff;text-shadow:0 -1px 0 rgba(0,0,0,0.25);background-color:#006dcc;background-image:-moz-linear-gradient(top,#08c,#04c);background-image:-webkit-gradient(linear,0 0,0 100%,from(#08c),to(#04c));background-image:-webkit-linear-gradient(top,#08c,#04c);background-image:-o-linear-gradient(top,#08c,#04c);background-image:linear-gradient(to bottom,#08c,#04c);background-repeat:repeat-x;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#ff0088cc',endColorstr='#ff0044cc',GradientType=0);border-color:#04c #04c #002a80;border-color:rgba(0,0,0,0.1) rgba(0,0,0,0.1) rgba(0,0,0,0.25);*background-color:#04c;filter:progid:DXImageTransform.Microsoft.gradient(enabled = false)}.btn-primary:hover,.btn-primary:focus,.btn-primary:active,.btn-primary.active,.btn-primary.disabled,.btn-primary[disabled]{color:#fff;background-color:#04c;*background-color:#003bb3}.btn-primary:active,.btn-primary.active{background-color:#039 \9}.btn-warning{color:#fff;text-shadow:0 -1px 0 rgba(0,0,0,0.25);background-color:#faa732;background-image:-moz-linear-gradient(top,#fbb450,#f89406);background-image:-webkit-gradient(linear,0 0,0 100%,from(#fbb450),to(#f89406));background-image:-webkit-linear-gradient(top,#fbb450,#f89406);background-image:-o-linear-gradient(top,#fbb450,#f89406);background-image:linear-gradient(to bottom,#fbb450,#f89406);background-repeat:repeat-x;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#fffbb450',endColorstr='#fff89406',GradientType=0);border-color:#f89406 #f89406 #ad6704;border-color:rgba(0,0,0,0.1) rgba(0,0,0,0.1) rgba(0,0,0,0.25);*background-color:#f89406;filter:progid:DXImageTransform.Microsoft.gradient(enabled = false)}.btn-warning:hover,.btn-warning:focus,.btn-warning:aLine truncated
|
||||
@@ -379,7 +379,7 @@ GCODE.renderer = (function(){
|
||||
};
|
||||
|
||||
var drawLayer = function(layerNum, fromProgress, toProgress, isNotCurrentLayer){
|
||||
console.log("Drawing layer " + layerNum + " from " + fromProgress + " to " + toProgress + " (current: " + !isNotCurrentLayer + ")");
|
||||
log.trace("Drawing layer " + layerNum + " from " + fromProgress + " to " + toProgress + " (current: " + !isNotCurrentLayer + ")");
|
||||
|
||||
var i;
|
||||
|
||||
|
||||
@@ -250,7 +250,6 @@ function DataUpdater(allViewModels) {
|
||||
text: _.sprintf(gettext("Streamed %(local)s to %(remote)s on SD, took %(time).2f seconds"), payload),
|
||||
type: "success"
|
||||
});
|
||||
gcodeFilesViewModel.requestData(payload.remote, "sdcard");
|
||||
}
|
||||
|
||||
var legacyEventHandlers = {
|
||||
|
||||
@@ -7,6 +7,72 @@ $(function() {
|
||||
|
||||
log.setLevel(CONFIG_DEBUG ? "debug" : "info");
|
||||
|
||||
//~~ setup browser and internal tab tracking (in 1.3.0 that will be
|
||||
// much nicer with the global OctoPrint object...)
|
||||
|
||||
var tabTracking = (function() {
|
||||
var exports = {
|
||||
browserTabVisibility: undefined,
|
||||
selectedTab: undefined
|
||||
};
|
||||
|
||||
var browserVisibilityCallbacks = [];
|
||||
|
||||
var getHiddenProp = function() {
|
||||
var prefixes = ["webkit", "moz", "ms", "o"];
|
||||
|
||||
// if "hidden" is natively supported just return it
|
||||
if ("hidden" in document) {
|
||||
return "hidden"
|
||||
}
|
||||
|
||||
// otherwise loop over all the known prefixes until we find one
|
||||
var vendorPrefix = _.find(prefixes, function(prefix) {
|
||||
return (prefix + "Hidden" in document);
|
||||
});
|
||||
if (vendorPrefix !== undefined) {
|
||||
return vendorPrefix + "Hidden";
|
||||
}
|
||||
|
||||
// nothing found
|
||||
return undefined;
|
||||
};
|
||||
|
||||
var isHidden = function() {
|
||||
var prop = getHiddenProp();
|
||||
if (!prop) return false;
|
||||
|
||||
return document[prop];
|
||||
};
|
||||
|
||||
var updateBrowserVisibility = function() {
|
||||
var visible = !isHidden();
|
||||
exports.browserTabVisible = visible;
|
||||
_.each(browserVisibilityCallbacks, function(callback) {
|
||||
callback(visible);
|
||||
})
|
||||
};
|
||||
|
||||
// register for browser visibility tracking
|
||||
|
||||
var prop = getHiddenProp();
|
||||
if (!prop) return undefined;
|
||||
|
||||
var eventName = prop.replace(/[H|h]idden/, "") + "visibilitychange";
|
||||
document.addEventListener(eventName, updateBrowserVisibility);
|
||||
|
||||
updateBrowserVisibility();
|
||||
|
||||
// exports
|
||||
|
||||
exports.isVisible = function() { return !isHidden() };
|
||||
exports.onBrowserVisibilityChange = function(callback) {
|
||||
browserVisibilityCallbacks.push(callback);
|
||||
};
|
||||
|
||||
return exports;
|
||||
})();
|
||||
|
||||
//~~ AJAX setup
|
||||
|
||||
// work around a stupid iOS6 bug where ajax requests get cached and only work once, as described at
|
||||
@@ -67,6 +133,18 @@ $(function() {
|
||||
// the view model map is our basic look up table for dependencies that may be injected into other view models
|
||||
var viewModelMap = {};
|
||||
|
||||
// We put our tabTracking into the viewModelMap as a workaround until
|
||||
// our global OctoPrint object becomes available in 1.3.0. This way
|
||||
// we'll still be able to access it in our view models.
|
||||
//
|
||||
// NOTE TO DEVELOPERS: Do NOT depend on this dependency in your custom
|
||||
// view models. It is ONLY provided for the core application to be able
|
||||
// to backport a fix from the 1.3.0 development branch and WILL BE
|
||||
// REMOVED once 1.3.0 gets released without any fallback!
|
||||
//
|
||||
// TODO: Remove with release of 1.3.0
|
||||
viewModelMap.tabTracking = tabTracking;
|
||||
|
||||
// Fix Function#name on browsers that do not support it (IE):
|
||||
// see: http://stackoverflow.com/questions/6903762/function-name-not-supported-in-ie
|
||||
if (!(function f() {}).name) {
|
||||
@@ -371,16 +449,22 @@ $(function() {
|
||||
$('.nav-pills, .nav-tabs').tabdrop();
|
||||
|
||||
// Allow components to react to tab change
|
||||
var tabs = $('#tabs a[data-toggle="tab"]');
|
||||
tabs.on('show', function (e) {
|
||||
var current = e.target.hash;
|
||||
var previous = e.relatedTarget.hash;
|
||||
var onTabChange = function(current, previous) {
|
||||
log.debug("Selected OctoPrint tab changed: previous = " + previous + ", current = " + current);
|
||||
tabTracking.selectedTab = current;
|
||||
|
||||
_.each(allViewModels, function(viewModel) {
|
||||
if (viewModel.hasOwnProperty("onTabChange")) {
|
||||
viewModel.onTabChange(current, previous);
|
||||
}
|
||||
});
|
||||
};
|
||||
|
||||
var tabs = $('#tabs a[data-toggle="tab"]');
|
||||
tabs.on('show', function (e) {
|
||||
var current = e.target.hash;
|
||||
var previous = e.relatedTarget.hash;
|
||||
onTabChange(current, previous);
|
||||
});
|
||||
|
||||
tabs.on('shown', function (e) {
|
||||
@@ -394,6 +478,8 @@ $(function() {
|
||||
});
|
||||
});
|
||||
|
||||
onTabChange(OCTOPRINT_INITIAL_TAB);
|
||||
|
||||
// Fix input element click problems on dropdowns
|
||||
$(".dropdown input, .dropdown label").click(function(e) {
|
||||
e.stopPropagation();
|
||||
@@ -485,11 +571,22 @@ $(function() {
|
||||
});
|
||||
log.info("... binding done");
|
||||
|
||||
// startup complete
|
||||
_.each(allViewModels, function(viewModel) {
|
||||
if (viewModel.hasOwnProperty("onStartupComplete")) {
|
||||
viewModel.onStartupComplete();
|
||||
}
|
||||
});
|
||||
|
||||
// make sure we can track the browser tab visibility
|
||||
tabTracking.onBrowserVisibilityChange(function(status) {
|
||||
log.debug("Browser tab is now " + (status ? "visible" : "hidden"));
|
||||
_.each(allViewModels, function(viewModel) {
|
||||
if (viewModel.hasOwnProperty("onBrowserTabVisibilityChange")) {
|
||||
viewModel.onBrowserTabVisibilityChange(status);
|
||||
}
|
||||
});
|
||||
});
|
||||
};
|
||||
|
||||
if (!_.has(viewModelMap, "settingsViewModel")) {
|
||||
|
||||
@@ -5,6 +5,9 @@ $(function() {
|
||||
self.loginState = parameters[0];
|
||||
self.settings = parameters[1];
|
||||
|
||||
// TODO remove with release of 1.3.0 and switch to OctoPrint.coreui usage
|
||||
self.tabTracking = parameters[2];
|
||||
|
||||
self._createToolEntry = function () {
|
||||
return {
|
||||
name: ko.observable(),
|
||||
@@ -415,31 +418,51 @@ $(function() {
|
||||
|
||||
self.onSettingsBeforeSave = self.updateRotatorWidth;
|
||||
|
||||
self._disableWebcam = function() {
|
||||
// only disable webcam stream if tab is out of focus for more than 5s, otherwise we might cause
|
||||
// more load by the constant connection creation than by the actual webcam stream
|
||||
self.webcamDisableTimeout = setTimeout(function () {
|
||||
$("#webcam_image").attr("src", "");
|
||||
}, 5000);
|
||||
};
|
||||
|
||||
self._enableWebcam = function() {
|
||||
if (self.tabTracking.selectedTab != "#control" || !self.tabTracking.browserTabVisible) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (self.webcamDisableTimeout != undefined) {
|
||||
clearTimeout(self.webcamDisableTimeout);
|
||||
}
|
||||
var webcamImage = $("#webcam_image");
|
||||
var currentSrc = webcamImage.attr("src");
|
||||
if (currentSrc === undefined || currentSrc.trim() == "") {
|
||||
var newSrc = CONFIG_WEBCAM_STREAM;
|
||||
if (CONFIG_WEBCAM_STREAM.lastIndexOf("?") > -1) {
|
||||
newSrc += "&";
|
||||
} else {
|
||||
newSrc += "?";
|
||||
}
|
||||
newSrc += new Date().getTime();
|
||||
|
||||
self.updateRotatorWidth();
|
||||
webcamImage.attr("src", newSrc);
|
||||
}
|
||||
};
|
||||
|
||||
self.onTabChange = function (current, previous) {
|
||||
if (current == "#control") {
|
||||
if (self.webcamDisableTimeout != undefined) {
|
||||
clearTimeout(self.webcamDisableTimeout);
|
||||
}
|
||||
var webcamImage = $("#webcam_image");
|
||||
var currentSrc = webcamImage.attr("src");
|
||||
if (currentSrc === undefined || currentSrc.trim() == "") {
|
||||
var newSrc = CONFIG_WEBCAM_STREAM;
|
||||
if (CONFIG_WEBCAM_STREAM.lastIndexOf("?") > -1) {
|
||||
newSrc += "&";
|
||||
} else {
|
||||
newSrc += "?";
|
||||
}
|
||||
newSrc += new Date().getTime();
|
||||
|
||||
self.updateRotatorWidth();
|
||||
webcamImage.attr("src", newSrc);
|
||||
}
|
||||
self._enableWebcam();
|
||||
} else if (previous == "#control") {
|
||||
// only disable webcam stream if tab is out of focus for more than 5s, otherwise we might cause
|
||||
// more load by the constant connection creation than by the actual webcam stream
|
||||
self.webcamDisableTimeout = setTimeout(function () {
|
||||
$("#webcam_image").attr("src", "");
|
||||
}, 5000);
|
||||
self._disableWebcam();
|
||||
}
|
||||
};
|
||||
|
||||
self.onBrowserTabVisibilityChange = function(status) {
|
||||
if (status) {
|
||||
self._enableWebcam();
|
||||
} else {
|
||||
self._disableWebcam();
|
||||
}
|
||||
};
|
||||
|
||||
@@ -565,7 +588,7 @@ $(function() {
|
||||
|
||||
OCTOPRINT_VIEWMODELS.push([
|
||||
ControlViewModel,
|
||||
["loginStateViewModel", "settingsViewModel"],
|
||||
["loginStateViewModel", "settingsViewModel", "tabTracking"],
|
||||
"#control"
|
||||
]);
|
||||
});
|
||||
@@ -600,6 +600,10 @@ $(function() {
|
||||
self.onEventMetadataStatisticsUpdated = function(payload) {
|
||||
self.requestData();
|
||||
};
|
||||
|
||||
self.onEventTransferDone = function(payload) {
|
||||
self.requestData(payload.remote, "sdcard");
|
||||
};
|
||||
}
|
||||
|
||||
OCTOPRINT_VIEWMODELS.push([
|
||||
|
||||
@@ -5,6 +5,9 @@ $(function() {
|
||||
self.loginState = parameters[0];
|
||||
self.settings = parameters[1];
|
||||
|
||||
// TODO remove with release of 1.3.0 and switch to OctoPrint.coreui usage
|
||||
self.tabTracking = parameters[2];
|
||||
|
||||
self.ui_progress_percentage = ko.observable();
|
||||
self.ui_progress_type = ko.observable();
|
||||
self.ui_progress_text = ko.computed(function() {
|
||||
@@ -339,6 +342,21 @@ $(function() {
|
||||
self._processData(data);
|
||||
};
|
||||
|
||||
self._renderPercentage = function(percentage) {
|
||||
var cmdIndex = GCODE.gCodeReader.getCmdIndexForPercentage(percentage);
|
||||
if (!cmdIndex) return;
|
||||
|
||||
GCODE.renderer.render(cmdIndex.layer, 0, cmdIndex.cmd);
|
||||
GCODE.ui.updateLayerInfo(cmdIndex.layer);
|
||||
|
||||
if (self.layerSlider != undefined) {
|
||||
self.layerSlider.slider("setValue", cmdIndex.layer);
|
||||
}
|
||||
if (self.layerCommandSlider != undefined) {
|
||||
self.layerCommandSlider.slider("setValue", [0, cmdIndex.cmd]);
|
||||
}
|
||||
};
|
||||
|
||||
self._processData = function(data) {
|
||||
if (!data.job.file || !data.job.file.name && (self.loadedFilename || self.loadedFileDate)) {
|
||||
self.waitForApproval(false);
|
||||
@@ -358,19 +376,8 @@ $(function() {
|
||||
if(self.loadedFilename
|
||||
&& self.loadedFilename == data.job.file.name
|
||||
&& self.loadedFileDate == data.job.file.date) {
|
||||
if (self.currentlyPrinting && self.renderer_syncProgress() && !self.waitForApproval()) {
|
||||
var cmdIndex = GCODE.gCodeReader.getCmdIndexForPercentage(data.progress.completion);
|
||||
if(cmdIndex){
|
||||
GCODE.renderer.render(cmdIndex.layer, 0, cmdIndex.cmd);
|
||||
GCODE.ui.updateLayerInfo(cmdIndex.layer);
|
||||
|
||||
if (self.layerSlider != undefined) {
|
||||
self.layerSlider.slider("setValue", cmdIndex.layer);
|
||||
}
|
||||
if (self.layerCommandSlider != undefined) {
|
||||
self.layerCommandSlider.slider("setValue", [0, cmdIndex.cmd]);
|
||||
}
|
||||
}
|
||||
if (self.tabTracking.browserTabVisible && self.tabActive && self.currentlyPrinting && self.renderer_syncProgress() && !self.waitForApproval()) {
|
||||
self._renderPercentage(data.progress.completion);
|
||||
}
|
||||
self.errorCount = 0
|
||||
} else {
|
||||
@@ -394,6 +401,12 @@ $(function() {
|
||||
}
|
||||
};
|
||||
|
||||
self.onEventPrintDone = function() {
|
||||
if (self.renderer_syncProgress() && !self.waitForApproval()) {
|
||||
self._renderPercentage(100.0);
|
||||
}
|
||||
};
|
||||
|
||||
self.approveLargeFile = function() {
|
||||
self.waitForApproval(false);
|
||||
self.loadFile(self.selectedFile.name(), self.selectedFile.date());
|
||||
@@ -504,13 +517,16 @@ $(function() {
|
||||
|
||||
self.onBeforeBinding = function() {
|
||||
self.initialize();
|
||||
}
|
||||
};
|
||||
|
||||
self.onTabChange = function(current, previous) {
|
||||
self.tabActive = current == "#gcode";
|
||||
};
|
||||
}
|
||||
|
||||
OCTOPRINT_VIEWMODELS.push([
|
||||
GcodeViewModel,
|
||||
["loginStateViewModel", "settingsViewModel"],
|
||||
["loginStateViewModel", "settingsViewModel", "tabTracking"],
|
||||
"#gcode"
|
||||
]);
|
||||
});
|
||||
@@ -15,7 +15,7 @@ $(function() {
|
||||
height: 200,
|
||||
origin: "lowerleft"
|
||||
},
|
||||
heatedBed: false,
|
||||
heatedBed: true,
|
||||
axes: {
|
||||
x: {speed: 6000, inverted: false},
|
||||
y: {speed: 6000, inverted: false},
|
||||
|
||||
@@ -36,7 +36,7 @@ $(function() {
|
||||
|
||||
self.heaterOptions = ko.observable({});
|
||||
|
||||
self._numExtrudersUpdated = function() {
|
||||
self._printerProfileUpdated = function() {
|
||||
var graphColors = ["red", "orange", "green", "brown", "purple"];
|
||||
var heaterOptions = {};
|
||||
var tools = self.tools();
|
||||
@@ -69,15 +69,21 @@ $(function() {
|
||||
}
|
||||
|
||||
// print bed
|
||||
heaterOptions["bed"] = {name: gettext("Bed"), color: "blue"};
|
||||
if (self.settingsViewModel.printerProfiles.currentProfileData().heatedBed()) {
|
||||
self.hasBed(true);
|
||||
heaterOptions["bed"] = {name: gettext("Bed"), color: "blue"};
|
||||
} else {
|
||||
self.hasBed(false);
|
||||
}
|
||||
|
||||
// write back
|
||||
self.heaterOptions(heaterOptions);
|
||||
self.tools(tools);
|
||||
};
|
||||
self.settingsViewModel.printerProfiles.currentProfileData.subscribe(function() {
|
||||
self._numExtrudersUpdated();
|
||||
self.settingsViewModel.printerProfiles.currentProfileData().extruder.count.subscribe(self._numExtrudersUpdated);
|
||||
self._printerProfileUpdated();
|
||||
self.settingsViewModel.printerProfiles.currentProfileData().extruder.count.subscribe(self._printerProfileUpdated);
|
||||
self.settingsViewModel.printerProfiles.currentProfileData().heatedBed.subscribe(self._printerProfileUpdated());
|
||||
});
|
||||
|
||||
self.temperatures = [];
|
||||
@@ -152,11 +158,8 @@ $(function() {
|
||||
}
|
||||
|
||||
if (lastData.hasOwnProperty("bed")) {
|
||||
self.hasBed(true);
|
||||
self.bedTemp["actual"](lastData.bed.actual);
|
||||
self.bedTemp["target"](lastData.bed.target);
|
||||
} else {
|
||||
self.hasBed(false);
|
||||
}
|
||||
|
||||
if (!CONFIG_TEMPERATURE_GRAPH) return;
|
||||
@@ -208,8 +211,6 @@ $(function() {
|
||||
if (!d[type]) return;
|
||||
result[type].actual.push([time, d[type].actual]);
|
||||
result[type].target.push([time, d[type].target]);
|
||||
|
||||
self.hasBed(self.hasBed() || (type == "bed"));
|
||||
})
|
||||
});
|
||||
|
||||
@@ -375,4 +376,4 @@ $(function() {
|
||||
["loginStateViewModel", "settingsViewModel"],
|
||||
"#temp"
|
||||
]);
|
||||
});
|
||||
});
|
||||
@@ -7,6 +7,7 @@ $(function() {
|
||||
|
||||
self.log = ko.observableArray([]);
|
||||
self.buffer = ko.observable(300);
|
||||
self.upperLimit = ko.observable(3000);
|
||||
|
||||
self.command = ko.observable(undefined);
|
||||
|
||||
@@ -34,7 +35,8 @@ $(function() {
|
||||
|
||||
var filtered = false;
|
||||
var result = [];
|
||||
_.each(self.log(), function(entry) {
|
||||
var lines = self.log();
|
||||
_.each(lines, function(entry) {
|
||||
if (lineVisible(entry)) {
|
||||
result.push(entry);
|
||||
filtered = false;
|
||||
@@ -46,19 +48,30 @@ $(function() {
|
||||
|
||||
return result;
|
||||
});
|
||||
self.displayedLines.subscribe(function() {
|
||||
self.updateOutput();
|
||||
});
|
||||
|
||||
self.lineCount = ko.computed(function() {
|
||||
var total = self.log().length;
|
||||
var displayed = _.filter(self.displayedLines(), function(entry) { return entry.type == "line" }).length;
|
||||
var regex = self.filterRegex();
|
||||
var lineVisible = function(entry) {
|
||||
return regex == undefined || !entry.line.match(regex);
|
||||
};
|
||||
|
||||
var lines = self.log();
|
||||
var total = lines.length;
|
||||
var displayed = _.filter(lines, lineVisible).length;
|
||||
var filtered = total - displayed;
|
||||
|
||||
if (total == displayed) {
|
||||
return _.sprintf(gettext("showing %(displayed)d lines"), {displayed: displayed});
|
||||
if (filtered > 0) {
|
||||
if (total > self.upperLimit()) {
|
||||
return _.sprintf(gettext("showing %(displayed)d lines (%(filtered)d of %(total)d total lines filtered, buffer full)"), {displayed: displayed, total: total, filtered: filtered});
|
||||
} else {
|
||||
return _.sprintf(gettext("showing %(displayed)d lines (%(filtered)d of %(total)d total lines filtered)"), {displayed: displayed, total: total, filtered: filtered});
|
||||
}
|
||||
} else {
|
||||
return _.sprintf(gettext("showing %(displayed)d lines (%(filtered)d of %(total)d total lines filtered)"), {displayed: displayed, total: total, filtered: filtered});
|
||||
if (total > self.upperLimit()) {
|
||||
return _.sprintf(gettext("showing %(displayed)d lines (buffer full)"), {displayed: displayed});
|
||||
} else {
|
||||
return _.sprintf(gettext("showing %(displayed)d lines"), {displayed: displayed});
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
@@ -84,14 +97,31 @@ $(function() {
|
||||
};
|
||||
|
||||
self._processCurrentLogData = function(data) {
|
||||
self.log(self.log().concat(_.map(data, function(line) { return self._toInternalFormat(line) })));
|
||||
if (self.autoscrollEnabled()) {
|
||||
self.log(self.log.slice(-self.buffer()));
|
||||
var length = self.log().length;
|
||||
if (length >= self.upperLimit()) {
|
||||
var cutoff = "--- too many lines to buffer, cut off ---";
|
||||
var last = self.log()[length-1];
|
||||
if (!last || last.type != "cut" || last.line != cutoff) {
|
||||
self.log(self.log().concat(self._toInternalFormat(cutoff, "cut")));
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
var newLog = self.log().concat(_.map(data, function(line) { return self._toInternalFormat(line) }));
|
||||
if (self.autoscrollEnabled()) {
|
||||
// we only keep the last <buffer> entries
|
||||
newLog = newLog.slice(-self.buffer());
|
||||
} else if (newLog.length > self.upperLimit()) {
|
||||
// we only keep the first <upperLimit> entries
|
||||
newLog = newLog.slice(0, self.upperLimit());
|
||||
}
|
||||
self.log(newLog);
|
||||
self.updateOutput();
|
||||
};
|
||||
|
||||
self._processHistoryLogData = function(data) {
|
||||
self.log(_.map(data, function(line) { return self._toInternalFormat(line) }));
|
||||
self.updateOutput();
|
||||
};
|
||||
|
||||
self._toInternalFormat = function(line, type) {
|
||||
@@ -141,7 +171,7 @@ $(function() {
|
||||
self.scrollToEnd = function() {
|
||||
var container = $("#terminal-output");
|
||||
if (container.length) {
|
||||
container.scrollTop(container[0].scrollHeight - container.height())
|
||||
container.scrollTop(container[0].scrollHeight);
|
||||
}
|
||||
};
|
||||
|
||||
@@ -232,4 +262,4 @@ $(function() {
|
||||
["loginStateViewModel", "settingsViewModel"],
|
||||
"#term"
|
||||
]);
|
||||
});
|
||||
});
|
||||
@@ -396,10 +396,17 @@ ul.dropdown-menu li a {
|
||||
left: 0;
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
z-index: 10001;
|
||||
display: none;
|
||||
}
|
||||
|
||||
#offline_overlay {
|
||||
z-index: 10002;
|
||||
}
|
||||
|
||||
#reloadui_overlay {
|
||||
z-index: 10001;
|
||||
}
|
||||
|
||||
#offline_overlay_background,
|
||||
#reloadui_overlay_background {
|
||||
position: fixed;
|
||||
|
||||
@@ -33,4 +33,12 @@
|
||||
var OCTOPRINT_VIEWMODELS = [];
|
||||
var ADDITIONAL_VIEWMODELS = [];
|
||||
var OCTOPRINT_ADDITIONAL_BINDINGS = [];
|
||||
|
||||
{% if templates.tab.order %}
|
||||
{% set first_tab = templates.tab.order[0] %}
|
||||
{% set entry, data = templates.tab.entries[first_tab] %}
|
||||
var OCTOPRINT_INITIAL_TAB = "#{{ data._div }}";
|
||||
{% else %}
|
||||
var OCTOPRINT_INITIAL_TAB = undefined;
|
||||
{% endif %}
|
||||
</script>
|
||||
@@ -1,5 +1,5 @@
|
||||
{% if enableTemperatureGraph %}
|
||||
<div class="row" style="padding-left: 20px">
|
||||
<div class="row-fluid">
|
||||
<div id="temperature-graph"></div>
|
||||
</div>
|
||||
{% endif %}
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
<div class="terminal">
|
||||
<pre id="terminal-output" class="pre-scrollable" data-bind="foreach: displayedLines"><span data-bind="text: line, css: {muted: type == 'filtered'}"></span><br></pre>
|
||||
<pre id="terminal-output" class="pre-scrollable" data-bind="foreach: displayedLines"><span data-bind="text: line, css: {muted: type == 'filtered' || type == 'cut'}"></span><br></pre>
|
||||
<small class="pull-left"><button class="btn btn-mini" data-bind="click: toggleAutoscroll, css: {active: autoscrollEnabled}">{{ _('Autoscroll') }}</button> <span data-bind="text: lineCount"></span></small>
|
||||
<small class="pull-right"><a href="#" data-bind="click: scrollToEnd">{{ _("Scroll to end") }}</a> | <a href="#" data-bind="click: selectAll">{{ _("Select all") }}</a></small>
|
||||
</div>
|
||||
|
||||
Binary file not shown.
File diff suppressed because it is too large.
Load diff
+128
-17
@@ -378,6 +378,14 @@ def dict_merge(a, b):
|
||||
|
||||
Taken from https://www.xormedia.com/recursively-merge-dictionaries-in-python/
|
||||
|
||||
Example::
|
||||
|
||||
>>> a = dict(foo="foo", bar="bar", fnord=dict(a=1))
|
||||
>>> b = dict(foo="other foo", fnord=dict(b=2, l=["some", "list"]))
|
||||
>>> expected = dict(foo="other foo", bar="bar", fnord=dict(a=1, b=2, l=["some", "list"]))
|
||||
>>> dict_merge(a, b) == expected
|
||||
True
|
||||
|
||||
Arguments:
|
||||
a (dict): The dictionary to merge ``b`` into
|
||||
b (dict): The dictionary to merge into ``a``
|
||||
@@ -399,14 +407,24 @@ def dict_merge(a, b):
|
||||
return result
|
||||
|
||||
|
||||
def dict_clean(a, b):
|
||||
def dict_sanitize(a, b):
|
||||
"""
|
||||
Recursively deep-cleans ``b`` from ``a``, removing all keys and corresponding values from ``a`` that appear in
|
||||
``b``.
|
||||
Recursively deep-sanitizes ``a`` based on ``b``, removing all keys (and
|
||||
associated values) from ``a`` that do not appear in ``b``.
|
||||
|
||||
Example::
|
||||
|
||||
>>> a = dict(foo="foo", bar="bar", fnord=dict(a=1, b=2, l=["some", "list"]))
|
||||
>>> b = dict(foo=None, fnord=dict(a=None, b=None))
|
||||
>>> expected = dict(foo="foo", fnord=dict(a=1, b=2))
|
||||
>>> dict_sanitize(a, b) == expected
|
||||
True
|
||||
>>> dict_clean(a, b) == expected
|
||||
True
|
||||
|
||||
Arguments:
|
||||
a (dict): The dictionary to clean from ``b``.
|
||||
b (dict): The dictionary to clean ``b`` from.
|
||||
a (dict): The dictionary to clean against ``b``.
|
||||
b (dict): The dictionary containing the key structure to clean from ``a``.
|
||||
|
||||
Results:
|
||||
dict: A new dict based on ``a`` with all keys (and corresponding values) found in ``b`` removed.
|
||||
@@ -421,21 +439,87 @@ def dict_clean(a, b):
|
||||
if not k in b:
|
||||
del result[k]
|
||||
elif isinstance(v, dict):
|
||||
result[k] = dict_clean(v, b[k])
|
||||
result[k] = dict_sanitize(v, b[k])
|
||||
else:
|
||||
result[k] = deepcopy(v)
|
||||
return result
|
||||
dict_clean = deprecated("dict_clean has been renamed to dict_sanitize",
|
||||
includedoc="Replaced by :func:`dict_sanitize`")(dict_sanitize)
|
||||
|
||||
|
||||
def dict_contains_keys(a, b):
|
||||
def dict_minimal_mergediff(source, target):
|
||||
"""
|
||||
Recursively deep-checks if ``a`` contains all keys found in ``b``.
|
||||
Recursively calculates the minimal dict that would be needed to be deep merged with
|
||||
a in order to produce the same result as deep merging a and b.
|
||||
|
||||
Example::
|
||||
|
||||
>>> dict_contains_keys(dict(foo="bar", fnord=dict(a=1, b=2, c=3)), dict(foo="some_other_bar", fnord=dict(b=100)))
|
||||
>>> a = dict(foo=dict(a=1, b=2), bar=dict(c=3, d=4))
|
||||
>>> b = dict(bar=dict(c=3, d=5), fnord=None)
|
||||
>>> c = dict_minimal_mergediff(a, b)
|
||||
>>> c == dict(bar=dict(d=5), fnord=None)
|
||||
True
|
||||
>>> dict_contains_keys(dict(foo="bar", fnord=dict(a=1, b=2, c=3)), dict(foo="some_other_bar", fnord=dict(b=100, d=20)))
|
||||
>>> dict_merge(a, c) == dict_merge(a, b)
|
||||
True
|
||||
|
||||
Arguments:
|
||||
source (dict): Source dictionary
|
||||
target (dict): Dictionary to compare to source dictionary and derive diff for
|
||||
|
||||
Returns:
|
||||
dict: The minimal dictionary to deep merge on ``source`` to get the same result
|
||||
as deep merging ``target`` on ``source``.
|
||||
"""
|
||||
|
||||
if not isinstance(source, dict) or not isinstance(target, dict):
|
||||
raise ValueError("source and target must be dictionaries")
|
||||
|
||||
if source == target:
|
||||
# shortcut: if both are equal, we return an empty dict as result
|
||||
return dict()
|
||||
|
||||
from copy import deepcopy
|
||||
|
||||
all_keys = set(source.keys() + target.keys())
|
||||
result = dict()
|
||||
for k in all_keys:
|
||||
if k not in target:
|
||||
# key not contained in target => not contained in result
|
||||
continue
|
||||
|
||||
if k in source:
|
||||
# key is present in both dicts, we have to take a look at the value
|
||||
value_source = source[k]
|
||||
value_target = target[k]
|
||||
|
||||
if value_source != value_target:
|
||||
# we only need to look further if the values are not equal
|
||||
|
||||
if isinstance(value_source, dict) and isinstance(value_target, dict):
|
||||
# both are dicts => deeper down it goes into the rabbit hole
|
||||
result[k] = dict_minimal_mergediff(value_source, value_target)
|
||||
else:
|
||||
# new b wins over old a
|
||||
result[k] = deepcopy(value_target)
|
||||
|
||||
else:
|
||||
# key is new, add it
|
||||
result[k] = deepcopy(target[k])
|
||||
return result
|
||||
|
||||
|
||||
def dict_contains_keys(keys, dictionary):
|
||||
"""
|
||||
Recursively deep-checks if ``dictionary`` contains all keys found in ``keys``.
|
||||
|
||||
Example::
|
||||
|
||||
>>> positive = dict(foo="some_other_bar", fnord=dict(b=100))
|
||||
>>> negative = dict(foo="some_other_bar", fnord=dict(b=100, d=20))
|
||||
>>> dictionary = dict(foo="bar", fnord=dict(a=1, b=2, c=3))
|
||||
>>> dict_contains_keys(positive, dictionary)
|
||||
True
|
||||
>>> dict_contains_keys(negative, dictionary)
|
||||
False
|
||||
|
||||
Arguments:
|
||||
@@ -446,14 +530,14 @@ def dict_contains_keys(a, b):
|
||||
boolean: True if all keys found in ``b`` are also present in ``a``, False otherwise.
|
||||
"""
|
||||
|
||||
if not isinstance(a, dict) or not isinstance(b, dict):
|
||||
if not isinstance(keys, dict) or not isinstance(dictionary, dict):
|
||||
return False
|
||||
|
||||
for k, v in a.iteritems():
|
||||
if not k in b:
|
||||
for k, v in keys.iteritems():
|
||||
if not k in dictionary:
|
||||
return False
|
||||
elif isinstance(v, dict):
|
||||
if not dict_contains_keys(v, b[k]):
|
||||
if not dict_contains_keys(v, dictionary[k]):
|
||||
return False
|
||||
|
||||
return True
|
||||
@@ -500,8 +584,10 @@ def address_for_client(host, port):
|
||||
@contextlib.contextmanager
|
||||
def atomic_write(filename, mode="w+b", prefix="tmp", suffix=""):
|
||||
temp_config = tempfile.NamedTemporaryFile(mode=mode, prefix=prefix, suffix=suffix, delete=False)
|
||||
yield temp_config
|
||||
temp_config.close()
|
||||
try:
|
||||
yield temp_config
|
||||
finally:
|
||||
temp_config.close()
|
||||
shutil.move(temp_config.name, filename)
|
||||
|
||||
|
||||
@@ -525,7 +611,32 @@ def bom_aware_open(filename, encoding="ascii", mode="r", **kwargs):
|
||||
if header.startswith(bom):
|
||||
encoding += "-sig"
|
||||
|
||||
return codecs.open(filename, encoding=encoding, **kwargs)
|
||||
return codecs.open(filename, encoding=encoding, mode=mode, **kwargs)
|
||||
|
||||
|
||||
def is_hidden_path(path):
|
||||
if path is None:
|
||||
# we define a None path as not hidden here
|
||||
return False
|
||||
|
||||
filename = os.path.basename(path)
|
||||
if filename.startswith("."):
|
||||
# filenames starting with a . are hidden
|
||||
return True
|
||||
|
||||
if sys.platform == "win32":
|
||||
# if we are running on windows we also try to read the hidden file
|
||||
# attribute via the windows api
|
||||
try:
|
||||
import ctypes
|
||||
attrs = ctypes.windll.kernel32.GetFileAttributesW(unicode(path))
|
||||
assert attrs != -1 # INVALID_FILE_ATTRIBUTES == -1
|
||||
return bool(attrs & 2) # FILE_ATTRIBUTE_HIDDEN == 2
|
||||
except (AttributeError, AssertionError):
|
||||
pass
|
||||
|
||||
# if we reach that point, the path is not hidden
|
||||
return False
|
||||
|
||||
|
||||
class RepeatedTimer(threading.Thread):
|
||||
|
||||
@@ -262,6 +262,7 @@ class MachineCom(object):
|
||||
self._serial_factory_hooks = self._pluginManager.get_hooks("octoprint.comm.transport.serial.factory")
|
||||
|
||||
# SD status data
|
||||
self._sdEnabled = settings().getBoolean(["feature", "sdSupport"])
|
||||
self._sdAvailable = False
|
||||
self._sdFileList = False
|
||||
self._sdFiles = []
|
||||
@@ -719,21 +720,28 @@ class MachineCom(object):
|
||||
return self._sdFiles
|
||||
|
||||
def startSdFileTransfer(self, filename):
|
||||
if not self.isOperational() or self.isBusy():
|
||||
if not self._sdEnabled:
|
||||
return
|
||||
|
||||
if not self.isOperational() or self.isBusy():
|
||||
return
|
||||
self._changeState(self.STATE_TRANSFERING_FILE)
|
||||
self.sendCommand("M28 %s" % filename.lower())
|
||||
|
||||
def endSdFileTransfer(self, filename):
|
||||
if not self.isOperational() or self.isBusy():
|
||||
if not self._sdEnabled:
|
||||
return
|
||||
|
||||
if not self.isOperational() or self.isBusy():
|
||||
return
|
||||
self.sendCommand("M29 %s" % filename.lower())
|
||||
self._changeState(self.STATE_OPERATIONAL)
|
||||
self.refreshSdFiles()
|
||||
|
||||
def deleteSdFile(self, filename):
|
||||
if not self._sdEnabled:
|
||||
return
|
||||
|
||||
if not self.isOperational() or (self.isBusy() and
|
||||
isinstance(self._currentFile, PrintingSdFileInformation) and
|
||||
self._currentFile.getFilename() == filename):
|
||||
@@ -744,13 +752,21 @@ class MachineCom(object):
|
||||
self.refreshSdFiles()
|
||||
|
||||
def refreshSdFiles(self):
|
||||
if not self._sdEnabled:
|
||||
return
|
||||
|
||||
if not self.isOperational() or self.isBusy():
|
||||
return
|
||||
|
||||
self.sendCommand("M20")
|
||||
|
||||
def initSdCard(self):
|
||||
if not self._sdEnabled:
|
||||
return
|
||||
|
||||
if not self.isOperational():
|
||||
return
|
||||
|
||||
self.sendCommand("M21")
|
||||
if settings().getBoolean(["feature", "sdAlwaysAvailable"]):
|
||||
self._sdAvailable = True
|
||||
@@ -758,6 +774,9 @@ class MachineCom(object):
|
||||
self._callback.on_comm_sd_state_change(self._sdAvailable)
|
||||
|
||||
def releaseSdCard(self):
|
||||
if not self._sdEnabled:
|
||||
return
|
||||
|
||||
if not self.isOperational() or (self.isBusy() and self.isSdFileSelected()):
|
||||
# do not release the sd card if we are currently printing from it
|
||||
return
|
||||
@@ -1314,6 +1333,11 @@ class MachineCom(object):
|
||||
return False
|
||||
|
||||
def _handleErrors(self, line):
|
||||
if line is None:
|
||||
return
|
||||
|
||||
lower_line = line.lower()
|
||||
|
||||
# No matter the state, if we see an error, goto the error state and store the error for reference.
|
||||
if line.startswith('Error:') or line.startswith('!!'):
|
||||
#Oh YEAH, consistency.
|
||||
@@ -1323,14 +1347,18 @@ class MachineCom(object):
|
||||
if regex_minMaxError.match(line):
|
||||
line = line.rstrip() + self._readline()
|
||||
|
||||
if 'line number' in line.lower() or 'checksum' in line.lower() or 'format error' in line.lower() or 'expected line' in line.lower():
|
||||
if 'line number' in lower_line or 'checksum' in lower_line or 'format error' in lower_line or 'expected line' in lower_line:
|
||||
#Skip the communication errors, as those get corrected.
|
||||
self._lastCommError = line[6:] if line.startswith("Error:") else line[2:]
|
||||
pass
|
||||
elif 'volume.init' in line.lower() or "openroot" in line.lower() or 'workdir' in line.lower()\
|
||||
or "error writing to file" in line.lower():
|
||||
elif 'volume.init' in lower_line or "openroot" in lower_line or 'workdir' in lower_line\
|
||||
or "error writing to file" in lower_line or "cannot open" in lower_line\
|
||||
or "cannot enter" in lower_line:
|
||||
#Also skip errors with the SD card
|
||||
pass
|
||||
elif 'unknown command' in lower_line:
|
||||
#Ignore unkown command errors, it could be a typo or some missing feature
|
||||
pass
|
||||
elif not self.isError():
|
||||
self._errorValue = line[6:] if line.startswith("Error:") else line[2:]
|
||||
self._changeState(self.STATE_ERROR)
|
||||
@@ -1701,6 +1729,18 @@ class MachineCom(object):
|
||||
return None, # Don't send the M0 or M1 to the machine, as M0 and M1 are handled as an LCD menu pause.
|
||||
_gcode_M1_queuing = _gcode_M0_queuing
|
||||
|
||||
def _gcode_M25_queuing(self, cmd, cmd_type=None):
|
||||
# M25 while not printing from SD will be handled as pause. This way it can be used as another marker
|
||||
# for GCODE induced pausing. Send it to the printer anyway though.
|
||||
if self.isPrinting() and not self.isSdPrinting():
|
||||
self.setPause(True)
|
||||
|
||||
def _gcode_M140_queuing(self, cmd, cmd_type=None):
|
||||
if not self._printerProfileManager.get_current_or_default()["heatedBed"]:
|
||||
self._log("Warn: Not sending \"{}\", printer profile has no heated bed".format(cmd))
|
||||
return None, # Don't send bed commands if we don't have a heated bed
|
||||
_gcode_M190_queuing = _gcode_M140_queuing
|
||||
|
||||
def _gcode_M104_sent(self, cmd, cmd_type=None):
|
||||
toolNum = self._currentTool
|
||||
toolMatch = regexes_parameters["intT"].search(cmd)
|
||||
@@ -1774,7 +1814,8 @@ class MachineCom(object):
|
||||
# are going to shutdown the connection in a second anyhow.
|
||||
for tool in range(self._printerProfileManager.get_current_or_default()["extruder"]["count"]):
|
||||
self._doIncrementAndSendWithChecksum("M104 T{tool} S0".format(tool=tool))
|
||||
self._doIncrementAndSendWithChecksum("M140 S0")
|
||||
if self._printerProfileManager.get_current_or_default()["heatedBed"]:
|
||||
self._doIncrementAndSendWithChecksum("M140 S0")
|
||||
|
||||
# close to reset host state
|
||||
self._errorValue = "Closing serial port due to emergency stop M112."
|
||||
|
||||
@@ -0,0 +1,50 @@
|
||||
# coding=utf-8
|
||||
from __future__ import absolute_import
|
||||
|
||||
__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html'
|
||||
__copyright__ = "Copyright (C) 2015 The OctoPrint Project - Released under terms of the AGPLv3 License"
|
||||
|
||||
import os
|
||||
|
||||
from jinja2.loaders import FileSystemLoader, TemplateNotFound, split_template_path
|
||||
|
||||
class FilteredFileSystemLoader(FileSystemLoader):
|
||||
"""
|
||||
Jinja2 ``FileSystemLoader`` subclass that allows filtering templates.
|
||||
|
||||
Only such templates will be accessible for whose paths the provided
|
||||
``path_filter`` filter function returns True.
|
||||
|
||||
``path_filter`` will receive the actual path on disc and should behave just
|
||||
like callables provided to Python's internal ``filter`` function, returning
|
||||
``True`` if the path is cleared and ``False`` if it is supposed to be removed
|
||||
from results and hence ``filter(path_filter, iterable)`` should be
|
||||
equivalent to ``[item for item in iterable if path_filter(item)]``.
|
||||
|
||||
If ``path_filter`` is not set or not a ``callable``, the loader will
|
||||
behave just like the regular Jinja2 ``FileSystemLoader``.
|
||||
"""
|
||||
def __init__(self, searchpath, path_filter=None, **kwargs):
|
||||
FileSystemLoader.__init__(self, searchpath, **kwargs)
|
||||
self.path_filter = path_filter
|
||||
|
||||
def get_source(self, environment, template):
|
||||
if callable(self.path_filter):
|
||||
pieces = split_template_path(template)
|
||||
if not self._combined_filter(os.path.join(*pieces)):
|
||||
raise TemplateNotFound(template)
|
||||
|
||||
return FileSystemLoader.get_source(self, environment, template)
|
||||
|
||||
def list_templates(self):
|
||||
result = FileSystemLoader.list_templates(self)
|
||||
|
||||
if callable(self.path_filter):
|
||||
result = sorted(filter(self._combined_filter, result))
|
||||
|
||||
return result
|
||||
|
||||
def _combined_filter(self, path):
|
||||
filter_results = map(lambda x: not os.path.exists(os.path.join(x, path)) or self.path_filter(os.path.join(x, path)),
|
||||
self.searchpath)
|
||||
return all(filter_results)
|
||||
@@ -0,0 +1,139 @@
|
||||
import unittest
|
||||
import mock
|
||||
|
||||
import octoprint.plugin
|
||||
|
||||
class BlueprintPluginTest(unittest.TestCase):
|
||||
|
||||
def setUp(self):
|
||||
self.basefolder = "/some/funny/basefolder"
|
||||
|
||||
self.plugin = octoprint.plugin.BlueprintPlugin()
|
||||
self.plugin._basefolder = self.basefolder
|
||||
|
||||
class MyAssetPlugin(octoprint.plugin.BlueprintPlugin, octoprint.plugin.AssetPlugin):
|
||||
def get_asset_folder(self):
|
||||
return "/some/asset/folder"
|
||||
|
||||
class MyTemplatePlugin(octoprint.plugin.BlueprintPlugin, octoprint.plugin.TemplatePlugin):
|
||||
def get_template_folder(self):
|
||||
return "/some/template/folder"
|
||||
|
||||
self.assetplugin = MyAssetPlugin()
|
||||
self.assetplugin._basefolder = self.basefolder
|
||||
|
||||
self.templateplugin = MyTemplatePlugin()
|
||||
self.templateplugin._basefolder = self.basefolder
|
||||
|
||||
def test_route(self):
|
||||
|
||||
def test_method():
|
||||
pass
|
||||
|
||||
octoprint.plugin.BlueprintPlugin.route("/test/method", methods=["GET"])(test_method)
|
||||
octoprint.plugin.BlueprintPlugin.route("/test/method/{foo}", methods=["PUT"])(test_method)
|
||||
|
||||
self.assertTrue(hasattr(test_method, "_blueprint_rules"))
|
||||
self.assertTrue("test_method" in test_method._blueprint_rules)
|
||||
self.assertTrue(len(test_method._blueprint_rules["test_method"]) == 2)
|
||||
self.assertListEqual(test_method._blueprint_rules["test_method"], [
|
||||
("/test/method", dict(methods=["GET"])),
|
||||
("/test/method/{foo}", dict(methods=["PUT"]))
|
||||
])
|
||||
|
||||
def test_errorhandler(self):
|
||||
|
||||
def test_method():
|
||||
pass
|
||||
|
||||
octoprint.plugin.BlueprintPlugin.errorhandler(404)(test_method)
|
||||
|
||||
self.assertTrue(hasattr(test_method, "_blueprint_error_handler"))
|
||||
self.assertTrue("test_method" in test_method._blueprint_error_handler)
|
||||
self.assertTrue(len(test_method._blueprint_error_handler["test_method"]) == 1)
|
||||
self.assertListEqual(test_method._blueprint_error_handler["test_method"], [
|
||||
404
|
||||
])
|
||||
|
||||
def test_get_blueprint_kwargs(self):
|
||||
import os
|
||||
expected = dict(
|
||||
static_folder=os.path.join(self.basefolder, "static"),
|
||||
template_folder=os.path.join(self.basefolder, "templates")
|
||||
)
|
||||
|
||||
result = self.plugin.get_blueprint_kwargs()
|
||||
|
||||
self.assertEquals(result, expected)
|
||||
|
||||
def test_get_blueprint_kwargs_assetplugin(self):
|
||||
import os
|
||||
expected = dict(
|
||||
static_folder=self.assetplugin.get_asset_folder(),
|
||||
template_folder=os.path.join(self.basefolder, "templates")
|
||||
)
|
||||
|
||||
result = self.assetplugin.get_blueprint_kwargs()
|
||||
|
||||
self.assertEquals(result, expected)
|
||||
|
||||
def test_get_blueprint_kwargs_templateplugin(self):
|
||||
import os
|
||||
expected = dict(
|
||||
static_folder=os.path.join(self.basefolder, "static"),
|
||||
template_folder=self.templateplugin.get_template_folder()
|
||||
)
|
||||
|
||||
result = self.templateplugin.get_blueprint_kwargs()
|
||||
|
||||
self.assertEquals(result, expected)
|
||||
|
||||
def test_get_blueprint(self):
|
||||
import os
|
||||
expected_kwargs = dict(
|
||||
static_folder=os.path.join(self.basefolder, "static"),
|
||||
template_folder=os.path.join(self.basefolder, "templates")
|
||||
)
|
||||
|
||||
class MyPlugin(octoprint.plugin.BlueprintPlugin):
|
||||
|
||||
@octoprint.plugin.BlueprintPlugin.route("/some/path", methods=["GET"])
|
||||
def route_method(self):
|
||||
pass
|
||||
|
||||
@octoprint.plugin.BlueprintPlugin.errorhandler(404)
|
||||
def errorhandler_method(self):
|
||||
pass
|
||||
|
||||
@octoprint.plugin.BlueprintPlugin.route("/hidden/path", methods=["GET"])
|
||||
def _hidden_method(self):
|
||||
pass
|
||||
|
||||
plugin = MyPlugin()
|
||||
plugin._basefolder = self.basefolder
|
||||
plugin._identifier = "myplugin"
|
||||
|
||||
with mock.patch("flask.Blueprint") as MockBlueprint:
|
||||
blueprint = mock.MagicMock()
|
||||
MockBlueprint.return_value = blueprint
|
||||
|
||||
errorhandler = mock.MagicMock()
|
||||
blueprint.errorhandler.return_value = errorhandler
|
||||
|
||||
result = plugin.get_blueprint()
|
||||
|
||||
self.assertEquals(result, blueprint)
|
||||
|
||||
MockBlueprint.assert_called_once_with("plugin.myplugin", "myplugin", **expected_kwargs)
|
||||
blueprint.add_url_rule.assert_called_once_with("/some/path", "route_method", view_func=plugin.route_method, methods=["GET"])
|
||||
|
||||
blueprint.errorhandler.assert_called_once_with(404)
|
||||
errorhandler.assert_called_once_with(plugin.errorhandler_method)
|
||||
|
||||
def test_get_blueprint_cached(self):
|
||||
blueprint = mock.MagicMock()
|
||||
self.plugin._blueprint = blueprint
|
||||
|
||||
result = self.plugin.get_blueprint()
|
||||
|
||||
self.assertEquals(blueprint, result)
|
||||
@@ -0,0 +1,313 @@
|
||||
import unittest
|
||||
import mock
|
||||
|
||||
import octoprint.plugin
|
||||
|
||||
class TestSettingsPlugin(unittest.TestCase):
|
||||
|
||||
def setUp(self):
|
||||
self.settings = mock.MagicMock()
|
||||
|
||||
self.plugin = octoprint.plugin.SettingsPlugin()
|
||||
self.plugin._settings = self.settings
|
||||
|
||||
def test_on_settings_cleanup(self):
|
||||
"""Tests that after cleanup only minimal config is left in storage."""
|
||||
|
||||
### setup
|
||||
|
||||
# settings defaults
|
||||
defaults = dict(
|
||||
foo=dict(
|
||||
a=1,
|
||||
b=2,
|
||||
l1=["some", "list"],
|
||||
l2=["another", "list"]
|
||||
),
|
||||
bar=True,
|
||||
fnord=None
|
||||
)
|
||||
self.plugin.get_settings_defaults = mock.MagicMock()
|
||||
self.plugin.get_settings_defaults.return_value = defaults
|
||||
|
||||
# stored config, containing one redundant entry (bar=True, same as default)
|
||||
in_config = dict(
|
||||
foo=dict(
|
||||
l1=["some", "other", "list"],
|
||||
l2=["another", "list"],
|
||||
l3=["a", "third", "list"]
|
||||
),
|
||||
bar=True,
|
||||
fnord=dict(
|
||||
c=3,
|
||||
d=4
|
||||
)
|
||||
)
|
||||
self.settings.get_all_data.return_value = in_config
|
||||
|
||||
### execute
|
||||
|
||||
self.plugin.on_settings_cleanup()
|
||||
|
||||
### assert
|
||||
|
||||
# minimal config (current without redundant value) should have been set
|
||||
expected = dict(
|
||||
foo=dict(
|
||||
l1=["some", "other", "list"],
|
||||
l3=["a", "third", "list"]
|
||||
),
|
||||
fnord=dict(
|
||||
c=3,
|
||||
d=4
|
||||
)
|
||||
)
|
||||
self.settings.set.assert_called_once_with([], expected)
|
||||
|
||||
def test_on_settings_cleanup_configversion(self):
|
||||
"""Tests that set config version is always left stored."""
|
||||
|
||||
### setup
|
||||
|
||||
defaults = dict(
|
||||
foo="fnord"
|
||||
)
|
||||
self.plugin.get_settings_defaults = mock.MagicMock()
|
||||
self.plugin.get_settings_defaults.return_value = defaults
|
||||
|
||||
in_config = dict(
|
||||
_config_version=1,
|
||||
foo="fnord"
|
||||
)
|
||||
self.settings.get_all_data.return_value = in_config
|
||||
|
||||
### execute
|
||||
|
||||
self.plugin.on_settings_cleanup()
|
||||
|
||||
### assert
|
||||
|
||||
# minimal config incl. config version should have been set
|
||||
self.settings.set.assert_called_once_with([], dict(_config_version=1))
|
||||
|
||||
def test_on_settings_cleanup_noconfigversion(self):
|
||||
"""Tests that config versions of None are cleaned from stored data."""
|
||||
|
||||
### setup
|
||||
|
||||
defaults = dict(
|
||||
foo="bar"
|
||||
)
|
||||
self.plugin.get_settings_defaults = mock.MagicMock()
|
||||
self.plugin.get_settings_defaults.return_value = defaults
|
||||
|
||||
# stored config version is None
|
||||
in_config = dict(
|
||||
_config_version=None,
|
||||
foo="fnord"
|
||||
)
|
||||
self.settings.get_all_data.return_value = in_config
|
||||
|
||||
### execute
|
||||
|
||||
self.plugin.on_settings_cleanup()
|
||||
|
||||
### assert
|
||||
|
||||
# minimal config without config version should have been set
|
||||
self.settings.set.assert_called_once_with([], dict(foo="fnord"))
|
||||
|
||||
def test_on_settings_cleanup_emptydiff(self):
|
||||
"""Tests that settings are cleaned up if the diff data <-> defaults is empty."""
|
||||
|
||||
### setup
|
||||
|
||||
defaults = dict(
|
||||
foo="bar"
|
||||
)
|
||||
self.plugin.get_settings_defaults = mock.MagicMock()
|
||||
self.plugin.get_settings_defaults.return_value = defaults
|
||||
|
||||
# current stored config, same as defaults
|
||||
in_config = dict(
|
||||
foo="bar"
|
||||
)
|
||||
self.settings.get_all_data.return_value = in_config
|
||||
|
||||
### execute
|
||||
|
||||
self.plugin.on_settings_cleanup()
|
||||
|
||||
### assert
|
||||
|
||||
# should have been cleared
|
||||
self.settings.clean_all_data.assert_called_once_with()
|
||||
|
||||
def test_on_settings_cleanup_nosuchpath(self):
|
||||
"""Tests that no processing is done if nothing is stored in settings."""
|
||||
|
||||
from octoprint.settings import NoSuchSettingsPath
|
||||
|
||||
### setup
|
||||
|
||||
# simulate no settings stored in config.yaml
|
||||
self.settings.get_all_data.side_effect = NoSuchSettingsPath()
|
||||
|
||||
### execute
|
||||
|
||||
self.plugin.on_settings_cleanup()
|
||||
|
||||
### assert
|
||||
|
||||
# only get_all_data should have been called
|
||||
self.settings.get_all_data.assert_called_once_with(merged=False, incl_defaults=False, error_on_path=True)
|
||||
self.assertTrue(len(self.settings.method_calls) == 1)
|
||||
|
||||
def test_on_settings_cleanup_none(self):
|
||||
"""Tests the None entries in config get cleaned up."""
|
||||
|
||||
### setup
|
||||
|
||||
# simulate None entry in config.yaml
|
||||
self.settings.get_all_data.return_value = None
|
||||
|
||||
### execute
|
||||
|
||||
self.plugin.on_settings_cleanup()
|
||||
|
||||
### assert
|
||||
|
||||
# should have been cleaned
|
||||
self.settings.clean_all_data.assert_called_once_with()
|
||||
|
||||
def test_on_settings_save(self):
|
||||
"""Tests that only the diff is saved."""
|
||||
|
||||
### setup
|
||||
|
||||
current = dict(
|
||||
foo="bar"
|
||||
)
|
||||
self.settings.get_all_data.return_value = current
|
||||
|
||||
defaults = dict(
|
||||
foo="foo",
|
||||
bar=dict(
|
||||
a=1,
|
||||
b=2
|
||||
)
|
||||
)
|
||||
self.plugin.get_settings_defaults = mock.MagicMock()
|
||||
self.plugin.get_settings_defaults.return_value = defaults
|
||||
|
||||
### execute
|
||||
|
||||
data = dict(
|
||||
foo="fnord",
|
||||
bar=dict(
|
||||
a=1,
|
||||
b=2
|
||||
)
|
||||
)
|
||||
diff = self.plugin.on_settings_save(data)
|
||||
|
||||
### assert
|
||||
|
||||
# the minimal diff should have been saved
|
||||
expected = dict(
|
||||
foo="fnord"
|
||||
)
|
||||
self.settings.set.assert_called_once_with([], expected)
|
||||
|
||||
self.assertEquals(diff, expected)
|
||||
|
||||
def test_on_settings_save_nodiff(self):
|
||||
"""Tests that data is cleaned if there's not difference between data and defaults."""
|
||||
|
||||
### setup
|
||||
|
||||
self.settings.get_all_data.return_value = None
|
||||
|
||||
defaults = dict(
|
||||
foo="bar",
|
||||
bar=dict(
|
||||
a=1,
|
||||
b=2,
|
||||
l=["some", "list"]
|
||||
)
|
||||
)
|
||||
self.plugin.get_settings_defaults = mock.MagicMock()
|
||||
self.plugin.get_settings_defaults.return_value = defaults
|
||||
|
||||
### execute
|
||||
|
||||
data = dict(foo="bar")
|
||||
diff = self.plugin.on_settings_save(data)
|
||||
|
||||
### assert
|
||||
|
||||
self.settings.clean_all_data.assert_called_once_with()
|
||||
self.assertEquals(diff, dict())
|
||||
|
||||
def test_on_settings_save_configversion(self):
|
||||
"""Tests that saved data gets stripped config version and set correct one."""
|
||||
|
||||
### setup
|
||||
|
||||
self.settings.get_all_data.return_value = None
|
||||
|
||||
defaults = dict(
|
||||
foo="bar"
|
||||
)
|
||||
self.plugin.get_settings_defaults = mock.MagicMock()
|
||||
self.plugin.get_settings_defaults.return_value = defaults
|
||||
|
||||
version = 1
|
||||
self.plugin.get_settings_version = mock.MagicMock()
|
||||
self.plugin.get_settings_version.return_value = version
|
||||
|
||||
### execute
|
||||
|
||||
data = dict(_config_version=None, foo="bar")
|
||||
diff = self.plugin.on_settings_save(data)
|
||||
|
||||
### assert
|
||||
|
||||
expected_diff = dict()
|
||||
expected_set = dict(_config_version=version)
|
||||
|
||||
# while there was no diff, we should still have saved the new config version
|
||||
self.settings.set.assert_called_once_with([], expected_set)
|
||||
|
||||
self.assertEquals(diff, expected_diff)
|
||||
|
||||
def test_on_settings_load(self):
|
||||
"""Tests that on_settings_load returns what's stored in the config, without config version."""
|
||||
|
||||
### setup
|
||||
|
||||
# current data incl. config version
|
||||
current = dict(
|
||||
_config_version=3,
|
||||
foo="bar",
|
||||
fnord=dict(
|
||||
a=1,
|
||||
b=2,
|
||||
l=["some", "list"]
|
||||
)
|
||||
)
|
||||
|
||||
# expected is current without _config_version - we make the copy now
|
||||
# since our current dict will be modified by the test
|
||||
expected = dict(current)
|
||||
del expected["_config_version"]
|
||||
|
||||
self.settings.get_all_data.return_value = expected
|
||||
|
||||
### execute
|
||||
|
||||
result = self.plugin.on_settings_load()
|
||||
|
||||
### assert
|
||||
|
||||
self.assertEquals(result, expected)
|
||||
@@ -0,0 +1 @@
|
||||
hidden_everywhere
|
||||
@@ -0,0 +1 @@
|
||||
normal_text
|
||||
@@ -0,0 +1 @@
|
||||
not_a_text
|
||||
@@ -0,0 +1,3 @@
|
||||
# This is a text file encoded in UTF8 with a BOM
|
||||
|
||||
Here are some umlauts: äöüÄÖÜß
|
||||
@@ -0,0 +1,3 @@
|
||||
# This is a text file encoded in UTF8 without a BOM
|
||||
|
||||
Here are some umlauts: äöüÄÖÜß
|
||||
@@ -0,0 +1,208 @@
|
||||
# coding=utf-8
|
||||
from __future__ import absolute_import
|
||||
|
||||
__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html'
|
||||
__copyright__ = "Copyright (C) 2015 The OctoPrint Project - Released under terms of the AGPLv3 License"
|
||||
|
||||
import unittest
|
||||
import mock
|
||||
import os
|
||||
import ddt
|
||||
import sys
|
||||
|
||||
import octoprint.util
|
||||
|
||||
class BomAwareOpenTest(unittest.TestCase):
|
||||
"""
|
||||
Tests for :func:`octoprint.util.bom_aware_open`.
|
||||
"""
|
||||
|
||||
def setUp(self):
|
||||
self.filename_utf8_with_bom = os.path.join(os.path.abspath(os.path.dirname(__file__)), "_files", "utf8_with_bom.txt")
|
||||
self.filename_utf8_without_bom = os.path.join(os.path.abspath(os.path.dirname(__file__)), "_files", "utf8_without_bom.txt")
|
||||
|
||||
def test_bom_aware_open_with_bom(self):
|
||||
"""Tests that the contents of a UTF8 file with BOM are loaded correctly (without the BOM)."""
|
||||
|
||||
# test
|
||||
with octoprint.util.bom_aware_open(self.filename_utf8_with_bom, encoding="utf-8") as f:
|
||||
contents = f.readlines()
|
||||
|
||||
# assert
|
||||
self.assertEquals(len(contents), 3)
|
||||
self.assertTrue(contents[0].startswith("#"))
|
||||
|
||||
def test_bom_aware_open_without_bom(self):
|
||||
"""Tests that the contents of a UTF8 file without BOM are loaded correctly."""
|
||||
|
||||
# test
|
||||
with octoprint.util.bom_aware_open(self.filename_utf8_without_bom, encoding="utf-8") as f:
|
||||
contents = f.readlines()
|
||||
|
||||
# assert
|
||||
self.assertEquals(len(contents), 3)
|
||||
self.assertTrue(contents[0].startswith("#"))
|
||||
|
||||
def test_bom_aware_open_ascii(self):
|
||||
"""Tests that the contents of a UTF8 file loaded as ASCII are replaced correctly if "replace" is specified on errors."""
|
||||
|
||||
# test
|
||||
with octoprint.util.bom_aware_open(self.filename_utf8_with_bom, errors="replace") as f:
|
||||
contents = f.readlines()
|
||||
|
||||
# assert
|
||||
self.assertEquals(len(contents), 3)
|
||||
self.assertTrue(contents[0].startswith(u"\ufffd" * 3 + "#"))
|
||||
self.assertTrue(contents[2].endswith(u"\ufffd\ufffd" * 6))
|
||||
|
||||
def test_bom_aware_open_encoding_error(self):
|
||||
"""Tests that an encoding error is thrown if not suppressed when opening a UTF8 file as ASCII."""
|
||||
try:
|
||||
with octoprint.util.bom_aware_open(self.filename_utf8_without_bom) as f:
|
||||
f.readlines()
|
||||
self.fail("Expected an exception")
|
||||
except UnicodeDecodeError:
|
||||
pass
|
||||
|
||||
def test_bom_aware_open_parameters(self):
|
||||
"""Tests that the parameters are propagated properly."""
|
||||
|
||||
with mock.patch("codecs.open") as mock_open:
|
||||
with octoprint.util.bom_aware_open(self.filename_utf8_without_bom, mode="rb", encoding="utf-8", errors="ignore") as f:
|
||||
f.readlines()
|
||||
|
||||
mock_open.assert_called_once_with(self.filename_utf8_without_bom, encoding="utf-8", mode="rb", errors="ignore")
|
||||
|
||||
class TestAtomicWrite(unittest.TestCase):
|
||||
"""
|
||||
Tests for :func:`octoprint.util.atomic_write`.
|
||||
"""
|
||||
|
||||
def setUp(self):
|
||||
pass
|
||||
|
||||
@mock.patch("shutil.move")
|
||||
@mock.patch("tempfile.NamedTemporaryFile")
|
||||
def test_atomic_write(self, mock_tempfile, mock_move):
|
||||
"""Tests the regular basic "good" case."""
|
||||
|
||||
# setup
|
||||
mock_file = mock.MagicMock()
|
||||
mock_file.name = "tempfile.tmp"
|
||||
mock_tempfile.return_value = mock_file
|
||||
|
||||
# test
|
||||
with octoprint.util.atomic_write("somefile.yaml") as f:
|
||||
f.write("test")
|
||||
|
||||
# assert
|
||||
mock_tempfile.assert_called_once_with(mode="w+b", prefix="tmp", suffix="", delete=False)
|
||||
mock_file.write.assert_called_once_with("test")
|
||||
mock_file.close.assert_called_once_with()
|
||||
mock_move.assert_called_once_with("tempfile.tmp", "somefile.yaml")
|
||||
|
||||
@mock.patch("shutil.move")
|
||||
@mock.patch("tempfile.NamedTemporaryFile")
|
||||
def test_atomic_write_error_on_write(self, mock_tempfile, mock_move):
|
||||
"""Tests the error case where something in the wrapped code fails."""
|
||||
|
||||
# setup
|
||||
mock_file = mock.MagicMock()
|
||||
mock_file.name = "tempfile.tmp"
|
||||
mock_file.write.side_effect = RuntimeError()
|
||||
mock_tempfile.return_value = mock_file
|
||||
|
||||
# test
|
||||
try:
|
||||
with octoprint.util.atomic_write("somefile.yaml") as f:
|
||||
f.write("test")
|
||||
self.fail("Expected an exception")
|
||||
except RuntimeError:
|
||||
pass
|
||||
|
||||
# assert
|
||||
mock_tempfile.assert_called_once_with(mode="w+b", prefix="tmp", suffix="", delete=False)
|
||||
mock_file.close.assert_called_once_with()
|
||||
self.assertFalse(mock_move.called)
|
||||
|
||||
@mock.patch("shutil.move")
|
||||
@mock.patch("tempfile.NamedTemporaryFile")
|
||||
def test_atomic_write_error_on_move(self, mock_tempfile, mock_move):
|
||||
"""Tests the error case where the final move fails."""
|
||||
# setup
|
||||
mock_file = mock.MagicMock()
|
||||
mock_file.name = "tempfile.tmp"
|
||||
mock_tempfile.return_value = mock_file
|
||||
mock_move.side_effect = RuntimeError()
|
||||
|
||||
# test
|
||||
try:
|
||||
with octoprint.util.atomic_write("somefile.yaml") as f:
|
||||
f.write("test")
|
||||
self.fail("Expected an exception")
|
||||
except RuntimeError:
|
||||
pass
|
||||
|
||||
# assert
|
||||
mock_tempfile.assert_called_once_with(mode="w+b", prefix="tmp", suffix="", delete=False)
|
||||
mock_file.close.assert_called_once_with()
|
||||
self.assertTrue(mock_move.called)
|
||||
|
||||
@mock.patch("shutil.move")
|
||||
@mock.patch("tempfile.NamedTemporaryFile")
|
||||
def test_atomic_write_parameters(self, mock_tempfile, mock_move):
|
||||
"""Tests that the open parameters are propagated properly."""
|
||||
|
||||
# setup
|
||||
mock_file = mock.MagicMock()
|
||||
mock_file.name = "tempfile.tmp"
|
||||
mock_tempfile.return_value = mock_file
|
||||
|
||||
# test
|
||||
with octoprint.util.atomic_write("somefile.yaml", mode="w", prefix="foo", suffix="bar") as f:
|
||||
f.write("test")
|
||||
|
||||
# assert
|
||||
mock_tempfile.assert_called_once_with(mode="w", prefix="foo", suffix="bar", delete=False)
|
||||
mock_file.close.assert_called_once_with()
|
||||
mock_move.assert_called_once_with("tempfile.tmp", "somefile.yaml")
|
||||
|
||||
|
||||
@ddt.ddt
|
||||
class IsHiddenPathTest(unittest.TestCase):
|
||||
|
||||
def setUp(self):
|
||||
import tempfile
|
||||
|
||||
self.basepath = tempfile.mkdtemp()
|
||||
|
||||
self.path_always_visible = os.path.join(self.basepath, "always_visible.txt")
|
||||
self.path_hidden_on_windows = os.path.join(self.basepath, "hidden_on_windows.txt")
|
||||
self.path_always_hidden = os.path.join(self.basepath, ".always_hidden.txt")
|
||||
|
||||
for attr in ("path_always_visible", "path_hidden_on_windows", "path_always_hidden"):
|
||||
path = getattr(self, attr)
|
||||
with open(path, "w+b") as f:
|
||||
f.write(attr)
|
||||
|
||||
import sys
|
||||
if sys.platform == "win32":
|
||||
# we use ctypes and the windows API to set the hidden attribute on the file
|
||||
# only hidden on windows
|
||||
import ctypes
|
||||
ctypes.windll.kernel32.SetFileAttributesW(unicode(self.path_hidden_on_windows), 2)
|
||||
|
||||
def tearDown(self):
|
||||
import shutil
|
||||
shutil.rmtree(self.basepath)
|
||||
|
||||
@ddt.data(
|
||||
(None, False),
|
||||
("path_always_visible", False),
|
||||
("path_always_hidden", True),
|
||||
("path_hidden_on_windows", sys.platform == "win32")
|
||||
)
|
||||
@ddt.unpack
|
||||
def test_is_hidden_path(self, path_id, expected):
|
||||
path = getattr(self, path_id) if path_id is not None else None
|
||||
self.assertEqual(octoprint.util.is_hidden_path(path), expected)
|
||||
@@ -0,0 +1,76 @@
|
||||
# coding=utf-8
|
||||
from __future__ import absolute_import
|
||||
|
||||
__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html'
|
||||
__copyright__ = "Copyright (C) 2015 The OctoPrint Project - Released under terms of the AGPLv3 License"
|
||||
|
||||
|
||||
import unittest
|
||||
import os
|
||||
import jinja2
|
||||
|
||||
from ddt import ddt, data, unpack
|
||||
|
||||
import octoprint.util.jinja
|
||||
|
||||
NONE_FILTER = None
|
||||
HIDDEN_FILTER = lambda x: not os.path.basename(x).startswith(".")
|
||||
NO_TXT_FILTER = lambda x: x.endswith(".txt")
|
||||
COMBINED_FILTER = lambda x: HIDDEN_FILTER(x) and NO_TXT_FILTER(x)
|
||||
|
||||
@ddt
|
||||
class FilteredFileSystemLoaderTest(unittest.TestCase):
|
||||
|
||||
def setUp(self):
|
||||
self.basepath = os.path.join(os.path.abspath(os.path.dirname(__file__)), "_files", "jinja_test_data")
|
||||
self.environment = jinja2.Environment()
|
||||
|
||||
def loader_factory(self, path_filter):
|
||||
return octoprint.util.jinja.FilteredFileSystemLoader(self.basepath,
|
||||
path_filter=path_filter)
|
||||
|
||||
@data(
|
||||
(NONE_FILTER, [".hidden_everywhere.txt", "normal_text.txt", "not_a_text.dat"]),
|
||||
(HIDDEN_FILTER, ["normal_text.txt", "not_a_text.dat"]),
|
||||
(NO_TXT_FILTER, [".hidden_everywhere.txt", "normal_text.txt"]),
|
||||
(COMBINED_FILTER, ["normal_text.txt"])
|
||||
)
|
||||
@unpack
|
||||
def test_list_templates(self, path_filter, expected):
|
||||
loader = self.loader_factory(path_filter=path_filter)
|
||||
templates = loader.list_templates()
|
||||
self.assertListEqual(templates, expected)
|
||||
|
||||
@data(
|
||||
(NONE_FILTER, ((".hidden_everywhere.txt", True),
|
||||
("normal_text.txt", True),
|
||||
("not_a_text.dat", True))),
|
||||
(HIDDEN_FILTER, ((".hidden_everywhere.txt", False),
|
||||
("normal_text.txt", True),
|
||||
("not_a_text.dat", True))),
|
||||
(NO_TXT_FILTER, ((".hidden_everywhere.txt", True),
|
||||
("normal_text.txt", True),
|
||||
("not_a_text.dat", False))),
|
||||
(COMBINED_FILTER, ((".hidden_everywhere.txt", False),
|
||||
("normal_text.txt", True),
|
||||
("not_a_text.dat", False)))
|
||||
)
|
||||
@unpack
|
||||
def test_get_source_none_filter(self, path_filter, param_sets):
|
||||
loader = self.loader_factory(path_filter=path_filter)
|
||||
for param_set in param_sets:
|
||||
template, success = param_set
|
||||
if success:
|
||||
self._test_get_source_success(loader, template)
|
||||
else:
|
||||
self._test_get_source_notfound(loader, template)
|
||||
|
||||
def _test_get_source_success(self, loader, template):
|
||||
loader.get_source(self.environment, template)
|
||||
|
||||
def _test_get_source_notfound(self, loader, template):
|
||||
try:
|
||||
loader.get_source(self.environment, template)
|
||||
self.fail("Expected an exception")
|
||||
except jinja2.TemplateNotFound:
|
||||
pass
|
||||
Binary file not shown.
File diff suppressed because it is too large.
Load diff
+425
-286
File diff suppressed because it is too large.
Load diff
+1680
-689
File diff suppressed because it is too large.
Load diff
Reference in new issue
Block a user