PK ! M X X poetry/__init__.pyimport os
import sys
_ROOT = os.path.dirname(os.path.realpath(__file__))
_VENDOR = os.path.join(_ROOT, "_vendor")
_CURRENT_VENDOR = os.path.join(
_VENDOR, "py{}".format(".".join(str(v) for v in sys.version_info[:2]))
)
# Add vendored dependencies to path.
sys.path.insert(0, _CURRENT_VENDOR)
from .__version__ import __version__ # noqa
PK ! );[ [ poetry/__main__.pyimport sys
if __name__ == "__main__":
from .console import main
sys.exit(main())
PK ! poetry/__version__.py__version__ = "0.12.11a"
PK ! 뚩 poetry/_vendor/.gitignore*
!.gitignore
PK ! 9[#
poetry/config.pyfrom __future__ import absolute_import
import io
import os
from typing import Any
from tomlkit import document
from tomlkit import table
from .locations import CONFIG_DIR
from .utils._compat import Path
from .utils.toml_file import TomlFile
class Config:
def __init__(self, file): # type: (TomlFile) -> None
self._file = file
if not self._file.exists():
self._content = document()
else:
self._content = file.read()
@property
def name(self):
return str(self._file.path)
@property
def file(self):
return self._file
@property
def content(self):
return self._content
def setting(self, setting_name, default=None): # type: (str) -> Any
"""
Retrieve a setting value.
"""
keys = setting_name.split(".")
config = self._content
for key in keys:
if key not in config:
return default
config = config[key]
return config
def add_property(self, key, value):
keys = key.split(".")
config = self._content
for i, key in enumerate(keys):
if key not in config and i < len(keys) - 1:
config[key] = table()
if i == len(keys) - 1:
config[key] = value
break
config = config[key]
self.dump()
def remove_property(self, key):
keys = key.split(".")
config = self._content
for i, key in enumerate(keys):
if key not in config:
return
if i == len(keys) - 1:
del config[key]
break
config = config[key]
self.dump()
def dump(self):
# Ensuring the file is only readable and writable
# by the current user
mode = 0o600
umask = 0o777 ^ mode
if self._file.exists():
# If the file already exists, remove it
# if the permissions are higher than what we want
current_mode = os.stat(str(self._file)).st_mode & 0o777
if current_mode != 384:
os.remove(str(self._file))
if self._file.exists():
fd = str(self._file)
else:
umask_original = os.umask(umask)
try:
fd = os.open(str(self._file), os.O_WRONLY | os.O_CREAT, mode)
finally:
os.umask(umask_original)
with io.open(fd, "w", encoding="utf-8") as f:
f.write(self._content.as_string())
@classmethod
def create(cls, file, base_dir=None): # type: (...) -> Config
if base_dir is None:
base_dir = CONFIG_DIR
file = TomlFile(Path(base_dir) / file)
return cls(file)
PK ! R R poetry/console/__init__.pyfrom .application import Application
def main():
return Application().run()
PK ! èot! ! poetry/console/application.pyimport os
import re
import sys
import traceback
from cleo import Application as BaseApplication
from cleo.formatters import Formatter
from cleo.inputs import ArgvInput
from cleo.outputs import ConsoleOutput
from cleo.outputs import Output
from poetry import __version__
from poetry.io.raw_argv_input import RawArgvInput
from .commands import AboutCommand
from .commands import AddCommand
from .commands import BuildCommand
from .commands import CheckCommand
from .commands import ConfigCommand
from .commands import DevelopCommand
from .commands import InitCommand
from .commands import InstallCommand
from .commands import LockCommand
from .commands import NewCommand
from .commands import PublishCommand
from .commands import RemoveCommand
from .commands import RunCommand
from .commands import ScriptCommand
from .commands import SearchCommand
from .commands import ShellCommand
from .commands import ShowCommand
from .commands import UpdateCommand
from .commands import VersionCommand
from .commands.cache import CacheClearCommand
from .commands.debug import DebugInfoCommand
from .commands.debug import DebugResolveCommand
from .commands.self import SelfUpdateCommand
class Application(BaseApplication):
def __init__(self):
super(Application, self).__init__("Poetry", __version__)
self._poetry = None
self._skip_io_configuration = False
self._formatter = Formatter(True)
self._formatter.add_style("error", "red", options=["bold"])
@property
def poetry(self):
from poetry.poetry import Poetry
if self._poetry is not None:
return self._poetry
self._poetry = Poetry.create(os.getcwd())
return self._poetry
def reset_poetry(self): # type: () -> None
self._poetry = None
def run(self, i=None, o=None): # type: (...) -> int
if i is None:
i = ArgvInput()
if o is None:
o = ConsoleOutput()
self._formatter.with_colors(o.is_decorated())
o.set_formatter(self._formatter)
name = i.get_first_argument()
if name in ["run", "script"]:
self._skip_io_configuration = True
i = RawArgvInput()
return super(Application, self).run(i, o)
def do_run(self, i, o):
name = self.get_command_name(i)
if name not in ["run", "script"]:
return super(Application, self).do_run(i, o)
command = self.find(name)
self._running_command = command
status_code = command.run(i, o)
self._running_command = None
return status_code
def configure_io(self, i, o):
if self._skip_io_configuration:
return
super(Application, self).configure_io(i, o)
def get_default_commands(self): # type: () -> list
commands = super(Application, self).get_default_commands()
commands += [
AboutCommand(),
AddCommand(),
BuildCommand(),
CheckCommand(),
ConfigCommand(),
DevelopCommand(),
InitCommand(),
InstallCommand(),
LockCommand(),
NewCommand(),
PublishCommand(),
RemoveCommand(),
RunCommand(),
ScriptCommand(),
SearchCommand(),
ShellCommand(),
ShowCommand(),
UpdateCommand(),
VersionCommand(),
]
# Cache commands
commands += [CacheClearCommand()]
# Debug commands
commands += [DebugInfoCommand(), DebugResolveCommand()]
# Self commands
commands += [SelfUpdateCommand()]
return commands
def render_exception(self, e, o):
tb = traceback.extract_tb(sys.exc_info()[2])
title = "[%s] " % e.__class__.__name__
l = len(title)
width = self._terminal.width
if not width:
width = sys.maxsize
formatter = o.get_formatter()
lines = []
for line in re.split(r"\r?\n", str(e)):
for splitline in [
line[x : x + (width - 4)] for x in range(0, len(line), width - 4)
]:
line_length = (
len(re.sub(r"\[[^m]*m", "", formatter.format(splitline))) + 4
)
lines.append((splitline, line_length))
l = max(line_length, l)
messages = []
empty_line = formatter.format("%s" % (" " * l))
messages.append(empty_line)
messages.append(
formatter.format("%s%s" % (title, " " * max(0, l - len(title))))
)
for line in lines:
messages.append(
formatter.format(
"%s %s" % (line[0], " " * (l - line[1]))
)
)
messages.append(empty_line)
o.writeln(messages, Output.OUTPUT_RAW)
if Output.VERBOSITY_VERBOSE <= o.get_verbosity():
o.writeln("Exception trace:")
for exc_info in tb:
file_ = exc_info[0]
line_number = exc_info[1]
function = exc_info[2]
line = exc_info[3]
o.writeln(
" %s in %s()> "
"at line %s" % (file_, function, line_number)
)
o.writeln(" %s" % line)
o.writeln("")
if self._running_command is not None:
o.writeln("%s" % self._running_command.get_synopsis())
o.writeln("")
PK ! BF3,h h # poetry/console/commands/__init__.pyfrom .about import AboutCommand
from .add import AddCommand
from .build import BuildCommand
from .check import CheckCommand
from .config import ConfigCommand
from .develop import DevelopCommand
from .init import InitCommand
from .install import InstallCommand
from .lock import LockCommand
from .new import NewCommand
from .publish import PublishCommand
from .remove import RemoveCommand
from .run import RunCommand
from .script import ScriptCommand
from .search import SearchCommand
from .shell import ShellCommand
from .show import ShowCommand
from .update import UpdateCommand
from .version import VersionCommand
PK ! Rs߯ poetry/console/commands/about.pyfrom .command import Command
class AboutCommand(Command):
"""
Short information about Poetry.
about
"""
def handle(self):
self.line(
"""Poetry - Package Management for Python
Poetry is a dependency manager tracking local dependencies of your projects and libraries.
See https://github.com/sdispater/poetry> for more information.
"""
)
PK ! = = poetry/console/commands/add.pyfrom .init import InitCommand
from .env_command import EnvCommand
class AddCommand(EnvCommand, InitCommand):
"""
Add a new dependency to pyproject.toml>.
add
{ name* : Packages to add. }
{ --D|dev : Add package as development dependency. }
{ --git= : The url of the Git repository. }
{ --path= : The path to a dependency. }
{ --E|extras=* : Extras to activate for the dependency. }
{ --optional : Add as an optional dependency. }
{ --python= : Python version( for which the dependencies must be installed. }
{ --platform= : Platforms for which the dependencies must be installed. }
{ --allow-prereleases : Accept prereleases. }
{ --dry-run : Outputs the operations but will not execute anything
(implicitly enables --verbose). }
"""
help = """The add command adds required packages to your pyproject.toml> and installs them.
If you do not specify a version constraint, poetry will choose a suitable one based on the available package versions.
"""
_loggers = ["poetry.repositories.pypi_repository"]
def handle(self):
from poetry.installation import Installer
from poetry.semver import parse_constraint
from tomlkit import inline_table
packages = self.argument("name")
is_dev = self.option("dev")
if (self.option("git") or self.option("path") or self.option("extras")) and len(
packages
) > 1:
raise ValueError(
"You can only specify one package "
"when using the --git or --path options"
)
if self.option("git") and self.option("path"):
raise RuntimeError("--git and --path cannot be used at the same time")
section = "dependencies"
if is_dev:
section = "dev-dependencies"
original_content = self.poetry.file.read()
content = self.poetry.file.read()
poetry_content = content["tool"]["poetry"]
if section not in poetry_content:
poetry_content[section] = {}
for name in packages:
for key in poetry_content[section]:
if key.lower() == name.lower():
raise ValueError("Package {} is already present".format(name))
if self.option("git") or self.option("path"):
requirements = {packages[0]: ""}
else:
requirements = self._determine_requirements(
packages, allow_prereleases=self.option("allow-prereleases")
)
requirements = self._format_requirements(requirements)
# validate requirements format
for constraint in requirements.values():
parse_constraint(constraint)
for name, _constraint in requirements.items():
constraint = inline_table()
constraint["version"] = _constraint
if self.option("git"):
del constraint["version"]
constraint["git"] = self.option("git")
elif self.option("path"):
del constraint["version"]
constraint["path"] = self.option("path")
if self.option("optional"):
constraint["optional"] = True
if self.option("allow-prereleases"):
constraint["allows-prereleases"] = True
if self.option("extras"):
extras = []
for extra in self.option("extras"):
if " " in extra:
extras += [e.strip() for e in extra.split(" ")]
else:
extras.append(extra)
constraint["extras"] = self.option("extras")
if self.option("python"):
constraint["python"] = self.option("python")
if self.option("platform"):
constraint["platform"] = self.option("platform")
if len(constraint) == 1 and "version" in constraint:
constraint = constraint["version"]
poetry_content[section][name] = constraint
# Write new content
self.poetry.file.write(content)
# Cosmetic new line
self.line("")
# Update packages
self.reset_poetry()
installer = Installer(
self.output,
self.env,
self.poetry.package,
self.poetry.locker,
self.poetry.pool,
)
installer.dry_run(self.option("dry-run"))
installer.update(True)
installer.whitelist(requirements)
try:
status = installer.run()
except Exception:
self.poetry.file.write(original_content)
raise
if status != 0 or self.option("dry-run"):
# Revert changes
if not self.option("dry-run"):
self.error(
"\n"
"Addition failed, reverting pyproject.toml "
"to its original content."
)
self.poetry.file.write(original_content)
return status
PK ! cP9 poetry/console/commands/build.pyfrom .env_command import EnvCommand
class BuildCommand(EnvCommand):
"""
Builds a package, as a tarball and a wheel by default.
build
{ --f|format= : Limit the format to either wheel or sdist. }
"""
def handle(self):
from poetry.masonry import Builder
fmt = "all"
if self.option("format"):
fmt = self.option("format")
package = self.poetry.package
self.line(
"Building {}> ({}>)".format(
package.pretty_name, package.version
)
)
builder = Builder(self.poetry, self.env, self.output)
builder.build(fmt)
PK ! Hu% % ) poetry/console/commands/cache/__init__.pyfrom .clear import CacheClearCommand
PK !
0w &