Skip to content

Commit

Permalink
Merge pull request #630 from amyreese/version-file
Browse files Browse the repository at this point in the history
Read version from version files via ast
  • Loading branch information
takluyver committed Apr 9, 2023
2 parents 532bdaa + 9be0c3e commit 0c6608f
Show file tree
Hide file tree
Showing 3 changed files with 39 additions and 20 deletions.
55 changes: 35 additions & 20 deletions flit_core/flit_core/common.py
Expand Up @@ -71,6 +71,21 @@ def file(self):
else:
return self.path

@property
def version_files(self):
"""Files which will be parsed to find a version number
Files later in this list take precedence over earlier ones.
"""
if self.is_package:
paths = [self.path / '__init__.py']
for filename in ('version.py', '_version.py', '__version__.py'):
if (self.path / filename).is_file():
paths.insert(0, self.path / filename)
return paths
else:
return [self.path]

def iter_files(self):
"""Iterate over the files contained in this module.
Expand Down Expand Up @@ -127,26 +142,26 @@ def get_docstring_and_version_via_ast(target):
Return a tuple like (docstring, version) for the given module,
extracted by parsing its AST.
"""
# read as bytes to enable custom encodings
with target.file.open('rb') as f:
node = ast.parse(f.read())
for child in node.body:
# Only use the version from the given module if it's a simple
# string assignment to __version__
is_version_str = (
isinstance(child, ast.Assign)
and any(
isinstance(target, ast.Name)
and target.id == "__version__"
for target in child.targets
)
and isinstance(child.value, ast.Str)
)
if is_version_str:
version = child.value.s
break
else:
version = None
version = None
for target_path in target.version_files:
# read as bytes to enable custom encodings
with target_path.open('rb') as f:
node = ast.parse(f.read())
for child in node.body:
# Only use the version from the given module if it's a simple
# string assignment to __version__
is_version_str = (
isinstance(child, ast.Assign)
and any(
isinstance(target, ast.Name)
and target.id == "__version__"
for target in child.targets
)
and isinstance(child.value, ast.Str)
)
if is_version_str:
version = child.value.s
break
return ast.get_docstring(node), version


Expand Down
@@ -1,3 +1,5 @@
"""This module has a __version__ that requires a relative import"""

from ._version import __version__

import a_package_that_doesnt_exist
@@ -1 +1,3 @@
"""Imposter docstring that shouldn't be used"""

__version__ = '0.5.8'

0 comments on commit 0c6608f

Please sign in to comment.