tradedangerous 11.2.0__py3-none-any.whl → 11.3.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.

Potentially problematic release.


This version of tradedangerous might be problematic. Click here for more details.

tradedangerous/cache.py CHANGED
@@ -30,14 +30,17 @@ import sqlite3
30
30
  import sys
31
31
  import typing
32
32
 
33
+ from functools import partial as partial_fn
34
+ from .fs import file_line_count
33
35
  from .tradeexcept import TradeException
36
+ from tradedangerous.misc.progress import Progress, CountingBar
34
37
  from . import corrections, utils
35
38
  from . import prices
36
39
 
37
40
 
38
41
  # For mypy/pylint type checking
39
42
  if typing.TYPE_CHECKING:
40
- from typing import Any, Optional, TextIO
43
+ from typing import Any, Callable, Optional, TextIO # noqa
41
44
 
42
45
  from .tradeenv import TradeEnv
43
46
 
@@ -777,11 +780,14 @@ def deprecationCheckItem(importPath, lineNo, line):
777
780
  )
778
781
 
779
782
 
780
- def processImportFile(tdenv, db, importPath, tableName):
783
+ def processImportFile(tdenv, db, importPath, tableName, *, line_callback: Optional[Callable] = None, call_args: Optional[dict] = None):
781
784
  tdenv.DEBUG0(
782
785
  "Processing import file '{}' for table '{}'",
783
786
  str(importPath), tableName
784
787
  )
788
+ call_args = call_args or {}
789
+ if line_callback:
790
+ line_callback = partial_fn(line_callback, **call_args)
785
791
 
786
792
  fkeySelectStr = (
787
793
  "("
@@ -870,6 +876,8 @@ def processImportFile(tdenv, db, importPath, tableName):
870
876
  uniqueIndex = {}
871
877
 
872
878
  for linein in csvin:
879
+ if line_callback:
880
+ line_callback()
873
881
  if not linein:
874
882
  continue
875
883
  lineNo = csvin.line_num
@@ -977,25 +985,34 @@ def buildCache(tdb, tdenv):
977
985
  tempDB.executescript(sqlScript)
978
986
 
979
987
  # import standard tables
980
- for (importName, importTable) in tdb.importTables:
981
- try:
982
- processImportFile(tdenv, tempDB, Path(importName), importTable)
983
- except FileNotFoundError:
984
- tdenv.DEBUG0(
985
- "WARNING: processImportFile found no {} file", importName
986
- )
987
- except StopIteration:
988
- tdenv.NOTE(
989
- "{} exists but is empty. "
990
- "Remove it or add the column definition line.",
991
- importName
992
- )
993
-
994
- tempDB.commit()
988
+ with Progress(max_value=len(tdb.importTables) + 1, prefix="Importing", width=25, style=CountingBar) as prog:
989
+ for importName, importTable in tdb.importTables:
990
+ import_path = Path(importName)
991
+ import_lines = file_line_count(import_path, missing_ok=True)
992
+ with prog.sub_task(max_value=import_lines, description=importTable) as child:
993
+ prog.increment(value=1)
994
+ call_args = {'task': child, 'advance': 1}
995
+ try:
996
+ processImportFile(tdenv, tempDB, import_path, importTable, line_callback=prog.update_task, call_args=call_args)
997
+ except FileNotFoundError:
998
+ tdenv.DEBUG0(
999
+ "WARNING: processImportFile found no {} file", importName
1000
+ )
1001
+ except StopIteration:
1002
+ tdenv.NOTE(
1003
+ "{} exists but is empty. "
1004
+ "Remove it or add the column definition line.",
1005
+ importName
1006
+ )
1007
+ prog.increment(1)
1008
+
1009
+ with prog.sub_task(description="Save DB"):
1010
+ tempDB.commit()
995
1011
 
996
1012
  # Parse the prices file
997
1013
  if pricesPath.exists():
998
- processPricesFile(tdenv, tempDB, pricesPath)
1014
+ with Progress(max_value=None, width=25, prefix="Processing prices file"):
1015
+ processPricesFile(tdenv, tempDB, pricesPath)
999
1016
  else:
1000
1017
  tdenv.NOTE(
1001
1018
  "Missing \"{}\" file - no price data.",
@@ -60,7 +60,6 @@ class PadSizeArgument(int):
60
60
  'dest': 'padSize',
61
61
  'metavar': 'PADSIZES',
62
62
  'type': 'padsize',
63
- 'choices': 'SsMmLl?',
64
63
  }
65
64
 
66
65
 
@@ -153,7 +152,6 @@ class PlanetaryArgument(int):
153
152
  'dest': 'planetary',
154
153
  'metavar': 'PLANETARY',
155
154
  'type': 'planetary',
156
- 'choices': 'YyNn?',
157
155
  }
158
156
 
159
157
 
@@ -181,7 +179,6 @@ class FleetCarrierArgument(int):
181
179
  'dest': 'fleet',
182
180
  'metavar': 'FLEET',
183
181
  'type': 'fleet',
184
- 'choices': 'YyNn?',
185
182
  }
186
183
 
187
184
  class OdysseyArgument(int):
@@ -208,7 +205,6 @@ class OdysseyArgument(int):
208
205
  'dest': 'odyssey',
209
206
  'metavar': 'ODYSSEY',
210
207
  'type': 'odyssey',
211
- 'choices': 'YyNn?',
212
208
  }
213
209
 
214
210
 
@@ -1,5 +1,5 @@
1
- # Deprecated
2
1
  #!/usr/bin/env python3.6
2
+ # Deprecated
3
3
 
4
4
  """
5
5
  This tool looks for changes in the EDSC service since the most
@@ -1,5 +1,5 @@
1
- # Deprecated
2
1
  #!/usr/bin/env python3.6
2
+ # Deprecated
3
3
 
4
4
  """
5
5
  based on edscupdate.py without the submit_distance()
@@ -8,8 +8,7 @@ import itertools
8
8
  import typing
9
9
 
10
10
  if typing.TYPE_CHECKING:
11
- from typing import Any, Optional
12
- from collections.abc import Callable
11
+ from typing import Any, Callable, Optional # noqa
13
12
 
14
13
 
15
14
  class ColumnFormat:
tradedangerous/fs.py CHANGED
@@ -1,10 +1,10 @@
1
1
  """This module should handle filesystem related operations
2
2
  """
3
3
  from shutil import copy as shcopy
4
- from os import makedirs
4
+ from os import makedirs, PathLike
5
5
  from pathlib import Path
6
6
 
7
- __all__ = ['copy', 'copyallfiles', 'touch', 'ensurefolder']
7
+ __all__ = ['copy', 'copyallfiles', 'touch', 'ensurefolder', 'file_line_count']
8
8
 
9
9
  def pathify(*args):
10
10
  if len(args) > 1 or not isinstance(args[0], Path):
@@ -99,3 +99,39 @@ def ensurefolder(folder):
99
99
  except FileExistsError:
100
100
  pass
101
101
  return folderPath.resolve()
102
+
103
+
104
+ def file_line_count(from_file: PathLike, buf_size: int = 128 * 1024, *, missing_ok: bool = False) -> int:
105
+ """ counts the number of newline characters in a given file. """
106
+ if not isinstance(from_file, Path):
107
+ from_file = Path(from_file)
108
+
109
+ if missing_ok and not from_file.exists():
110
+ return 0
111
+
112
+ # Pre-allocate a buffer so that we aren't putting pressure on the garbage collector.
113
+ buf = bytearray(buf_size)
114
+
115
+ # Capture it's counting method, so we don't have to keep looking that up on
116
+ # large files.
117
+ counter = buf.count
118
+
119
+ total = 0
120
+ with from_file.open("rb") as fh:
121
+ # Capture the 'readinto' method to avoid lookups.
122
+ reader = fh.readinto
123
+
124
+ # read into the buffer and capture the number of bytes fetched,
125
+ # which will be 'size' until the last read from the file.
126
+ read = reader(buf)
127
+ while read == buf_size: # nominal case for large files
128
+ total += counter(b'\n')
129
+ read = reader(buf)
130
+
131
+ # when 0 <= read < buf_size we're on the last page of the
132
+ # file, so we need to take a slice of the buffer, which creates
133
+ # a new object, thus we also have to lookup count. it's trivial
134
+ # but if you have to do it 10,000x it's definitely not a rounding error.
135
+ return total + buf[:read].count(b'\n')
136
+
137
+
@@ -1,71 +1,179 @@
1
- import sys
1
+ from rich.progress import (
2
+ Progress as RichProgress,
3
+ TaskID,
4
+ ProgressColumn,
5
+ BarColumn, DownloadColumn, MofNCompleteColumn, SpinnerColumn,
6
+ TaskProgressColumn, TextColumn, TimeElapsedColumn, TimeRemainingColumn,
7
+ TransferSpeedColumn
8
+ )
9
+ from contextlib import contextmanager
10
+
11
+ from typing import Iterable, Optional, Union, Type # noqa
12
+
13
+
14
+ class BarStyle:
15
+ """ Base class for Progress bar style types. """
16
+ def __init__(self, width: int = 10, prefix: Optional[str] = None, *, add_columns: Optional[Iterable[ProgressColumn]]):
17
+ self.columns = [SpinnerColumn(), TextColumn("[progress.description]{task.description}"), BarColumn(bar_width=width)]
18
+ if add_columns:
19
+ self.columns.extend(add_columns)
20
+
21
+
22
+ class CountingBar(BarStyle):
23
+ """ Creates a progress bar that is counting M/N items to completion. """
24
+ def __init__(self, width: int = 10, prefix: Optional[str] = None):
25
+ my_columns = [MofNCompleteColumn(), TimeElapsedColumn()]
26
+ super().__init__(width, prefix, add_columns=my_columns)
27
+
28
+
29
+ class DefaultBar(BarStyle):
30
+ """ Creates a simple default progress bar with a percentage and time elapsed. """
31
+ def __init__(self, width: int = 10, prefix: Optional[str] = None):
32
+ my_columns = [TaskProgressColumn(), TimeElapsedColumn()]
33
+ super().__init__(width, prefix, add_columns=my_columns)
34
+
35
+
36
+ class LongRunningCountBar(BarStyle):
37
+ """ Creates a progress bar that is counting M/N items to completion with a time-remaining counter """
38
+ def __init__(self, width: int = 10, prefix: Optional[str] = None):
39
+ my_columns = [MofNCompleteColumn(), TimeElapsedColumn(), TimeRemainingColumn()]
40
+ super().__init__(width, prefix, add_columns=my_columns)
41
+
42
+
43
+ class TransferBar(BarStyle):
44
+ """ Creates a progress bar representing a data transfer, which shows the amount of
45
+ data transferred, speed, and estimated time remaining. """
46
+ def __init__(self, width: int = 16, prefix: Optional[str] = None):
47
+ my_columns = [DownloadColumn(), TransferSpeedColumn(), TimeRemainingColumn()]
48
+ super().__init__(width, prefix, add_columns=my_columns)
49
+
2
50
 
3
51
  class Progress:
4
52
  """
5
- Helper class that describes a simple text-based progress bar.
53
+ Facade around the rich Progress bar system to help transition away from
54
+ TD's original basic progress bar implementation.
6
55
  """
7
-
8
- def __init__(self, maxValue, width, start=0, prefix=""):
56
+ def __init__(self,
57
+ max_value: Optional[float] = None,
58
+ width: Optional[int] = None,
59
+ start: float = 0,
60
+ prefix: Optional[str] = None,
61
+ *,
62
+ style: Optional[Type[BarStyle]] = None,
63
+ show: bool = True,
64
+ ) -> None:
9
65
  """
10
- Arguments:
11
- maxValue
12
- Last value we can reach (100%).
13
- width
14
- Number of '='s characters for 100%
15
- start
16
- Initial value
17
- prefix
18
- Something to print infront of the progress bar
66
+ :param max_value: Last value we can reach (100%).
67
+ :param width: How wide to make the bar itself.
68
+ :param start: Override initial value to non-zero.
69
+ :param prefix: Text to print between the spinner and the bar.
70
+ :param style: Bar-style factory to use for styling.
71
+ :param show: If False, disables the bar entirely.
19
72
  """
20
- self.start = start
21
- self.maxValue = maxValue
22
- self.width = width
73
+ self.show = bool(show)
74
+ if not show:
75
+ return
76
+
77
+ if style is None:
78
+ style = DefaultBar
79
+
80
+ self.max_value = 0 if max_value is None else max(max_value, start)
23
81
  self.value = start
24
- self.progress = -1
25
- self.prefix = prefix
26
- self.textLen = 0
27
- self.mask = '\r' + self.prefix + "[{{:<{width}}}]".format(width=width)
82
+ self.prefix = prefix or ""
83
+ self.width = width or 25
84
+ # The 'Progress' itself is a view for displaying the progress of tasks. So we construct it
85
+ # and then create a task for our job.
86
+ style_instance = style(width=self.width, prefix=self.prefix)
87
+ self.progress = RichProgress(
88
+ # What fields to display.
89
+ *style_instance.columns,
90
+ # Hide it once it's finished, update it for us, 4x a second
91
+ transient=True, auto_refresh=True, refresh_per_second=5
92
+ )
28
93
 
94
+ # Now we add an actual task to track progress on.
95
+ self.task = self.progress.add_task("Working...", total=max_value, start=True)
96
+ if self.value:
97
+ self.progress.update(self.task, advance=self.value)
29
98
 
30
- def increment(self, value, postfix=""):
31
- """
32
- Increment the progress bar's internal counter by 'value',
33
- and if this changes the progress step, re-draw the bar.
34
-
35
- Attributes:
36
- value
37
- The amount to increment the internal counter by
38
- postfix [optional]
39
- String or callable to print after the bar
99
+ # And show the task tracker.
100
+ self.progress.start()
101
+
102
+ def __enter__(self):
103
+ """ Context manager.
40
104
 
41
- Returns:
42
- False if the progress bar did not redraw,
43
- True if the progress bar was redrawn,
105
+ Example use:
106
+
107
+ import time
108
+ import tradedangerous.progress
109
+
110
+ # Progress(max_value=100, width=32, style=progress.CountingBar)
111
+ with progress.Progress(100, 32, style=progress.CountingBar) as prog:
112
+ for i in range(100):
113
+ prog.increment(1)
114
+ time.sleep(3)
44
115
  """
45
- self.value = min(self.maxValue, self.value + value)
46
- progress = int(self.width * (self.value - self.start) / self.maxValue)
47
- if progress == self.progress:
48
- return False
49
-
50
- if callable(postfix):
51
- postfixText = postfix(self.value, self.maxValue)
52
- else:
53
- postfixText = postfix
54
- text = self.mask.format("="*progress) + postfixText + " "
55
- sys.stdout.write(text)
56
- sys.stdout.flush()
57
-
58
- self.progress = progress
59
- self.textLen = len(text)
60
-
61
- return True
116
+ return self
62
117
 
118
+ def __exit__(self, *args, **kwargs):
119
+ self.clear()
63
120
 
64
- def clear(self):
121
+ def increment(self, value: Optional[float] = None, description: Optional[str] = None, *, progress: Optional[float] = None) -> None:
65
122
  """
66
- Remove the current progress bar, if any
123
+ Increase the progress of the bar by a given amount.
124
+
125
+ :param value: How much to increase the progress by.
126
+ :param description: If set, replaces the task description.
127
+ :param progress: Instead of increasing by value, set the absolute progress to this.
67
128
  """
68
- if self.textLen:
69
- fin = "\r{:{width}}\r".format('', width=self.textLen)
70
- sys.stdout.write(fin)
71
- sys.stdout.flush()
129
+ if not self.show:
130
+ return
131
+ if description:
132
+ self.prefix = description
133
+ self.progress.update(self.task, description=description, refresh=True)
134
+
135
+ bump = False
136
+ if not value and progress is not None and self.value != progress:
137
+ self.value = progress
138
+ bump = True
139
+ elif value:
140
+ self.value += value # Update our internal count
141
+ bump = True
142
+
143
+ if self.value >= self.max_value: # Did we go past the end? Increase the end.
144
+ self.max_value += value * 2
145
+ self.progress.update(self.task, description=self.prefix, total=self.max_value)
146
+ bump = True
147
+
148
+ if bump and self.max_value > 0:
149
+ self.progress.update(self.task, description=self.prefix, completed=self.value)
150
+
151
+ def clear(self) -> None:
152
+ """ Remove the current progress bar, if any. """
153
+ # These two shouldn't happen separately, but incase someone tinkers, test each
154
+ # separately and shut them down.
155
+ if not self.show:
156
+ return
157
+
158
+ if self.task:
159
+ self.progress.remove_task(self.task)
160
+ self.task = None
161
+
162
+ if self.progress:
163
+ self.progress.stop()
164
+ self.progress = None
165
+
166
+ @contextmanager
167
+ def sub_task(self, description: str, max_value: Optional[int] = None, width: int = 25):
168
+ if not self.show:
169
+ yield
170
+ return
171
+ task = self.progress.add_task(description, total=max_value, start=True, width=width)
172
+ try:
173
+ yield task
174
+ finally:
175
+ self.progress.remove_task(task)
176
+
177
+ def update_task(self, task: TaskID, advance: Union[float, int], description: Optional[str] = None):
178
+ if self.show:
179
+ self.progress.update(task, advance=advance, description=description)