Exemplo n.º 1
0
def get_result(conf):
    # Load config file
    f = open(conf, 'r')
    conf = json.loads(f.read())
    f.close()

    d = Dir(conf)
    res = d.get_result()

    return res
Exemplo n.º 2
0
 def browse_repo(self, rel=None):
     """Browse remote repo function."""
     self.c.screen.clear()
     self.base_status("browse loading...", text_only=True)
     _directory = Dir(self._client)
     files = _directory.list(rel)
     if files is None:
         msg = os.path.join(self._base,
                            rel) + " - Not under version control."
         logger.warning(msg)
         self.base_status(msg, text_only=True)
         self.history = self.history[:-1]
     else:
         self.base_status(os.path.join(self._base, rel if rel else ''))
         self.c.print_remote_files(files)
Exemplo n.º 3
0
    def get_message(self, message=None):
        """
        Returns decoded message
        :param message: email.message.Message
        """
        if message is None:
            message = self.message

        payload = message.get_payload()
        encoding = message.get('Content-Transfer-Encoding', '8bit')
        charset = message.get_content_charset() or 'utf-8'

        content_subtype = message.get_content_subtype()

        if message.is_multipart():
            return '\n'.join(self.get_message(msg_part)
                             for msg_part in payload)

        decoded_payload = self.get_decoded_payload(payload, encoding, charset)

        if content_subtype != 'plain':
            if not self.attachments:
                return ''
            self.dir = self.dir or Dir.make_unique_dir()
            filename = message.get_filename() or 'mail.%s' % content_subtype
            file_dir = os.path.join(self.dir, filename)
            try:
                with open(file_dir, 'wb') as f:
                    f.write(decoded_payload)
            except IOError:
                sys.stderr.write('Cannot open %s\n' % file_dir)
                return ''
            return '%s saved' % file_dir

        return decoded_payload.decode(charset)
Exemplo n.º 4
0
    def get_message(self, message=None):
        """
        Returns decoded message
        :param message: email.message.Message
        """
        if message is None:
            message = self.message

        payload = message.get_payload()
        encoding = message.get('Content-Transfer-Encoding', '8bit')
        charset = message.get_content_charset() or 'utf-8'

        content_subtype = message.get_content_subtype()

        if message.is_multipart():
            return '\n'.join(
                self.get_message(msg_part) for msg_part in payload)

        decoded_payload = self.get_decoded_payload(payload, encoding, charset)

        if content_subtype != 'plain':
            if not self.attachments:
                return ''
            self.dir = self.dir or Dir.make_unique_dir()
            filename = message.get_filename() or 'mail.%s' % content_subtype
            file_dir = os.path.join(self.dir, filename)
            try:
                with open(file_dir, 'wb') as f:
                    f.write(decoded_payload)
            except IOError:
                sys.stderr.write('Cannot open %s\n' % file_dir)
                return ''
            return '%s saved' % file_dir

        return decoded_payload.decode(charset)
Exemplo n.º 5
0
 def __init__(self, message, attachments=False, messages=False):
     """
     :type message: bytes
     """
     self.raw = message
     self.message = email.message_from_bytes(self.raw)
     self.attachments = attachments
     self.dir = None
     if messages:
         self.dir = Dir.make_unique_dir()
         self.message_to_file()
Exemplo n.º 6
0
 def __init__(self, message, attachments=False, messages=False):
     """
     :type message: bytes
     """
     self.raw = message
     self.message = email.message_from_bytes(self.raw)
     self.attachments = attachments
     self.dir = None
     if messages:
         self.dir = Dir.make_unique_dir()
         self.message_to_file()
Exemplo n.º 7
0
 def save_all_photos(self):
     gabp = GetAllBlogPages(self.url)
     while self.i < len(gabp.get_all_pages()):
         print('====================正在保存第', self.i + 1,
               '页=============================')
         page_url = gabp.get_all_pages()[self.i]
         opbl = OnePageBlogLink(page_url)
         blog_page_urls = opbl.get_blog_page_urls()
         # 保存一个页面上的所有blog链接到的图片
         for blog_page_url_num in range(0, len(blog_page_urls)):
             Dir().ch_dir(self.path)
             Dir().make_dir(
                 opbl.get_blog_page_contents()[1][blog_page_url_num][0])
             new_path = os.path.join(
                 self.path,
                 opbl.get_blog_page_contents()[1][blog_page_url_num][0])
             Dir().ch_dir(new_path)
             photo_urls = gbpl(
                 blog_page_urls[blog_page_url_num]).get_photo_urls()
             sp().save_one_page_photos(photo_urls)
         self.i += 1
Exemplo n.º 8
0
 def __init__(self):
     self.closed = False
     self.command = str()
     self.args = defaultdict(list)
     self.command_history = list()
     self.valid_commands = {}
     self.valid_commands["init"] = Init()
     self.valid_commands["push"] = Push()
     self.valid_commands["pull"] = Pull()
     self.valid_commands["config"] = Config()
     self.valid_commands["dir"] = Dir()
     self.valid_commands["purgue"] = Purgue()
Exemplo n.º 9
0
def check_empty(dirobj, dirid, delete_sql):
    empty = True

    #look for file records to delete
    c.execute(
        'select id, name from files where parentid = ? and size is not null and size > 1',
        (dirid, ))
    filerows = c.fetchall()
    for filerow in filerows:
        fileid = filerow[0]
        #build path
        filepath = dirobj.path + filerow[1]
        #if file exists
        if (not os.path.exists(filepath)):
            #append delete file sql
            print('file missing', fileid, filepath)
            delete_sql.append('delete from files where id = ' + str(fileid))
        else:
            empty = False

    #look for frame records to delete
    c.execute('select id, name from frame where parentid = ?', (dirid, ))
    framerows = c.fetchall()
    for framerow in framerows:
        frameid = framerow[0]
        #build path
        framepath = dirobj.path + framerow[1]
        #if frame exists
        if (not os.path.exists(framepath)):
            print('frame missing', frameid, framepath)
            #append delete frame sql
            delete_sql.append('delete from frame where id = ' + str(frameid))
        else:
            empty = False

    #look for empty subdirs
    c.execute('select id, name from directory where parent = ?', (dirid, ))
    subdirrows = c.fetchall()
    for subdirrow in subdirrows:
        subdirid = subdirrow[0]
        subdirobj = Dir(dirobj.path + subdirrow[1])

        if (not check_empty(subdirobj, subdirid, delete_sql)):
            empty = False

    if (empty):
        if (not os.path.exists(dirobj.path)):
            print('dir missing', dirid, dirobj.path)
        else:
            print('dir unused', dirid, dirobj.path)
        delete_sql.append('delete from directory where id = ' + str(dirid))

    return empty
Exemplo n.º 10
0
def get_un_use_code_files(a_project_path, a_zh_un_check_enable):
    c__dir = Dir(a_project_path)
    c_files = c__dir.files()
    h_files = []
    check_files = []
    for c_file in c_files:
        match = False
        if a_zh_un_check_enable:
            match = zhPattern.search(unicode(c_file.name))
        not_system_file = ('xcodeproj'
                           not in c_file.name) and ('xcworkspace'
                                                    not in c_file.name)
        not_node_module = 'node_modules' not in c_file.path
        if 'Pod' not in c_file.path and (
                not match) and not_system_file and not_node_module:
            is_png = 'png' == c_file.get_extension()
            is_jpg = 'jpg' == c_file.get_extension()
            if not (is_jpg or is_png):
                check_files.append(c_file)
                # 过滤pod
                if 'h' == c_file.get_extension():
                    h_files.append(c_file)

    i = 0
    progress_index = 0
    total = len(h_files)
    print("Total \'.h\' Files Count:%d" % total)
    while i < len(h_files):
        progress_index += 1
        progress.show_progress(progress_index, total)

        h_file = h_files[i]
        contain = has_code_file_contain(h_file, check_files)
        if contain:
            i -= 1
            h_files.remove(h_file)

        i += 1
    return h_files
Exemplo n.º 11
0
def get_dir_from_id(dirid):
    dirobj = None
    #recursive cte to fetch all parent dirs
    #print('recursing with:', dirid)
    c.execute(
        'with parents(id, name, parent) as (select par.id, par.name, par.parent from directory par where par.id = ? union all select child.id, child.name, child.parent from directory child inner join parents par on par.parent = child.id) select id, name from parents',
        (dirid, ))
    rows = c.fetchall()
    if (len(rows) > 0):
        dirpath = ''
        for r in rows:
            #print('row', r, r[1])
            dirpath = str(r[1]) + os.sep + dirpath
        dirpath = os.sep + 'media' + os.sep + dirpath
        #print(dirpath)
        dirobj = Dir(dirpath)

    return dirobj
Exemplo n.º 12
0
class TypescriptHost(object):
    def __init__(self, vim):
        self.vim = vim
        self._client = Client(debug_fn=self.log, log_fn=self.log)
        self.files = Dir()
        self._last_input_reload = time()
        self.cwd = os.getcwd()

    def relative_file(self):
        """
            Return the current file
        """
        return self.vim.current.buffer.name

    def reload(self):
        """
            Call tsserver.reload()

        """
        filename = self.relative_file()
        contents = self.vim.eval("join(getline(1,'$'), \"\n\")")
        tmpfile = NamedTemporaryFile(delete=False)
        tmpfile.write(contents.encode("utf-8"))
        tmpfile.close()

        try:
            self._client.reload(filename, tmpfile.name)
        except:
            pass
        os.unlink(tmpfile.name)

    @neovim.function("TSFindConfig", sync=True)
    def findconfig(self, args):
        files = self.files.files()
        m = re.compile(r'(ts|js)config.json$')
        for file in files:
            if m.search(file):
                return True

    def writeFile(self):
        jsSupport = self.vim.eval('g:nvim_typescript#javascript_support')
        if bool(jsSupport):
            input = self.vim.call(
                'input',
                'nvim-ts: config is not present, create one [yes|no]? ')
            if input == "yes":
                with open('jsconfig.json', 'w') as config:
                    json.dump(defaultArgs,
                              config,
                              indent=2,
                              separators=(',', ': '))
                    config.close()
                    self.vim.command('redraws')
                    self.vim.out_write(
                        'nvim-ts: js support was enable, but no config is present, writting defualt jsconfig.json \n'
                    )
                    self.tsstart()
            else:
                self.vim.command('redraws')
                self.vim.out_write('TSServer not started.')

    @neovim.command("TSStop")
    def tsstop(self):
        """
            Stop the client
        """
        if self._client.server_handle is not None:
            self._client.stop()
            self.vim.out_write('TS: Server Stopped \n')

    @neovim.command("TSStart")
    def tsstart(self):
        """
            Stat the client
        """
        if self._client.server_handle is None:
            self._client.serverPath = self.vim.vars[
                "nvim_typescript#server_path"]
            if self._client.start():
                self._client.open(self.relative_file())
                self.vim.out_write('TS: Server Started \n')

    @neovim.command("TSRestart")
    def tsrestart(self):
        """
            Restart the Client
        """
        self.tsstop()
        self.tsstart()

        # self._client.open(self.relative_file())

    @neovim.command("TSReloadProject")
    def reloadProject(self):
        self._client.refresh()

    @neovim.command("TSDoc")
    def tsdoc(self):
        """
            Get the doc strings and type info
        """
        if self._client.server_handle is not None:
            self.reload()
            file = self.vim.current.buffer.name
            line = self.vim.current.window.cursor[0]
            offset = self.vim.current.window.cursor[1] + 2
            info = self._client.getDoc(file, line, offset)

            if (not info) or (not info['success']):
                self.vim.command(
                    'echohl WarningMsg | echo "TS: No doc at cursor" | echohl None'
                )
            else:
                displayString = '{0}'.format(info['body']['displayString'])
                documentation = '{0}'.format(info['body']['documentation'])
                documentation = documentation.split('\n')
                displayString = displayString.split('\n')
                message = displayString + documentation
                buf = self.vim.eval("bufnr('__doc__')")
                if buf > 0:
                    wi = self.vim.eval("index(tabpagebuflist(tabpagenr())," +
                                       str(buf) + ")")
                    if wi >= 0:
                        self.vim.command(str(wi + 1) + 'wincmd w')
                    else:
                        self.vim.command('sbuffer ' + str(buf))
                else:
                    self.vim.command("split __doc__")

                for setting in [
                        "setlocal modifiable", "setlocal noswapfile",
                        "setlocal nonumber", "setlocal buftype=nofile"
                ]:
                    self.vim.command(setting)
                self.vim.command('sil normal! ggdG')
                self.vim.command('resize 10')
                self.vim.current.buffer.append(message, 0)
                self.vim.command("setlocal nomodifiable")
                self.vim.command('sil normal! gg')
        else:
            self.vim.command(
                'echohl WarningMsg | echo "TS: Server is not Running" | echohl None'
            )

    @neovim.command("TSDef")
    def tsdef(self):
        """
            Get the definition
        """
        if self._client.server_handle is not None:
            self.reload()
            file = self.vim.current.buffer.name
            line = self.vim.current.window.cursor[0]
            offset = self.vim.current.window.cursor[1] + 2
            info = self._client.goToDefinition(file, line, offset)
            if (not info) or (not info['success']):
                self.vim.command(
                    'echohl WarningMsg | echo "TS: No definition" | echohl None'
                )
            else:
                defFile = info['body'][0]['file']
                defLine = '{0}'.format(info['body'][0]['start']['line'])

                self.vim.command('e +' + defLine + ' ' + defFile)
        else:
            self.vim.command(
                'echohl WarningMsg | echo "TS: Server is not Running" | echohl None'
            )

    @neovim.command("TSDefPreview")
    def tsdefpreview(self):
        """
            Get the definition
        """
        if self._client.server_handle is not None:
            self.reload()
            file = self.vim.current.buffer.name
            line = self.vim.current.window.cursor[0]
            offset = self.vim.current.window.cursor[1] + 2
            info = self._client.goToDefinition(file, line, offset)
            if (not info) or (not info['success']):
                self.vim.command(
                    'echohl WarningMsg | echo "TS: No definition" | echohl None'
                )
            else:
                defFile = info['body'][0]['file']
                defLine = '{0}'.format(info['body'][0]['start']['line'])

                self.vim.command('split! +' + defLine + ' ' + defFile)
        else:
            self.vim.command(
                'echohl WarningMsg | echo "TS: Server is not Running" | echohl None'
            )

    @neovim.command("TSType")
    def tstype(self):
        """
            Get the type info
        """
        if self._client.server_handle is not None:
            self.reload()
            file = self.vim.current.buffer.name
            line = self.vim.current.window.cursor[0]
            offset = self.vim.current.window.cursor[1] + 2

            info = self._client.getDoc(file, line, offset)
            if (not info) or (not info['success']):
                pass
            else:
                message = '{0}'.format(info['body']['displayString'])
                message = re.sub("\s+", " ", message)
                self.vim.command('redraws!')
                self.vim.out_write(message + '\n')
        else:
            self.vim.command(
                'echohl WarningMsg | echo "TS: Server is not Running" | echohl None'
            )

    @neovim.command("TSGetErr")
    def tsgeterr(self):
        """
            Get the type info
        """
        if self._client.server_handle is not None:
            self.reload()
            files = [self.relative_file()]
            getErrRes = self._client.getErr(files)
            if not getErrRes:
                pass
            else:
                errorLoc = []
                filename = getErrRes['body']['file']
                errorList = getErrRes['body']['diagnostics']

                if len(errorList) > -1:
                    for error in errorList:
                        errorLoc.append({
                            'filename':
                            re.sub(self.cwd + '/', '', filename),
                            'lnum':
                            error['start']['line'],
                            'col':
                            error['start']['offset'],
                            'text':
                            error['text']
                        })
                    self.vim.call('setloclist', 0, errorLoc, 'r', 'Errors')
                    self.vim.command('lwindow')
        else:
            self.printError('Server is not Running')

    # REQUEST NAVTREE/DOC SYMBOLS
    @neovim.function("TSGetDocSymbolsFunc", sync=True)
    def getDocSymbolsFunc(self, args=None):
        return self._client.getDocumentSymbols(self.relative_file())

    # Display Doc symbols in loclist
    @neovim.command("TSGetDocSymbols")
    def tsgetdocsymbols(self):
        if self._client.server_handle is not None:
            self.reload()
            docSysmbols = self.getDocSymbolsFunc()
            if not docSysmbols:
                pass
            else:
                docSysmbolsLoc = []
                symbolList = docSysmbols['body']['childItems']
                filename = re.sub(self.cwd + '/', '', self.relative_file())
                if len(symbolList) > -1:
                    for symbol in symbolList:
                        docSysmbolsLoc.append({
                            'filename':
                            filename,
                            'lnum':
                            symbol['spans'][0]['start']['line'],
                            'col':
                            symbol['spans'][0]['start']['offset'],
                            'text':
                            symbol['text']
                        })

                    if 'childItems' in symbol and len(
                            symbol['childItems']) > 0:
                        for childSymbol in symbol['childItems']:
                            docSysmbolsLoc.append({
                                'filename':
                                filename,
                                'lnum':
                                childSymbol['spans'][0]['start']['line'],
                                'col':
                                childSymbol['spans'][0]['start']['offset'],
                                'text':
                                childSymbol['text']
                            })
                    self.vim.call('setloclist', 0, docSysmbolsLoc, 'r',
                                  'Symbols')
                    self.vim.command('lwindow')
        else:
            self.printError('Server is not running')

    # REQUEST NAVTo/Workplace symbols
    # @neovim.function("TSGetWorkplaceSymbolsFunc", sync=True)
    # def getWorkplaceSymbolsFunc(self, args=None):
    #     return self._client.getWorkplaceSymbols(self.relative_file(), args[0])

    # Display Doc symbols in loclist
    # @neovim.command("TSGetDocSymbols")
    # def tsgetdocsymbols(self):
    #     if self._client.server_handle is not None:
    #         self.reload()
    #         docSysmbols = self.getDocSymbolsFunc()
    #         if not docSysmbols:
    #             pass
    #         else:
    #             docSysmbolsLoc = []
    #             symbolList = docSysmbols['body']['childItems']
    #             filename = re.sub(self.cwd + '/', '', self.relative_file())
    #             if len(symbolList) > -1:
    #                 for symbol in symbolList:
    #                     docSysmbolsLoc.append({
    #                         'filename': filename,
    #                         'lnum': symbol['spans'][0]['start']['line'],
    #                         'col':  symbol['spans'][0]['start']['offset'],
    #                         'text': symbol['text']
    #                     })
    #
    #                 if 'childItems' in symbol and len(symbol['childItems']) > 0:
    #                     for childSymbol in symbol['childItems']:
    #                         docSysmbolsLoc.append({
    #                             'filename': filename,
    #                             'lnum': childSymbol['spans'][0]['start']['line'],
    #                             'col':  childSymbol['spans'][0]['start']['offset'],
    #                             'text': childSymbol['text']
    #                         })
    #                 self.vim.call('setloclist', 0,
    #                               docSysmbolsLoc, 'r', 'Symbols')
    #                 self.vim.command('lwindow')
    #     else:
    #         self.printError('Server is not running')

    @neovim.command("TSSig")
    def tssig(self):
        """
            Get the type info
        """
        if self._client.server_handle is not None:
            self.reload()
            file = self.vim.current.buffer.name
            line = self.vim.current.window.cursor[0]
            offset = self.vim.current.window.cursor[1]
            info = self._client.getDoc(file, line, offset)
            if (not info) or (info['success'] is False):
                pass
            else:
                message = '{0}'.format(info['body']['displayString'])
                message = re.sub("\s+", " ", message)
                if 'method' in info['body']['kind']:
                    self.vim.command(
                        'redraws! | echom "nvim-ts: " | echohl Function | echon \"'
                        + message + '\" | echohl None')
                else:
                    pass
        else:
            self.printError('Server is not running')

    @neovim.command("TSRefs")
    def tsrefs(self):
        """
            Get the type info
        """

        if self._client.server_handle is not None:
            self.reload()
            file = self.vim.current.buffer.name
            line = self.vim.current.window.cursor[0]
            offset = self.vim.current.window.cursor[1] + 2

            refs = self._client.getRef(file, line, offset)

            if (not refs) or (refs['success'] is False):
                pass
            else:
                truncateAfter = self.vim.eval(
                    'g:nvim_typescript#loc_list_item_truncate_after')
                location_list = []
                refList = refs["body"]["refs"]
                if len(refList) > -1:
                    for ref in refList:
                        lineText = re.sub('^\s+', '', ref['lineText'])
                        if (truncateAfter
                                == -1) or (len(lineText) <= truncateAfter):
                            lineText
                        else:
                            lineText = (lineText[:truncateAfter] + '...')
                        location_list.append({
                            'filename':
                            re.sub(self.cwd + '/', '', ref['file']),
                            'lnum':
                            ref['start']['line'],
                            'col':
                            ref['start']['offset'],
                            'text':
                            lineText
                        })
                    self.vim.call('setloclist', 0, location_list, 'r',
                                  'References')
                    self.vim.command('lwindow')
                else:
                    self.printError('References not found')
        else:
            self.printError('Server is not Running')

    @neovim.function('TSGetServerPath')
    def tstest(self, args):
        """
        Get the path of the tsserver
        """
        self.vim.out_write(self._client.serverPath + '\n')

    @neovim.function('TSOnBufEnter')
    def on_bufenter(self, args=None):
        """
           Send open event when a ts file is open
        """
        if self.findconfig(None):
            if self._client.server_handle is None:
                self.tsstart()
            else:
                self._client.open(self.relative_file())
        else:
            self.writeFile()

    @neovim.function('TSOnBufSave')
    def on_bufwritepost(self, args=None):
        """
           On save, reload to detect changes
        """
        self.reload()

    # @neovim.function('TSComplete', sync=True)
    # def tsomnifunc(self, args):
    #     line_str = self.vim.current.line
    #     line = self.vim.current.window.cursor[0]
    #     offset = self.vim.current.window.cursor[1]
    #     if args[0]:
    #         while offset > 0 and re.match(r"([a-zA-Z])", line_str[offset - 1]):
    #             offset -= 1
    #         return offset
    #     else:
    #         if self._client.server_handle is not None:
    #             if time() - self._last_input_reload > RELOAD_INTERVAL or re.search(r"\w*\.", args[1]):
    #                 self._last_input_reload = time()
    #                 self.reload()
    #             data = self._client.completions(
    #                 self.relative_file(), line, offset + 1, args[1])
    #
    #             if len(data) == 0:
    #                 return []
    #
    #             if len(data) > self.vim.vars["nvim_typescript#max_completion_detail"]:
    #                 filtered = []
    #                 for entry in data:
    #                     if entry["kind"] != "warning":
    #                         filtered.append(entry)
    #                 return [self._convert_completion_data(e) for e in filtered]
    #
    #             names = []
    #             maxNameLength = 0
    #
    #             for entry in data:
    #                 if (entry["kind"] != "warning"):
    #                     names.append(entry["name"])
    #                     maxNameLength = max(maxNameLength, len(entry["name"]))
    #             detailed_data = self._client.completion_entry_details(
    #                 self.relative_file(), line, offset + 1, names)
    #             if len(detailed_data) == 0:
    #                 return []
    #
    #             return [self._convert_detailed_completion_data(e, padding=maxNameLength) for e in detailed_data]
    # def _convert_completion_data(self, entry):
    #     return {
    #         "word": entry["name"],
    #         "kind": entry["kind"]
    #     }
    # def _convert_detailed_completion_data(self, entry, padding=80):
    #     name = entry["name"]
    #     display_parts = entry["displayParts"]
    #     signature = "".join([p["text"] for p in display_parts])
    #
    #     # needed to strip new lines and indentation from the signature
    #     signature = re.sub("\s+", " ", signature)
    #     menu_text = re.sub(
    #         "^(var|let|const|class|\(method\)|\(property\)|enum|namespace|function|import|interface|type)\s+", "", signature)
    #     documentation = menu_text
    #
    #     if "documentation" in entry and entry["documentation"]:
    #         documentation += "\n" + \
    #             "".join([d["text"] for d in entry["documentation"]])
    #
    #     kind = entry["kind"][0].title()
    #
    #     return ({
    #         "word": name,
    #         "kind": kind,
    #         "menu": 'TS ' + menu_text,
    #         "info": documentation
    #     })

    def printError(self, message):
        self.vim.err_write(message + '\n')
        # self.vim.command(
        #     'echohl WarningMsg | echo "TS: ' + messagee + '" | echohl None')

    def log(self, message):
        """
        Log message to vim echo
        """
        val = "{}".format(message)
        # self.vim.command('redraws!')
        self.vim.out_write(val + '\n')
Exemplo n.º 13
0
def get_un_use_images(a_project_path,
                      a_zh_un_check_enable,
                      image_analyse_check_as_line=False):
    c__dir = Dir(a_project_path)
    c_files = c__dir.files()
    img_files = []
    check_files = []
    for c_file in c_files:
        match = False
        if a_zh_un_check_enable:
            match = zhPattern.search(unicode(c_file.name))
        not_system_file = ('xcodeproj'
                           not in c_file.name) and ('xcworkspace'
                                                    not in c_file.name)
        not_node_module = 'node_modules' not in c_file.path
        if 'Pod' not in c_file.path and (
                not match) and not_system_file and not_node_module:
            is_png = 'png' == c_file.get_extension()
            is_jpg = 'jpg' == c_file.get_extension()
            if is_png or is_jpg:
                is_app_icon = 'AppIcon' in c_file.path
                is_launch = 'LaunchImage' in c_file.path
                if not (is_app_icon or is_launch):
                    img_files.append(c_file)
            else:
                check_files.append(c_file)

    i = 0
    progress_index = 0
    count = len(img_files)
    print("Total Image Files Count: %d" % len(check_files))
    while i < len(img_files):
        progress_index += 1
        progress.show_progress(progress_index, count)

        # 逐文件排查
        img_file = img_files[i]
        contain = False
        if not isinstance(img_file, File):
            contain = True
        else:
            image_name = img_file.name.partition('.')[0]
            if "@2x" in image_name or "@3x" in image_name:
                image_name = image_name.partition('@')[0]

            for check_file in check_files:
                if 'js' == check_file.get_extension():
                    simple_contain_str = img_file.name
                    if "@2x" in simple_contain_str:
                        simple_contain_str = simple_contain_str.replace(
                            "@2x", "")
                    if "@3x" in simple_contain_str:
                        simple_contain_str = simple_contain_str.replace(
                            "@3x", "")
                    contain = check_file.has_contain(
                        simple_contain_str, image_analyse_check_as_line)
                    if contain:
                        break

                # Json 内部查找,并且过滤到 .xcassets 内的 Content.json 的配置文件
                if 'json' in check_file.name and 'Content' not in check_file.name:
                    # 查找 json 串 "image_name"
                    simple_contain_str = "\"" + image_name + "\""
                    contain = check_file.has_contain(
                        simple_contain_str, image_analyse_check_as_line)
                    if contain:
                        break

                    # 查找json 串:\"image_name\"
                    simple_contain_str = "\\\"" + image_name + "\\\""
                    contain = check_file.has_contain(
                        simple_contain_str, image_analyse_check_as_line)
                    if contain:
                        break
                else:
                    # 查找 @"image_name"
                    contain_str = "@\"" + image_name + "\""
                    contain = check_file.has_contain(
                        contain_str, image_analyse_check_as_line)
                    if contain:
                        break
        if contain:
            img_files.remove(img_file)
        else:
            i += 1

    return img_files
Exemplo n.º 14
0
def process_dir(dirobj, parentid):
    print(indent(dirobj.depth, ' ') + '/' + dirobj.name)

    log = {
        'name': dirobj.name,
        'files': [],
        'dirs': [],
        'warnings': [],
        'errors': []
    }

    if (not os.path.exists(dirobj.path)):
        log['errors'].append('dir must exist')
        return log

    if (dirobj.parent == None):
        log['errors'].append('dir must have parent')
        return log

    #conditionally process mask dir
    if (is_mask_dir(dirobj)):
        return process_mask_dir(dirobj)

    if (parentid == None and dirobj.parent.name != MOUNT_ROOT):
        parentid = get_parent_id(dirobj)
        if (parentid == None):
            log['errors'].append('dir must have parent id')
            return log

    log['parentid'] = parentid

    dirid = get_dir_id(dirobj.name, parentid)

    #if no dirid then create dir
    if (dirid == None):
        log['db'] = 'INSERT'
        c.execute('insert into directory (parent, name) values (?, ?)',
                  (parentid, dirobj.name))
        dirid = c.lastrowid

    log['id'] = dirid

    #process frames or files first
    if (dirobj.parent.name == 'frames' or dirobj.parent.name == 'thumbs'):
        process_frames(dirobj, dirid, log)
    else:
        log['files'] = process_files(dirobj, dirid)

    subdirnames = []
    for subdirname in os.listdir(dirobj.path):
        if (os.path.isdir(dirobj.path + subdirname)
                and not subdirname in EXCLUDED_DIRS):
            subdirnames.append(subdirname)

    subdirnames = sorted(subdirnames,
                         key=lambda s: s.lower().translate(STRIP_PUNC))

    #process subdirs
    for subdirname in subdirnames:
        subdir = Dir(dirobj.path + subdirname)
        logsubdir = process_dir(subdir, dirid)
        log['dirs'].append(logsubdir)

    return log
Exemplo n.º 15
0
                        help="skip frame processing if frame dir exists",
                        action="store_true")
    parser.add_argument(
        '-d',
        '--delete_sql',
        help=
        "look for empty dirs and generate delete sql (not compatible with -n)",
        action="store_true")
    parser.add_argument('-c',
                        '--copy_log',
                        help="copy log to logviewer",
                        action="store_true")
    args = parser.parse_args()

    try:
        startdirobj = Dir(args.startdir)
    except IndexError:
        sys.exit('Not a valid directory name (must start with a /)')

    print('startdir =', startdirobj.path)
    print('startdepth =', startdirobj.depth)

    conn = sqlite3.connect(SQLITE3_DB_PATH)
    c = conn.cursor()

    if (args.startparentid != None):
        startparentid = args.startparentid
    else:
        startparentid = get_parent_id(startdirobj)

    print('startparentid =', startparentid)
Exemplo n.º 16
0
class TypescriptHost(object):
    def __init__(self, vim):
        self.vim = vim
        self._client = Client(debug_fn=self.log, log_fn=self.log)
        self.files = Dir()
        self._last_input_reload = time()
        self.cwd = os.getcwd()

    def relative_file(self):
        """
        Return the current file
        If the currently focused buffer is not a proper buffer
        (eg. location list window or quickfix window) `self.vim.current.buffer.name`
        returns a None value.
        In this case, do a best effort and return any buffer name.
        This is obviously not optimal, but for lack of a better solution...""
        """
        if not self.vim.current.buffer.name:
            if len(self.vim.buffers) > 0:
                # Vim buffer numbers are 1-indexed
                return self.vim.buffers[1].name
        else:
            return self.vim.current.buffer.name

    def reload(self):
        """
        Call tsserver.reload()
        """
        filename = self.relative_file()
        contents = self.vim.eval("join(getline(1,'$'), \"\n\")")
        tmpfile = NamedTemporaryFile(delete=False)
        tmpfile.write(contents.encode("utf-8"))
        tmpfile.close()

        try:
            self._client.reload(filename, tmpfile.name)
        except:
            pass
        os.unlink(tmpfile.name)

    @neovim.function("TSFindConfig", sync=True)
    def findconfig(self, args):
        files = self.files.files()
        m = re.compile(r'(ts|js)config.json$')
        for file in files:
            if m.search(file):
                return True

    def writeFile(self):
        jsSupport = self.vim.eval('g:nvim_typescript#javascript_support')
        if bool(jsSupport):
            input = self.vim.call(
                'input',
                'nvim-ts: config is not present, create one [yes|no]? ')
            if input == "yes":
                with open('jsconfig.json', 'w') as config:
                    json.dump(defaultArgs,
                              config,
                              indent=2,
                              separators=(',', ': '))
                    config.close()
                    self.vim.command('redraws')
                    self.vim.out_write(
                        'nvim-ts: js support was enable, but no config is present, writting defualt jsconfig.json \n'
                    )
                    self.tsstart()
            else:
                self.vim.command('redraws')
                self.printError('Server not started')

    @neovim.command("TSStop")
    def tsstop(self):
        """
        Stop the client
        """
        if self._client.server_handle is not None:
            self.printMsg('Server Stopped')

    @neovim.command("TSStart")
    def tsstart(self):
        """
        Stat the client
        """
        if self._client.server_handle is None:
            self._client.serverPath = self.vim.vars[
                "nvim_typescript#server_path"]
            if self._client.start():
                self._client.open(self.relative_file())
                self.printMsg('Server Started')

    @neovim.command("TSRestart")
    def tsrestart(self):
        """
            Restart the Client
        """
        self.tsstop()
        self.tsstart()

        # self._client.open(self.relative_file())

    @neovim.command("TSReloadProject")
    def reloadProject(self):
        self._client.refresh()

    @neovim.command("TSDoc")
    def tsdoc(self):
        """
        Get the doc strings and type info
        """
        if self._client.server_handle is not None:
            self.reload()
            file = self.vim.current.buffer.name
            line = self.vim.current.window.cursor[0]
            offset = self.vim.current.window.cursor[1] + 2
            info = self._client.getDoc(file, line, offset)

            if info:
                displayString = '{0}'.format(info['displayString'])
                documentation = '{0}'.format(info['documentation'])
                documentation = documentation.split('\n')
                displayString = displayString.split('\n')
                message = displayString + documentation
                buf = self.vim.eval("bufnr('__doc__')")
                if buf > 0:
                    wi = self.vim.eval("index(tabpagebuflist(tabpagenr())," +
                                       str(buf) + ")")
                    if wi >= 0:
                        self.vim.command(str(wi + 1) + 'wincmd w')
                    else:
                        self.vim.command('sbuffer ' + str(buf))
                else:
                    self.vim.command("split __doc__")

                for setting in [
                        "setlocal modifiable", "setlocal noswapfile",
                        "setlocal nonumber", "setlocal buftype=nofile"
                ]:
                    self.vim.command(setting)
                self.vim.command('sil normal! ggdG')
                self.vim.command('resize 10')
                self.vim.current.buffer.append(message, 0)
                self.vim.command("setlocal nomodifiable")
                self.vim.command('sil normal! gg')
        else:
            self.printError('Server is not running')

    @neovim.command("TSDef")
    def tsdef(self):
        """
        Get the definition
        """
        if self._client.server_handle is not None:
            self.reload()
            file = self.vim.current.buffer.name
            line = self.vim.current.window.cursor[0]
            offset = self.vim.current.window.cursor[1] + 2
            info = self._client.goToDefinition(file, line, offset)
            if info:
                defFile = info[0]['file']
                defLine = '{0}'.format(info[0]['start']['line'])
                self.vim.command('e +' + defLine + ' ' + defFile)
            else:
                self.printError('No definition')
        else:
            self.printError('Server is not running')

    @neovim.command("TSDefPreview")
    def tsdefpreview(self):
        """
            Get the definition
        """
        if self._client.server_handle is not None:
            self.reload()
            file = self.vim.current.buffer.name
            line = self.vim.current.window.cursor[0]
            offset = self.vim.current.window.cursor[1] + 2
            info = self._client.goToDefinition(file, line, offset)
            if info:
                defFile = info[0]['file']
                defLine = '{0}'.format(info[0]['start']['line'])
                self.vim.command('split! +' + defLine + ' ' + defFile)
            else:
                self.printError('No definition')
        else:
            self.vim.command(
                'echohl WarningMsg | echo "TS: Server is not Running" | echohl None'
            )

    @neovim.command("TSType")
    def tstype(self):
        """
        Get the type info
        """
        if self._client.server_handle is not None:
            self.reload()
            file = self.vim.current.buffer.name
            line = self.vim.current.window.cursor[0]
            offset = self.vim.current.window.cursor[1] + 2
            info = self._client.getDoc(file, line, offset)

            if info:
                message = '{0}'.format(info['displayString'])
                message = re.sub("\s+", " ", message)
                self.vim.out_write("{} \n".format(message))
        else:
            self.printError('Server is not running')

    @neovim.command("TSGetErr")
    def tsgeterr(self):
        """
        Get the type info
        """
        if self._client.server_handle is not None:
            self.reload()
            files = [self.relative_file()]
            getErrRes = self._client.getErr(files)
            if getErrRes:
                filename = getErrRes['file']
                errorList = getErrRes['diagnostics']
                if len(errorList) > -1:
                    errorLoc = list(
                        map(
                            lambda error: {
                                'filename': re.sub(self.cwd + '/', '', filename
                                                   ),
                                'lnum': error['start']['line'],
                                'col': error['start']['offset'],
                                'text': error['text']
                            }, errorList))
                    self.vim.call('setloclist', 0, errorLoc, 'r', 'Errors')
                    self.vim.command('lwindow')
        else:
            self.printError('Server is not Running')

    @neovim.command("TSRename", nargs="*")
    def tsrename(self, args=""):
        """
        Rename the current symbol
        """
        symbol = self.vim.eval('expand("<cword>")')
        if not args:
            newName = self.vim.call('input',
                                    'nvim-ts: rename {0} to '.format(symbol))
        else:
            newName = args[0]

        if self._client.server_handle is not None:
            self.reload()
            file = self.vim.current.buffer.name
            originalLine = self.vim.current.window.cursor[0]
            offset = self.vim.current.window.cursor[1] + 2
            renameRes = self._client.renameSymbol(file, originalLine, offset)

            if (renameRes) and (renameRes['info']['canRename']):
                locs = renameRes['locs']
                changeCount = 0
                for loc in locs:
                    defFile = loc['file']

                    self.vim.command('e ' + defFile)

                    for rename in loc['locs']:
                        line = rename['start']['line']
                        col = rename['start']['offset']
                        self.vim.command('cal cursor({}, {})'.format(
                            line, col))
                        self.vim.command('normal cw{}'.format(newName))
                        self.vim.command('write')
                        changeCount += 1

                self.vim.command('e ' + file)
                self.vim.command('cal cursor({}, {})'.format(
                    originalLine, offset))
                self.vim.out_write(
                    'Replaced {} occurences in {} files \n'.format(
                        len(locs), changeCount))
            else:
                self.printError(renameRes['info']['localizedErrorMessage'])

    @neovim.command("TSImport")
    def tsimport(self):
        symbol = self.vim.call('expand', '<cword>')
        currentlyImportedItems, lastImportLine = utils.getCurrentImports(
            self._client, self.relative_file())
        if symbol in currentlyImportedItems:
            self.vim.out_write("nvim-ts: %s is already imported\n" % symbol)
            return

        results = utils.getImportCandidates(self._client, self.relative_file(),
                                            symbol)
        if len(results) == 0:
            self.vim.out_write('nvim-ts: No import candidates were found.\n')
            return

        if len(results) == 1:
            importBlock = utils.createImportBlock(
                symbol,
                utils.getRelativeImportPath(self.relative_file(), results[0]),
                self.vim.vars["nvim_typescript#tsimport#template"])
        else:
            candidates = "\n".join([
                "[%s]: %s" % (ix, result) for ix, result in enumerate(results)
            ])
            input = self.vim.call(
                'input',
                'nvim-ts: More than 1 candidate found, Select from the following options:\n%s\n please choose one: '
                % candidates,
                '',
            )
            importBlock = utils.createImportBlock(
                symbol,
                utils.getRelativeImportPath(self.relative_file(),
                                            results[int(input)]),
                self.vim.vars["nvim_typescript#tsimport#template"])

        self.vim.current.buffer.append(importBlock, lastImportLine)

    # REQUEST NAVTREE/DOC SYMBOLS
    @neovim.function("TSGetDocSymbolsFunc", sync=True)
    def getDocSymbolsFunc(self, args=None):
        return self._client.getDocumentSymbols(self.relative_file())

    # Display Doc symbols in loclist
    @neovim.command("TSGetDocSymbols")
    def tsgetdocsymbols(self):
        if self._client.server_handle is not None:
            self.reload()
            docSysmbols = self._client.getDocumentSymbols(self.relative_file())
            if not docSysmbols:
                pass
            else:
                docSysmbolsLoc = []
                symbolList = docSysmbols['childItems']
                filename = re.sub(self.cwd + '/', '', self.relative_file())
                if len(symbolList) > -1:
                    for symbol in symbolList:
                        docSysmbolsLoc.append({
                            'filename':
                            filename,
                            'lnum':
                            symbol['spans'][0]['start']['line'],
                            'col':
                            symbol['spans'][0]['start']['offset'],
                            'text':
                            symbol['text']
                        })

                    if 'childItems' in symbol and len(
                            symbol['childItems']) > 0:
                        for childSymbol in symbol['childItems']:
                            docSysmbolsLoc.append({
                                'filename':
                                filename,
                                'lnum':
                                childSymbol['spans'][0]['start']['line'],
                                'col':
                                childSymbol['spans'][0]['start']['offset'],
                                'text':
                                childSymbol['text']
                            })
                    self.vim.call('setloclist', 0, docSysmbolsLoc, 'r',
                                  'Symbols')
                    self.vim.command('lwindow')
        else:
            self.printError('Server is not running')

    @neovim.function("TSGetWorkspaceSymbolsFunc", sync=True)
    def getWorkspaceSymbolsFunc(self, args=None):
        if self._client.server_handle is not None:
            searchSymbols = self._client.getWorkspaceSymbols(
                self.relative_file(), args[0])
            if not searchSymbols:
                return []
            else:
                symbolList = searchSymbols
                filename = re.sub(self.cwd + '/', '', self.relative_file())
                if len(symbolList) > -1:
                    return list(
                        map(
                            lambda symbol: {
                                'filename':
                                re.sub(self.cwd + '/', '', symbol['file']),
                                'lnum':
                                symbol['start']['line'],
                                'col':
                                symbol['start']['offset'],
                                'text':
                                '(' + symbol['kind'] + '): ' + symbol['name']
                            }, symbolList))
        else:
            self.printError('Server is not running')

    @neovim.command("TSSig")
    def tssig(self):
        """
        Get the type info
        """
        if self._client.server_handle is not None:
            self.reload()
            file = self.vim.current.buffer.name
            line = self.vim.current.window.cursor[0]
            offset = self.vim.current.window.cursor[1]
            info = self._client.getDoc(file, line, offset)
            if info:
                message = '{0}'.format(info['displayString'])
                message = re.sub("\s+", " ", message)
                if 'method' in info['kind']:
                    self.vim.command(
                        'redraws! | echom "nvim-ts: " | echohl Function | echon \"'
                        + message + '\" | echohl None')
        else:
            self.printError('Server is not running')

    @neovim.command("TSRefs")
    def tsrefs(self):
        """
        Get the type info
        """

        if self._client.server_handle is not None:
            self.reload()
            file = self.vim.current.buffer.name
            line = self.vim.current.window.cursor[0]
            offset = self.vim.current.window.cursor[1] + 2

            refs = self._client.getRef(file, line, offset)

            if refs:
                truncateAfter = self.vim.eval(
                    'g:nvim_typescript#loc_list_item_truncate_after')
                location_list = []
                refList = refs["refs"]
                if len(refList) > -1:
                    for ref in refList:
                        lineText = re.sub('^\s+', '', ref['lineText'])
                        if (truncateAfter
                                == -1) or (len(lineText) <= truncateAfter):
                            lineText
                        else:
                            lineText = (lineText[:truncateAfter] + '...')
                        location_list.append({
                            'filename':
                            re.sub(self.cwd + '/', '', ref['file']),
                            'lnum':
                            ref['start']['line'],
                            'col':
                            ref['start']['offset'],
                            'text':
                            lineText
                        })
                    self.vim.call('setloclist', 0, location_list, 'r',
                                  'References')
                    self.vim.command('lwindow')
                else:
                    self.printError('References not found')
        else:
            self.printError('Server is not Running')

    @neovim.function('TSGetServerPath')
    def tstest(self, args):
        """
        Get the path of the tsserver
        """
        self.vim.out_write(self._client.serverPath + '\n')

    @neovim.function('TSOnBufEnter')
    def on_bufenter(self, args=None):
        """
       Send open event when a ts file is open
        """
        if self.findconfig(None):
            if self._client.server_handle is None:
                self.tsstart()
            else:
                self._client.open(self.relative_file())
        else:
            self.writeFile()

    @neovim.function('TSOnBufSave')
    def on_bufwritepost(self, args=None):
        """
       On save, reload to detect changes
        """
        self.reload()

    def printError(self, message):
        self.vim.err_write('nvim-ts: {0}\n'.format(message))

    def printMsg(self, message):
        self.vim.command('redraws!')
        self.vim.out_write('nvim-ts: {0}\n'.format(message))

    def log(self, message):
        """
        Log message to vim echo
        """
        self.vim.out_write('{} \n'.format(message))
Exemplo n.º 17
0
 def __init__(self, vim):
     self.vim = vim
     self._client = Client(debug_fn=self.log, log_fn=self.log)
     self.files = Dir()
     self._last_input_reload = time()
     self.cwd = os.getcwd()
Exemplo n.º 18
0
from tkinter import *

from const import *
from dir import Dir
from display import Displays
from game import Game


game = Game ()
Dir.static_init ()


with game.brain.session.as_default ():
    window = Tk ()

    canvas = Canvas (window, bg = 'black', width = SIGHT_DIAMETER * SCALE, height = SIGHT_DIAMETER * SCALE)
    # canvas = Canvas (window, bg = 'black', width = WIDTH * SCALE, height = HEIGHT * SCALE)
    game.draw (canvas)
    canvas.grid (row = 0, column = 0)

    label_text = StringVar (value = 'Attempt:\nScore:')
    game.set_text (label_text)
    label = Label (window, fg = 'black', textvariable = label_text)
    label.grid (row = 1, column = 0)

    display_frame = Frame (window)
    display_frame.grid (row = 0, column = 1, rowspan = 2)
    game.displays = Displays (display_frame, game.brain)
    window.bind ('<KeyPress>', game.displays.key_press)