Skip to content

Commit

Permalink
support open all language files
Browse files Browse the repository at this point in the history
  • Loading branch information
absszero committed Oct 28, 2023
1 parent f01c48a commit 7e8ca68
Show file tree
Hide file tree
Showing 12 changed files with 214 additions and 37 deletions.
20 changes: 8 additions & 12 deletions lib/finder.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
from .middleware import Middleware
from .console import Console
from .router import Router
from .language import Language
from .setting import Setting


Expand Down Expand Up @@ -160,21 +161,16 @@ def lang_place(path, line, lines, selected):
compile(r"""trans_choice\([^'"]*(['"])([^'"]*)\1"""),
]

language = None
for pattern in lang_patterns:
matched = pattern.search(line) or pattern.search(lines)
if (matched and path == matched.group(2)):
split = path.split(':')
vendor = ''
# it's package trans
if (3 == len(split)):
vendor = '/vendor/' + split[0]
keys = split[-1].split('.')
path = 'lang' + vendor + '/' + keys[0] + '.php'
if (not matched or path != matched.group(2)):
continue

location = None
if (2 <= len(keys)):
location = find_pattern % (keys[1])
return Place(path, location)
if not language:
language = Language()
place = language.get_place(path)
return place

return False

Expand Down
62 changes: 62 additions & 0 deletions lib/language.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
import os
from . import workspace
from .logging import log
from .place import Place


routes = {}


class Language:
find_pattern = """(['"]{1})%s\\1\\s*=>"""
FILENAME = 'lang/%(vendor)s%(file)s.php'
LANG_FILENAME = '%(vendor)s%(lang)s/%(file)s.php'

def __init__(self):
self.base = None
self.langs = []

for folder in workspace.get_folders():
dirs = workspace.get_folder_path(folder, 'resources/lang/*')
if dirs:
self.base = os.path.dirname(dirs[0])
self.langs = []
for dir in dirs:
self.langs.append(os.path.basename(dir))
log('lang base', self.base)
log('langs', self.langs)
return

def get_place(self, path):
split = path.split(':')
vendor = ''
# it's package trans
if (3 == len(split)):
vendor = 'vendor/' + split[0] + '/'
keys = split[-1].split('.')
path = self.FILENAME % {'vendor': vendor, 'file': keys[0]}

uris = []
paths = []
for lang in self.langs:
lang_path = self.LANG_FILENAME % {
'vendor': vendor,
'lang': lang,
'file': keys[0],
}
paths.append('lang/' + lang_path)

uri = os.path.join(self.base, lang_path)
if workspace.is_file(uri):
uris.append(uri)

location = None
if (2 <= len(keys)):
location = self.find_pattern % (keys[1])

place = Place(path, location)
place.paths = paths
place.paths.sort()
place.uris = uris

return place
4 changes: 2 additions & 2 deletions lib/logging.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,14 +2,14 @@
import traceback


def debug(caption, *args):
def log(caption, *args):
if Setting().get('debug'):
print('[LG]' + caption + " :", *args)


def exception(caption, ex: Exception):
ex_traceback = ex.__traceback__
debug(caption, ''.join(traceback.format_exception(
log(caption, ''.join(traceback.format_exception(
ex.__class__,
ex,
ex_traceback
Expand Down
17 changes: 15 additions & 2 deletions lib/place.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,21 @@
class Place:
import json


class Place:
def __init__(self, path, location=None, uri=None):
self.path = path
self.location = location
self.is_controller = False
self.paths = []
self.uri = uri
self.paths = []
self.uris = []

def __str__(self):
return json.dumps({
"path": self.path,
"location": self.location,
"is_controller": self.is_controller,
"uri": self.uri,
"paths": self.paths,
"uris": self.uris
}, sort_keys=True, indent=2)
10 changes: 5 additions & 5 deletions lib/router.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
import subprocess
import json
from .setting import Setting
from .logging import debug, exception
from .logging import log, exception

routes = {}

Expand All @@ -23,13 +23,13 @@ def update(self, filepath=None):
'''
update routes if routes folder's files were changed
'''
debug('artisan', self.artisan)
debug('routes folder', self.dir)
log('artisan', self.artisan)
log('routes folder', self.dir)
if not self.artisan or not self.dir:
return

is_routes_changed = workspace.is_changed(self.dir, filepath)
debug('routes changed', is_routes_changed)
log('routes changed', is_routes_changed)
if not is_routes_changed:
return
workspace.set_unchange(self.dir)
Expand All @@ -45,7 +45,7 @@ def update(self, filepath=None):
'--json',
'--columns=name,action'
]
debug('args', args)
log('args', args)

try:
output = subprocess.check_output(args, stderr=subprocess.STDOUT)
Expand Down
33 changes: 28 additions & 5 deletions lib/workspace.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,13 @@
changes = {}


def is_file(base, filename=None):
fullpath = base
if filename:
fullpath = os.path.join([base, filename])
return os.path.isfile(fullpath)


def is_changed(folder_path, file_path=None):
'''
is the folder's files were changed
Expand Down Expand Up @@ -85,15 +92,31 @@ def get_folder_path(base, folder_name, recursion=True):
'''
get real path by folder name
'''
files = os.listdir(base)
if folder_name in files:
return os.path.join(base, folder_name)

star = None
folders = folder_name.split('/')
if '*' == folders[-1]:
star = folders.pop()
folder_path = '/'.join(folders)

full_folder_path = os.path.join(base, folder_path)
if os.path.isdir(full_folder_path):
if not star:
return full_folder_path

folders = []
for file in os.listdir(full_folder_path):
folder = os.path.join(full_folder_path, file)
if os.path.isdir(folder):
folders.append(folder)

return folders

if not recursion:
return

for file in files:
folder = os.path.join(base + '/' + file)
for file in os.listdir(base):
folder = os.path.join(base, file)
if not os.path.isdir(folder):
continue

Expand Down
48 changes: 44 additions & 4 deletions main.py
Original file line number Diff line number Diff line change
Expand Up @@ -62,6 +62,9 @@ def on_hover(self, view, point, hover_zone):

if place.paths:
content = '<br/>'.join(map(self.build_link, place.paths))
if place.uris:
content += '<br/><br/>' +\
self.build_link('Open all files above', 'A!!')

view.show_popup(
content,
Expand All @@ -71,11 +74,18 @@ def on_hover(self, view, point, hover_zone):
on_navigate=self.on_navigate
)

def build_link(self, path):
return '<a href="' + path + '">' + path + '</a>'
def build_link(self, path, href=None):
if not href:
href = path

return '<a href="' + href + '">' + path + '</a>'

def on_navigate(self, link):
global place

if link == 'A!!' and place.uris:
open_file_layouts(place.uris)
return
if place.paths and link in place.paths:
place.path = link
place.paths = []
Expand Down Expand Up @@ -113,10 +123,11 @@ def goto_place(place):
window = sublime.active_window()

if place.paths:
if place.uris:
place.paths.append('Open all files above')
window.show_quick_panel(
place.paths,
on_path_select,
placeholder="Select a component file"
on_path_select
)
return

Expand Down Expand Up @@ -144,6 +155,35 @@ def goto_place(place):
def on_path_select(idx):
if -1 is idx:
return

if place.uris and place.paths[idx] == place.paths[-1]:
open_file_layouts(place.uris)
return

place.path = place.paths[idx]
place.paths = []
goto_place(place)


def open_file_layouts(files=[]):
'''open files in multi-columns layouts'''
width = 1 / len(files)
cols = [0.0]
cells = []
for (idx, file) in enumerate(files):
cols.append(width*idx+width)
cells.append([idx, 0, idx+1, 1])

active_window = sublime.active_window()
active_window.run_command('new_window')
new_window = sublime.active_window()
new_window.set_layout({
"cols": cols,
"rows": [0.0, 1.0],
"cells": cells
})
for (idx, file) in enumerate(files):
new_window.open_file(file)
new_window.set_view_index(new_window.active_view(), idx, 0)

return
5 changes: 5 additions & 0 deletions tests/fixtures/resources/lang/en/blog.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
<?php

return [
'title' => 'Title',
];
5 changes: 5 additions & 0 deletions tests/fixtures/resources/lang/fr/blog.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
<?php

return [
'title' => 'Titre',
];
7 changes: 0 additions & 7 deletions tests/test_finder.py
Original file line number Diff line number Diff line change
Expand Up @@ -196,22 +196,15 @@ def test_lang_underscore(self):
self.fixture("""__('messages.w|elcome');""")
self.assertPath('lang/messages.php')

def test_lang_blade_directive(self):
self.fixture("""@lang('messages.we|lcome');""")
self.assertPath('lang/messages.php')

def test_lang_trans(self):
self.fixture("""trans('messages.we|lcome');""")
self.assertPath('lang/messages.php')

def test_lang_trans_choice(self):
self.fixture("""trans_choice('messages.a|pples', 10);""")
self.assertPath('lang/messages.php')

def test_lang_trans_package(self):
self.fixture("""trans('package::messa|ges');""")
self.assertPath('lang/vendor/package/messages.php')

def test_relative_path_static_file(self):
self.fixture("""'./../../hel|lo.css'""")
self.assertPath('hello.css')
Expand Down
30 changes: 30 additions & 0 deletions tests/test_language.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
from . import unittest
from unittest.mock import patch
from LaravelGoto.lib.language import Language


class TestLanguage(unittest.ViewTestCase):
@patch('LaravelGoto.lib.workspace.get_folders')
def test_get_place(self, mock_get_folders):
mock_get_folders.return_value = [self.get_test_dir()]

language = Language()
place = language.get_place('blog.title')

self.assertEqual(place.path, 'lang/blog.php')
self.assertEqual(
place.paths, [
'lang/en/blog.php',
'lang/fr/blog.php',
])
self.assertEqual(len(place.uris), 2)

## vendor
place = language.get_place('pkg::blog.title')

self.assertEqual(place.path, 'lang/vendor/pkg/blog.php')
self.assertEqual(
place.paths, [
'lang/vendor/pkg/en/blog.php',
'lang/vendor/pkg/fr/blog.php',
])
10 changes: 10 additions & 0 deletions tests/test_workspace.py
Original file line number Diff line number Diff line change
Expand Up @@ -42,9 +42,19 @@ def test_get_folder_path(self):
path = workspace.get_folder_path(base, 'fixtures')
self.assertTrue(path.endswith('fixtures'), path)

folders = workspace.get_folder_path(base, 'resources/lang/*')
self.assertEqual(len(folders), 2)

path = workspace.get_folder_path(base, 'fixtures/config')
self.assertTrue(path.endswith('config'), path)

path = workspace.get_folder_path(base, 'config')
self.assertTrue(path.endswith('config'), path)

path = workspace.get_folder_path(base, 'app/Http')
self.assertTrue(path.endswith('Http'), path)

# # over 2 layer directories
path = workspace.get_folder_path(base, 'Http')
self.assertFalse(path)

Expand Down

0 comments on commit 7e8ca68

Please sign in to comment.