Conditions | 13 |
Total Lines | 33 |
Code Lines | 28 |
Lines | 0 |
Ratio | 0 % |
Changes | 0 |
Complex classes like ocrd.resource_manager.OcrdResourceManager.download() often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes.
Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.
Methods with many parameters are not only hard to understand, but their parameters also often become inconsistent when you need more, or different data.
There are several approaches to avoid long parameter lists:
1 | from pathlib import Path |
||
92 | def download(self, executable, url, overwrite=False, basedir=XDG_CACHE_HOME, name=None, resource_type='file', path_in_archive='.'): |
||
93 | """ |
||
94 | Download a resource by URL |
||
95 | """ |
||
96 | log = getLogger('ocrd.resource_manager.download') |
||
97 | destdir = Path(basedir, executable) |
||
98 | if not name: |
||
99 | name = re.sub('[^A-Za-z0-9]', '', url) |
||
100 | fpath = Path(destdir, name) |
||
101 | if fpath.exists() and not overwrite: |
||
102 | log.info("%s to be downloaded to %s which already exists and overwrite is False" % (url, fpath)) |
||
103 | return fpath |
||
104 | destdir.mkdir(parents=True, exist_ok=True) |
||
105 | if resource_type == 'file': |
||
106 | with requests.get(url, stream=True) as r: |
||
107 | with open(fpath, 'wb') as f: |
||
108 | copyfileobj(r.raw, f) |
||
109 | elif resource_type == 'tarball': |
||
110 | with pushd_popd(tempdir=True): |
||
111 | log.info("Downloading %s" % url) |
||
112 | with open('download.tar.xx', 'wb') as f_write_tar: |
||
113 | with requests.get(url, stream=True) as r: |
||
114 | copyfileobj(r.raw, f_write_tar) |
||
115 | Path('out').mkdir() |
||
116 | with pushd_popd('out'): |
||
117 | log.info("Extracting tarball") |
||
118 | with open_tarfile('../download.tar.xx', 'r:*') as tar: |
||
119 | tar.extractall() |
||
120 | log.info("Copying '%s' from tarball to %s" % (path_in_archive, fpath)) |
||
121 | copytree(path_in_archive, str(fpath)) |
||
122 | # TODO |
||
123 | # elif resource_type == 'github-dir': |
||
124 | return fpath |
||
125 |