From be700472331354c454fa2792eec30c1b5ade9939 Mon Sep 17 00:00:00 2001 From: Ivan Kravets Date: Mon, 25 May 2015 23:26:35 +0300 Subject: [PATCH] Improve running project from other directory (not CWD) --- platformio/commands/run.py | 8 ++------ platformio/ide/projectgenerator.py | 18 +++++++++--------- platformio/util.py | 12 ++++++++++++ 3 files changed, 23 insertions(+), 15 deletions(-) diff --git a/platformio/commands/run.py b/platformio/commands/run.py index b61544ba..5b27d1c6 100644 --- a/platformio/commands/run.py +++ b/platformio/commands/run.py @@ -2,7 +2,7 @@ # See LICENSE for details. from datetime import datetime -from os import chdir, getcwd +from os import getcwd from os.path import getmtime, isdir, join from shutil import rmtree from time import time @@ -28,9 +28,7 @@ from platformio.platforms.base import PlatformFactory @click.pass_context def cli(ctx, environment, target, upload_port, # pylint: disable=R0913,R0914 project_dir, verbose): - initial_cwd = getcwd() - chdir(project_dir) - try: + with util.cd(project_dir): config = util.get_project_config() if not config.sections(): @@ -74,8 +72,6 @@ def cli(ctx, environment, target, upload_port, # pylint: disable=R0913,R0914 if not all(results): raise exception.ReturnErrorCode() - finally: - chdir(initial_cwd) class EnvironmentProcessor(object): diff --git a/platformio/ide/projectgenerator.py b/platformio/ide/projectgenerator.py index fda18e9e..ef3d2c51 100644 --- a/platformio/ide/projectgenerator.py +++ b/platformio/ide/projectgenerator.py @@ -26,16 +26,16 @@ class ProjectGenerator(object): return [d for d in listdir(tpls_dir) if isdir(join(tpls_dir, d))] - @staticmethod - def get_project_env(): + def get_project_env(self): data = {} - config = util.get_project_config() - for section in config.sections(): - if not section.startswith("env:"): - continue - data['env_name'] = section[4:] - for k, v in config.items(section): - data[k] = v + with util.cd(self.project_dir): + config = util.get_project_config() + for section in config.sections(): + if not section.startswith("env:"): + continue + data['env_name'] = section[4:] + for k, v in config.items(section): + data[k] = v return data @util.memoized diff --git a/platformio/util.py b/platformio/util.py index 6477df7e..a5d36c66 100644 --- a/platformio/util.py +++ b/platformio/util.py @@ -55,6 +55,18 @@ class AsyncPipe(Thread): self.join() +class cd: + def __init__(self, new_path): + self.new_path = new_path + self.prev_path = os.getcwd() + + def __enter__(self): + os.chdir(self.new_path) + + def __exit__(self, etype, value, traceback): + os.chdir(self.prev_path) + + class memoized(object): ''' Decorator. Caches a function's return value each time it is called.