def init(ctx): """ Generate project layout with an example contract. """ project = ctx.obj['PROJECT'] if not os.path.exists(project.primary_config_file_path): with open(project.primary_config_file_path, 'w') as config_file: config_file.write("[populus]\n") config_file.write("project_dir = {0}".format( os.path.relpath(project.project_dir))) if ensure_path_exists(project.contracts_dir): click.echo("Created Directory: ./{0}".format( os.path.relpath(project.contracts_dir))) example_contract_path = os.path.join(project.contracts_dir, 'Greeter.sol') if not os.path.exists(example_contract_path): with open(example_contract_path, 'w') as example_contract_file: example_contract_file.write(GREETER_FILE_CONTENTS) click.echo("Created Example Contract: ./{0}".format( os.path.relpath(example_contract_path))) tests_dir = os.path.join(project.project_dir, 'tests') if ensure_path_exists(tests_dir): click.echo("Created Directory: ./{0}".format( os.path.relpath(tests_dir))) example_tests_path = os.path.join(tests_dir, 'test_greeter.py') if not os.path.exists(example_tests_path): with open(example_tests_path, 'w') as example_tests_file: example_tests_file.write(TEST_FILE_CONTENTS) click.echo("Created Example Tests: ./{0}".format( os.path.relpath(example_tests_path)))
def _loaded_contract_fixtures(populus_source_root, project_dir, request): contracts_to_load_from_fn = getattr(request.function, '_populus_contract_fixtures', []) contracts_to_load_from_module = getattr(request.module, '_populus_contract_fixtures', []) contracts_to_load = itertools.chain( contracts_to_load_from_fn, contracts_to_load_from_module, ) contracts_source_dir = get_contracts_source_dir(project_dir) for item in contracts_to_load: ensure_path_exists(contracts_source_dir) fixture_path = os.path.join( populus_source_root, 'tests', 'fixtures', item, ) if os.path.exists(item): src_path = item elif os.path.exists(fixture_path): src_path = fixture_path else: raise ValueError("Unable to load contract '{0}'".format(item)) dst_path = os.path.join(contracts_source_dir, os.path.basename(item)) if os.path.exists(dst_path): raise ValueError("File already present at '{0}'".format(dst_path)) shutil.copy(src_path, dst_path)
def _write_project_file(filename, content=''): full_path = os.path.join(project_dir, filename) file_dir = os.path.dirname(full_path) ensure_path_exists(file_dir) with open(full_path, 'w') as f: f.write(content)
def test_reset_chain_on_empty_project_dir(project_dir, write_project_file): project = Project() data_dir = project.get_blockchain_data_dir('test-chain') ensure_path_exists(data_dir) chaindata_dir = project.get_blockchain_chaindata_dir('test-chain') dapp_dir = project.get_blockchain_dapp_dir('test-chain') nodekey_path = project.get_blockchain_nodekey_path('test-chain') geth_ipc_path = project.get_blockchain_ipc_path('test-chain') # sanity check assert os.path.exists(data_dir) assert not os.path.exists(chaindata_dir) assert not os.path.exists(dapp_dir) assert not os.path.exists(nodekey_path) assert not os.path.exists(geth_ipc_path) reset_chain(data_dir) assert os.path.exists(data_dir) assert not os.path.exists(chaindata_dir) assert not os.path.exists(dapp_dir) assert not os.path.exists(nodekey_path) assert not os.path.exists(geth_ipc_path)
def chain_init(ctx, chain_name): """ Prepare the current chain for migrations. contract onto this chain as well as """ project = ctx.obj['PROJECT'] ensure_path_exists(project.migrations_dir) # Determine which chain should be used. if not chain_name: chain_name = select_chain(project) chain_section_name = "chain:{0}".format(chain_name) if chain_name == 'testrpc': ctx.abort("Cannot initialize the {0!r} chain".format(chain_name)) # The `mainnet` and `morden` chains have default configurations. If the # user is working on one of these chains then we need to add the section # header so that we can write new config to it. if not project.config.has_section(chain_section_name): project.config.add_section(chain_section_name) chain = project.get_chain(chain_name) if 'registrar' not in chain.chain_config: # We need to deploy the registrar with chain: web3 = chain.web3 if chain_name in {'mainnet', 'morden'}: show_chain_sync_progress(chain) account = get_unlocked_deploy_from_address(chain) # Configure web3 to now send from our chosen account by default web3.eth.defaultAccount = account # Deploy the registrar RegistrarFactory = chain.RegistrarFactory registrar = deploy_contract_and_verify(chain, contract_name='Registrar', base_contract_factory=RegistrarFactory) # TODO: set the value in the registrar. # Write the registrar address to the chain config project.config.set(chain_section_name, 'registrar', registrar.address) config_file_path = project.write_config() click.echo("Wrote updated chain configuration to {0!r}".format( config_file_path, )) click.echo("The '{0}' blockchain is ready for migrations.".format( chain_name ))
def chain_init(ctx, chain_name): """ Prepare the current chain for migrations. contract onto this chain as well as """ project = ctx.obj['PROJECT'] ensure_path_exists(project.migrations_dir) # Determine which chain should be used. if not chain_name: chain_name = select_chain(project) chain_section_name = "chain:{0}".format(chain_name) if chain_name == 'testrpc': ctx.abort("Cannot initialize the {0!r} chain".format(chain_name)) # The `mainnet` and `morden` chains have default configurations. If the # user is working on one of these chains then we need to add the section # header so that we can write new config to it. if not project.config.has_section(chain_section_name): project.config.add_section(chain_section_name) chain = project.get_chain(chain_name) if 'registrar' not in chain.chain_config: # We need to deploy the registrar with chain: web3 = chain.web3 if chain_name in {'mainnet', 'morden'}: show_chain_sync_progress(chain) account = get_unlocked_deploy_from_address(chain) # Configure web3 to now send from our chosen account by default web3.eth.defaultAccount = account # Deploy the registrar RegistrarFactory = chain.RegistrarFactory registrar = deploy_contract_and_verify( chain, contract_name='Registrar', base_contract_factory=RegistrarFactory) # TODO: set the value in the registrar. # Write the registrar address to the chain config project.config.set(chain_section_name, 'registrar', registrar.address) config_file_path = project.write_config() click.echo("Wrote updated chain configuration to {0!r}".format( config_file_path, )) click.echo( "The '{0}' blockchain is ready for migrations.".format(chain_name))
def init(ctx): """ Generate project layout with an example contract. """ project = ctx.obj['PROJECT'] has_json_config = check_if_json_config_file_exists(project.project_dir) if has_json_config: click.echo( "Found existing `populus.json` file. Not writing default config." ) else: json_config_file_path = get_json_config_file_path(project.project_dir) default_config = load_default_config() write_config( project.project_dir, default_config, json_config_file_path, ) click.echo( "Wrote default populus configuration to `./{0}`.".format( os.path.relpath(json_config_file_path, project.project_dir), ) ) project.load_config() if ensure_path_exists(project.contracts_dir): click.echo( "Created Directory: ./{0}".format( os.path.relpath(project.contracts_dir) ) ) example_contract_path = os.path.join(project.contracts_dir, 'Greeter.sol') if not os.path.exists(example_contract_path): with open(example_contract_path, 'w') as example_contract_file: example_contract_file.write(GREETER_FILE_CONTENTS) click.echo("Created Example Contract: ./{0}".format( os.path.relpath(example_contract_path) )) tests_dir = os.path.join(project.project_dir, 'tests') if ensure_path_exists(tests_dir): click.echo("Created Directory: ./{0}".format(os.path.relpath(tests_dir))) example_tests_path = os.path.join(tests_dir, 'test_greeter.py') if not os.path.exists(example_tests_path): with open(example_tests_path, 'w') as example_tests_file: example_tests_file.write(TEST_FILE_CONTENTS) click.echo("Created Example Tests: ./{0}".format( os.path.relpath(example_tests_path) ))
def new_local_chain(project_dir, chain_name): chains_path = os.path.join(project_dir, 'chains') ensure_path_exists(chains_path) chain_dir = os.path.join(chains_path, chain_name) data_dir = os.path.join(chain_dir, 'chain_data') overrides = { 'data_dir': data_dir, 'ws_port': '8546', 'rpc_port': '8545', 'port': '30303' } geth_kwargs = construct_test_chain_kwargs(**overrides) password = geth_kwargs.pop('password') data_dir = geth_kwargs.pop('data_dir') account = create_new_account(data_dir, password, **geth_kwargs) account = account.decode('ascii') genesis = GENESIS_BLOCK % ( account, account, ) genesis_path = os.path.join(chain_dir, 'genesis.json') with open(genesis_path, 'w+') as f: f.write(genesis) password_path = os.path.join(chain_dir, 'password') shutil.copyfile(password, password_path) ipc_path = geth_kwargs['ipc_path'] init = INIT_COMMAND.format(data_dir=data_dir, ipc_path=ipc_path, genesis_path=genesis_path) init_geth_path = os.path.join(chain_dir, 'init_chain.sh') with open(init_geth_path, 'w+') as f: f.write(SHEBANG) f.write('\n') f.write(init) chmod_plus_x(init_geth_path) run = RUN_COMMAND.format(data_dir=data_dir, ipc_path=ipc_path, password_path=password_path, account=account) run_geth_path = os.path.join(chain_dir, 'run_chain.sh') with open(run_geth_path, 'w+') as f: f.write(SHEBANG) f.write('\n') f.write(run) chmod_plus_x(run_geth_path)
def get_logger(self, name): logger = logging.getLogger(name) logger.setLevel(self.log_level) has_stream_handler = any( isinstance(handler, logging.StreamHandler) for handler in logger.handlers ) if not has_stream_handler: stream_handler = logging.StreamHandler() stream_handler.setLevel(self.log_level) stream_handler.setFormatter(logging.Formatter( name + ': %(levelname)s: %(asctime)s %(message)s' )) logger.addHandler(stream_handler) has_file_handler = any( isinstance(handler, handlers.RotatingFileHandler) for handler in logger.handlers ) if self.logfile_root is not None and not has_file_handler: ensure_path_exists(self.logfile_root) logfile_path = os.path.join(self.logfile_root, "{0}.log".format(name)) file_handler = handlers.RotatingFileHandler(logfile_path, backupCount=20, maxBytes=10000000) file_handler.setLevel(logging.DEBUG) file_handler.setFormatter(logging.Formatter( '%(levelname)s: %(asctime)s %(message)s' )) logger.addHandler(file_handler) if is_rollbar_available(): import rollbar from rollbar.logger import RollbarHandler has_rollbar_handler = any( isinstance(handler, RollbarHandler) for handler in logger.handlers ) if not has_rollbar_handler: rb_secret = os.environ['ROLLBAR_SECRET'] rb_environment = os.environ['ROLLBAR_ENVIRONMENT'] if not rollbar._initialized: rollbar.init(rb_secret, rb_environment) rb_handler = RollbarHandler() rb_handler.setLevel(logging.WARNING) logger.addHandler(rb_handler) return logger
def init_cmd(ctx): """ Generate project layout with an example contract. """ logger = logging.getLogger('populus.cli.init_cmd') project = ctx.obj['PROJECT'] has_json_config = check_if_json_config_file_exists(project.project_dir) if has_json_config: logger.info( "Found existing `populus.json` file. Not writing default config.") else: json_config_file_path = get_json_config_file_path(project.project_dir) default_config = load_default_config() write_config( project.project_dir, default_config, json_config_file_path, ) logger.info("Wrote default populus configuration to `./{0}`.".format( os.path.relpath(json_config_file_path, project.project_dir), )) project.load_config() if ensure_path_exists(project.contracts_source_dir): logger.info("Created Directory: ./{0}".format( os.path.relpath(project.contracts_source_dir))) example_contract_path = os.path.join(project.contracts_source_dir, 'Greeter.sol') if not os.path.exists(example_contract_path): shutil.copy(GREETER_SOURCE_PATH, example_contract_path) logger.info("Created Example Contract: ./{0}".format( os.path.relpath(example_contract_path))) tests_dir = os.path.join(project.project_dir, 'tests') if ensure_path_exists(tests_dir): logger.info("Created Directory: ./{0}".format( os.path.relpath(tests_dir))) example_tests_path = os.path.join(tests_dir, 'test_greeter.py') if not os.path.exists(example_tests_path): shutil.copy(GREETER_TEST_PATH, example_tests_path) logger.info("Created Example Tests: ./{0}".format( os.path.relpath(example_tests_path)))
def issue(ctx, owner_address, identity): parent_ctx = ctx.parent validate_identity(parent_ctx, identity) owner_address = validate_owner_address(parent_ctx, owner_address) web3 = parent_ctx.web3 token = parent_ctx.token wait = parent_ctx.wait txn_hash = token.transact().mint(owner_address, identity) click.echo("Minted new token via txn: {0}".format(txn_hash)) click.echo("Waiting for txn to be mined ...", nl=False) txn_receipt = wait.for_receipt(txn_hash) txn = web3.eth.getTransaction(txn_hash) click.echo("MINED") token_id = token.call().ownedToken(owner_address) token_id_hex = web3.fromAscii(token_id) identity = token.call().identityOf(token_id) token_details = ("\n" "Token Details:\n" "------------\n" "owner: {owner}\n" "identity: {identity}\n" "token_id: {token_id_hex}\n" "minted in txn: {txn_hash}\n" "blockNumber: {blockNumber}\n" "gas: {gasUsed} / {gas}\n" "".format( owner=owner_address, identity=identity, token_id_hex=token_id_hex, txn_hash=txn_hash, blockNumber=txn_receipt['blockNumber'], gas=txn['gas'], gasUsed=txn_receipt['gasUsed'], )) click.echo(token_details) ensure_path_exists('./token-logs') log_file_path = './token-logs/{owner}.txt'.format(owner=owner_address) with open(log_file_path, 'w') as log_file: log_file.write(token_details) click.echo("Wrote log to: {0}".format(log_file_path))
def __init__(self, project_dir=None, user_config_file_path=None, create_config_file=False): # noqa: E501 self._reset_configs_cache() if project_dir is None: self.project_dir = os.getcwd() else: self.project_dir = os.path.abspath(project_dir) # user config self.user_config_file_path = user_config_file_path if self.user_config_file_path is None: self.user_config_file_path = get_user_json_config_file_path() if not check_if_user_json_config_file_exists(): user_config_path = get_user_json_config_file_path() user_defaults_path = get_user_default_config_path() ensure_path_exists(os.path.dirname(user_config_path)) shutil.copyfile(user_defaults_path, user_config_path) # legacy config legacy_path = get_legacy_json_config_file_path(self.project_dir) if os.path.exists(legacy_path): self.legacy_config_path = legacy_path warnings.warn( "Found legacy config file at {legacy_path}".format( legacy_path=legacy_path), PopulusResourceWarning) # project config self.config_file_path = get_json_config_file_path(self.project_dir) if not os.path.exists(self.config_file_path): if create_config_file: defaults_path = get_default_config_path() shutil.copyfile(defaults_path, self.config_file_path) else: if self.legacy_config_path is not None: msg = "No project config file found at {project_dir}, but a legacy config exists. Try to upgrade" # noqa: E501 else: msg = "No project config file found at {project_dir}" raise FileNotFoundError( msg.format(project_dir=self.project_dir)) self.load_config()
def _loaded_test_contract_fixtures(project_dir, request): test_contracts_to_load_from_fn = getattr( request.function, '_populus_test_contract_fixtures', [] ) test_contracts_to_load_from_module = getattr( request.module, '_populus_test_contract_fixtures', [] ) test_contracts_to_load = itertools.chain( test_contracts_to_load_from_module, test_contracts_to_load_from_fn, ) tests_dir = get_tests_dir(project_dir) for item, dst_path in test_contracts_to_load: ensure_path_exists(tests_dir) fixture_path = os.path.join( POPULUS_SOURCE_ROOT, 'tests', 'fixtures', item, ) if os.path.exists(item): src_path = item elif os.path.exists(fixture_path): src_path = fixture_path else: raise ValueError("Unable to load test contract '{0}'".format(item)) if dst_path is None: dst_path = os.path.join(tests_dir, os.path.basename(item)) elif not os.path.isabs(dst_path): dst_path = os.path.join(project_dir, dst_path) ensure_path_exists(os.path.dirname(dst_path)) if os.path.exists(dst_path): raise ValueError("File already present at '{0}'".format(dst_path)) shutil.copy(src_path, dst_path)
def init_project(project_dir, logger): if project_dir is None: project_dir = os.getcwd() else: project_dir = os.path.abspath(project_dir) has_json_config = check_if_json_config_file_exists(project_dir) if has_json_config: logger.info( "Found existing `project.json` file. Not writing default config.") project = Project(project_dir) logger.info("Wrote default populus configuration to `./{0}`.".format( os.path.relpath(project.config_file_path), )) for source_dir in project.contracts_source_dirs: if ensure_path_exists(source_dir): logger.info("Created Directory: ./{0}".format( os.path.relpath(source_dir))) example_contract_path = os.path.join(project.contracts_source_dirs[0], 'Greeter.sol') if not os.path.exists(example_contract_path): shutil.copy(GREETER_SOURCE_PATH, example_contract_path) logger.info("Created Example Contract: ./{0}".format( os.path.relpath(example_contract_path))) tests_dir = os.path.join(project.project_dir, 'tests') if ensure_path_exists(tests_dir): logger.info("Created Directory: ./{0}".format( os.path.relpath(tests_dir))) example_tests_path = os.path.join(tests_dir, 'test_greeter.py') if not os.path.exists(example_tests_path): shutil.copy(GREETER_TEST_PATH, example_tests_path) logger.info("Created Example Tests: ./{0}".format( os.path.relpath(example_tests_path))) return project
def test_reset_chain(project, write_project_file): data_dir = get_data_dir(project.project_dir, 'test-chain') ensure_path_exists(data_dir) chaindata_dir = get_chaindata_dir(data_dir) dapp_dir = get_dapp_dir(data_dir) nodekey_path = get_nodekey_path(data_dir) geth_ipc_path = get_geth_ipc_path(data_dir) ensure_path_exists(chaindata_dir) ensure_path_exists(dapp_dir) write_project_file(nodekey_path) write_project_file(geth_ipc_path) # sanity check assert os.path.exists(data_dir) assert os.path.exists(chaindata_dir) assert os.path.exists(dapp_dir) assert os.path.exists(nodekey_path) assert os.path.exists(geth_ipc_path) reset_chain(data_dir) assert os.path.exists(data_dir) assert not os.path.exists(chaindata_dir) assert not os.path.exists(dapp_dir) assert not os.path.exists(nodekey_path) assert not os.path.exists(geth_ipc_path)
def init(ctx): """ Generate project layout with an example contract. """ project = ctx.obj['PROJECT'] if not os.path.exists(project.primary_config_file_path): with open(project.primary_config_file_path, 'w') as config_file: config_file.write("[populus]\n") config_file.write("project_dir = {0}".format( os.path.relpath(project.project_dir) )) if ensure_path_exists(project.contracts_dir): click.echo( "Created Directory: ./{0}".format( os.path.relpath(project.contracts_dir) ) ) example_contract_path = os.path.join(project.contracts_dir, 'Greeter.sol') if not os.path.exists(example_contract_path): with open(example_contract_path, 'w') as example_contract_file: example_contract_file.write(GREETER_FILE_CONTENTS) click.echo("Created Example Contract: ./{0}".format( os.path.relpath(example_contract_path) )) tests_dir = os.path.join(project.project_dir, 'tests') if ensure_path_exists(tests_dir): click.echo("Created Directory: ./{0}".format(os.path.relpath(tests_dir))) example_tests_path = os.path.join(tests_dir, 'test_greeter.py') if not os.path.exists(example_tests_path): with open(example_tests_path, 'w') as example_tests_file: example_tests_file.write(TEST_FILE_CONTENTS) click.echo("Created Example Tests: ./{0}".format( os.path.relpath(example_tests_path) ))
def project_dir(tmpdir, monkeypatch): _project_dir = str(tmpdir.mkdir("project-dir")) # setup project directories ensure_path_exists(get_contracts_source_dir(_project_dir)) ensure_path_exists(get_build_asset_dir(_project_dir)) ensure_path_exists(get_base_blockchain_storage_dir(_project_dir)) monkeypatch.chdir(_project_dir) monkeypatch.syspath_prepend(_project_dir) return _project_dir
def project_dir(tmpdir, monkeypatch): _project_dir = str(tmpdir.mkdir("project-dir")) # setup project directories for source_dir in get_contracts_source_dirs(_project_dir): ensure_path_exists(source_dir) ensure_path_exists(get_build_asset_dir(_project_dir)) ensure_path_exists(get_base_blockchain_storage_dir(_project_dir)) monkeypatch.chdir(_project_dir) monkeypatch.syspath_prepend(_project_dir) return _project_dir
def project_dir(tmpdir, monkeypatch): from populus.utils.filesystem import ( ensure_path_exists, get_contracts_dir, get_build_dir, get_blockchains_dir, ) _project_dir = str(tmpdir.mkdir("project-dir")) # setup project directories ensure_path_exists(get_contracts_dir(_project_dir)) ensure_path_exists(get_build_dir(_project_dir)) ensure_path_exists(get_blockchains_dir(_project_dir)) monkeypatch.chdir(_project_dir) monkeypatch.syspath_prepend(_project_dir) return _project_dir