Example #1
0
def run_py(path: str):
    '''
    run a file like `python ?`.
    '''

    py_file = FileInfo(path)
    if not py_file.is_file():
        raise FileNotFoundError(f'{path} is not a file')

    with use_path(py_file.path.dirname):
        return runpy.run_path(py_file.path, run_name='__main__')
Example #2
0
def get_global_funcnames(pyfile: fsoopify.FileInfo) -> list:
    'get a list of global funcnames (use for entry_points.console_scripts).'
    assert pyfile.is_file()

    import ast

    funcnames = []
    mod = ast.parse(pyfile.read_text())
    for stmt in mod.body:
        if isinstance(stmt, ast.FunctionDef):
            funcnames.append(stmt.name)
    return funcnames
def test_get_global_funcnames():
    from fsoopify import FileInfo
    from setupmeta_builder.utils import get_global_funcnames

    funcnames = get_global_funcnames(FileInfo(__file__))
    assert 'test_get_global_funcnames' in funcnames
    for name in funcnames:
        assert name.startswith('test_')
class GlobalSettings:
    def __init__(self):
        home = str(Path.home())
        self._fileinfo = FileInfo(os.path.join(home, SYNC_CONFIG_NAME))
        self._data = self._fileinfo.load() if self._fileinfo.is_exists(
        ) else {}

    def _save(self):
        self._fileinfo.dump(self._data)

    @property
    def token(self):
        return self._data.get('token')

    @token.setter
    def token(self, value):
        self._data['token'] = value
        self._save()
Example #5
0
def find_pipfile_path(script_file: FileInfo, depth: int):
    dir_info = script_file.get_parent()
    while depth > 0:
        pf = dir_info.get_fileinfo('Pipfile')
        if pf.is_file():
            return pf.path
        dir_info = dir_info.get_parent()
        depth -= 1
    raise RuntimeError('cannot found Pipfile.')
Example #6
0
    def pick():
        print(yellow('[?]'), 'please pick a file that contains entry points:')
        idx = pick_item(filelist, defidx=find_default_on_files(filelist))
        if idx == -1:
            return

        filepath = filelist[idx]
        content = FileInfo(filepath).read_text()
        matches = re.findall('^def ([^(]+)\\(.+$', content, flags=re.M) # func names

        def find_default_on_funcs(items):
            for wkname in ('cli', 'main',):
                for i, x in enumerate(items):
                    if x == wkname:
                        return i

        if not matches:
            logger.error('no python files was founds from {}.'.format(lightgreen(filepath)))
            return

        print(yellow('[?]'), 'please pick a func from {}:'.format(lightgreen(Path(filepath).name)))
        idx = pick_item(matches, defidx=find_default_on_funcs(matches))
        if idx == -1:
            return
        funcname = matches[idx]

        msg = yellow('[?]')
        msg += 'please input the entry points name (default is {})'.format(
            lightgreen(packages_names[0])
        )
        print(msg, end='')
        entry_points = input().strip() or packages_names[0]

        module_name = filepath[:-3].replace(os.sep, '.') # remove `.py` and more

        script = '{entry_points}={module_name}:{funcname}'.format(
            entry_points=entry_points,
            module_name=module_name,
            funcname=funcname,
        )
        if script not in console_scripts:
            console_scripts.append(script)
        return _pick_more('entry_points')
Example #7
0
    def parse(cls, path):
        fileinfo = FileInfo(path)
        if not fileinfo.is_file():
            logger.debug('no exists metadata found.')
            return None

        metadata = PackageMetadata()

        fileinfo.load()
        try:
            content = fileinfo.load()
        except SerializeError:
            raise QuickExit(
                '[ERROR] <{}> is not a valid json file. try delete it for continue.'
                .format(path))

        metadata.__dict__.update(content)

        return metadata
Example #8
0
def configure_gitignore(proj_info: ProjectInfo):
    logger = get_logger()
    gitignore = FileInfo(proj_info.root_dir)

    if not gitignore.is_exists():
        logger.info(f'{lightgreen(gitignore)} does not exists')
        return

    gitignore_text = gitignore.read_text().splitlines()
    gitignore_set = set(gitignore_text)
    appends = []
    for line in GIT_IGNORES_VALUES:
        if line not in gitignore_set:
            appends.append(line)

    if appends:
        if GIT_IGNORES_HEADER in gitignore_set:
            raise NotImplementedError
        else:
            gitignore_text.append('')
            gitignore_text.append(GIT_IGNORES_HEADER)
            gitignore_text.extend(appends)

        gitignore.write_text('\n'.join(gitignore_text), append=False)
Example #9
0
 def resolve_from_file(node: FileInfo):
     store['pkg_root'] = node.path
     if node.path.name != '__init__.py':
         name_parts.append(node.path.name.pure_name)
     resolve_from_dir(node.get_parent())
Example #10
0
def get_conf_file() -> FileInfo:
    path = Path.from_home() / '.config' / 'clearcache' / 'conf.json'
    return FileInfo(path)
Example #11
0
def compute_sha1(path: str):
    'compute sha1 checksum.'

    return FileInfo(path).get_file_hash('sha1')[0].upper()
Example #12
0
def test_file_get_parent_nt():
    ofile = FileInfo('c:\\d\\e')
    assert ofile.get_parent().path == 'c:\\d'
    assert ofile.get_parent(1).path == 'c:\\d'
    assert ofile.get_parent(2).path == 'c:'
    assert ofile.get_parent(3) is None
Example #13
0
def test_file_node_type():
    assert FileInfo('abc').node_type is NodeType.file
 def __init__(self):
     home = str(Path.home())
     self._fileinfo = FileInfo(os.path.join(home, SYNC_CONFIG_NAME))
     self._data = self._fileinfo.load() if self._fileinfo.is_exists(
     ) else {}
Example #15
0
def test_file_get_parent():
    a_topdir_relpath = [os.pardir] * 50
    ofile = FileInfo(os.path.join(*a_topdir_relpath))
    assert ofile.get_parent() is None
Example #16
0
 def update_args(self, app: App, args: dict):
     super().update_args(app, args)
     script_file = FileInfo(args['path'])
     args['pipfile'] = self._find_pipfile_path(script_file, 5)
Example #17
0
 def save(self, path):
     ''' save template to file so we can get it next time. '''
     fileinfo = FileInfo(path)
     fileinfo.dump(self.__dict__, kwargs={'indent': 2})
Example #18
0
 def load_template(self, name):
     path = os.path.join(Path(sys.argv[0]).dirname, 'templates', name)
     return FileInfo(path).read_text()