Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
60 commits
Select commit Hold shift + click to select a range
15f4b47
Allow to define a project
przepompownia Apr 12, 2020
c6c6be1
Move project.vim into separate namespace
przepompownia Apr 12, 2020
e4073cd
Project repository with checking existing by file
przepompownia Apr 12, 2020
6366348
project repository can add projects
przepompownia Apr 12, 2020
5a23450
Define buffer matcher with the trivial matching case
przepompownia Apr 12, 2020
1ba95c1
Give a choice how to select project root (no test yet)
przepompownia Apr 13, 2020
a350f43
add todo
przepompownia Apr 13, 2020
d185c66
Do not use global project repository variable
przepompownia Apr 13, 2020
ffc7e75
Move command definition
przepompownia Apr 13, 2020
6fff43e
Do not use v:t_dict (unsupported by vim used in Travis)
przepompownia Apr 14, 2020
868cfdb
Move assigning logic into "static" bufferMatcher function
przepompownia Apr 14, 2020
012e445
Use isdirectory()
przepompownia Apr 14, 2020
7d84b30
Use range()
przepompownia Apr 14, 2020
4091887
Remove accessor (getRepository())
przepompownia Apr 14, 2020
9dc4f93
Remove listProjects()
przepompownia Apr 14, 2020
b07109b
Remove accessor to project.primaryRootPath
przepompownia Apr 14, 2020
bb9017b
command!
przepompownia Apr 14, 2020
e12d165
Use ftplugin instead of autocmd
przepompownia Apr 14, 2020
0113d9e
Rename function assinging project to buffer
przepompownia Apr 14, 2020
1c78674
Remove header of dropped test
przepompownia Apr 14, 2020
f2ea242
Make creation and using choices list more clear
przepompownia Apr 15, 2020
7446a9f
Rename matchFileToProject -> resolveProjectForFile
przepompownia Apr 15, 2020
29c0481
Rename bufferMatcher -> assigner
przepompownia Apr 15, 2020
54ae848
Fix tests
przepompownia Apr 16, 2020
2d71ade
Rename test
przepompownia Apr 16, 2020
7a11464
assigner: set the start choice value
przepompownia Apr 16, 2020
d3df431
Handle keyboard interrupt
przepompownia Apr 16, 2020
c0f13e6
Rename projectRepository.vim repository.vim
przepompownia Apr 16, 2020
15dc14e
Allow reassign project to buffer
przepompownia Apr 18, 2020
8abe37f
Use l:self within dict functions
przepompownia Apr 18, 2020
ea568c1
Keep directory tree logic separately
przepompownia Apr 18, 2020
c3d1583
Test phpactor#fileutils#normalizePath()
przepompownia Apr 18, 2020
0f07146
fixup! Test phpactor#fileutils#normalizePath()
przepompownia Apr 18, 2020
5e0b9fb
phpactor#fileutils#isSubdir - use stronger assumption
przepompownia Apr 18, 2020
6b7cd01
fixup! Rename bufferMatcher -> assigner
przepompownia Apr 18, 2020
73b65bc
Rename b:project to b:phpactorProject
przepompownia Apr 19, 2020
f5df4f6
FindProjectContainingFile: first return subproject if exists
przepompownia Apr 19, 2020
e008e14
Add integration test (still requires interactions with user)
przepompownia Apr 19, 2020
128e4d8
Merge branch 'develop' into projects
przepompownia Apr 21, 2020
5d8bf3f
project.containsFile(): use phpactor#fileutils#isSubdir()
przepompownia Apr 22, 2020
e3b4386
fixup! project.containsFile(): use phpactor#fileutils#isSubdir()
przepompownia Apr 22, 2020
abfbc2c
Change prompt message
przepompownia Apr 22, 2020
2cf71ef
fixup! Merge branch 'develop' into projects
przepompownia Apr 22, 2020
111598a
Merge branch 'develop' into projects
przepompownia Apr 22, 2020
88fbf57
Use local function to print the prompt header
przepompownia Apr 22, 2020
027532b
Keep resolvers in a separate reusable directory
przepompownia Apr 22, 2020
32ca70b
Allow noninteractive configurable root detection
przepompownia Apr 22, 2020
ac37012
Remove redundant `redraw`
przepompownia Apr 22, 2020
3224c65
Fix logging after new project was added
przepompownia Apr 23, 2020
30a7a98
Fix setting g:phpactorAllowInteractiveProjectResolution
przepompownia Apr 23, 2020
b80e67e
Fix vimdoc
przepompownia Apr 23, 2020
f0a2f27
Fix variable name
przepompownia Apr 23, 2020
f2c9582
Add health check for shortmess and interactive prompt
przepompownia Apr 23, 2020
cc700e9
Apply b:phpactorProject.primaryRootPath to --working-dir in RPC requests
przepompownia Apr 28, 2020
df90934
Merge branch 'develop' into projects
przepompownia Apr 29, 2020
9d5c6a7
Move assigning g:phpactorProjectAssigner from ftplugin to plugin
przepompownia Apr 29, 2020
ec932c6
Move assigning project back to autocommand
przepompownia Apr 29, 2020
82f9aaa
Merge branch 'develop' into projects
przepompownia May 1, 2020
0ff3e70
Add tests to isSubdir
przepompownia May 1, 2020
95d85ef
Test searching upward with root marker below forbidden dir
przepompownia May 1, 2020
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 21 additions & 0 deletions autoload/health/phpactor.vim
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,26 @@ function! s:check_diagnostics(diagnostics) abort
endfor
endfunction

function s:check_prompt_from_autocommand() abort
call health#report_start('Project root detection')
let l:shmFIsPresent = (stridx(&shortmess, 'F') >= 0)

if !l:shmFIsPresent
call health#report_ok('`shortmess` does not contain `F`')
return
endif

call health#report_warn(printf('`shortmess` vim option contains `F` (is %s)', &shortmess))

if v:true == g:phpactorAllowInteractiveProjectResolution
call health#report_warn('- interactive choice of method may be unavailable.')
endif

if index(g:phpactorNoninteractiveProjectResolvers, 'manual') >= 0
call health#report_warn('- manual input was enabled but it may not work')
endif
endfunction

Comment on lines +22 to +41

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think we should improve that, the goal is that it should be understandable by someone not knowing how everything works.
It's an help to show the user how the plugin will behave and hint on how to configure it if needed.

So first, I would add an information stating which kind of root detection is used.
Then you could add one function per type of detection, each one will have the responsibility to add relevant information.

For instance, we should not bother someone with the F being part of shortmessage or not if it does not impact his current configuration.

You should also use the {advice} parameter for health#report_warn and health#report_error in order to explain why the F option is problematic and only in the case of the manual detection.

function! s:check_config_files(configFiles) abort
call health#report_start('Config files (missing is not bad)')

Expand All @@ -37,4 +57,5 @@ function! health#phpactor#check() abort
call s:check_info(l:status)
call s:check_diagnostics(l:status.diagnostics)
call s:check_config_files(l:status.config_files)
call s:check_prompt_from_autocommand()
endfunction
38 changes: 1 addition & 37 deletions autoload/phpactor.vim
Original file line number Diff line number Diff line change
Expand Up @@ -459,49 +459,13 @@ endfunction
" RPC -->-->-->-->-->--
"""""""""""""""""""""""

function! s:searchDirectoryUpwardForRootPatterns(initialDirectory, workspaceRootPatterns, fallbackDirectory)
if index(g:phpactorGlobalRootPatterns, '/') < 0
call add(g:phpactorGlobalRootPatterns, '/')
endif

let l:directory = a:initialDirectory

while index(g:phpactorGlobalRootPatterns, l:directory) < 0
if s:directoryMatchesToPatterns(l:directory, a:workspaceRootPatterns)
return l:directory
endif

let l:directory = fnamemodify(l:directory, ':h')
endwhile

if index(g:phpactorGlobalRootPatterns, l:directory) >= 0
let l:directory = a:fallbackDirectory
endif

return l:directory
endfunction

function s:directoryMatchesToPatterns(directory, patterns) abort
for l:pattern in a:patterns
if (filereadable(a:directory .'/'. l:pattern))
return v:true
endif
endfor

return v:false
endfunction

function! phpactor#rpc(action, arguments)
" Remove any existing output in the message window
execute ':redraw'

let request = { "action": a:action, "parameters": a:arguments }

let l:workspaceDir = empty(g:phpactorProjectRootPatterns) ? g:phpactorInitialCwd : s:searchDirectoryUpwardForRootPatterns(
\ fnamemodify(phpactor#_path(), ':h'),
\ g:phpactorProjectRootPatterns,
\ g:phpactorInitialCwd
\)
let l:workspaceDir = (get(b:, 'phpactorProject', v:null) isnot v:null) ? b:phpactorProject.primaryRootPath : g:phpactorInitialCwd

@camilledejoye camilledejoye Apr 29, 2020 •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This will solve the issue #985
But I think we can do even better, right now it only makes possible to use phpactor root detection system.

It should not be phpactor responsibility to resolve the directory in the first place, we should only ensure that we provide the root directory when sending a request.

I mentioned it because on this line I think we should consider the all root detection mechanism as external.
It would reduce the complexity by getting back to real need: provide a root directory.
Initially phpactor was using g:phpactorInitialCwd, to prevent any BC break we need to keep this variable with it's value being the directory from which vim was started.
From this point we want to be able to provide a directory depending on the buffer, meaning we will need to "ask" each buffer what is its root directory.
We can translate this need by

We want to be able to apply different strategies at runtime

So instead of coupling this piece of code to any system, let's couple it to an abstract strategy that could be defined by anyone.

Suggested change
let l:workspaceDir = (get(b:, 'phpactorProject', v:null) isnot v:null) ? b:phpactorProject.primaryRootPath : g:phpactorInitialCwd
let l:workspaceDir = phpactor#getRootDirectory()

With

if !exists('g:PhpactorRootDirectoryStrategy')
  let g:PhpactorRootDirectoryStrategy = {-> g:phpactorInitialCwd}
endif

function! phpactor#getRootDirectory() abort
  let l:Strategy = get(b:, 'PhpactorRootDirectoryStrategy', g:PhpactorRootDirectoryStrategy)

  if type(function('type')) != type(l:Strategy)
    let l:Strategy = {-> g:phpactorInitialCwd}
  endif

  return l:Strategy()
endfunction

At this point the user is free to define both global and buffer local strategies.
We don't have any BC break since the default behavior is the same as before the first attempt to resolve the root directory.
Example of configuration:

To use with your system

" vimrc
let g:PhpactorRootDirectoryStrategy = {-> get(get(b:, 'phpactorProject', {}), 'primaryRootPath', g:phpactorInitialCwd)}

To use vim pwd (for users with vim-rooter for instance)

" vimrc
let g:PhpactorRootDirectoryStrategy = function('getcwd')

The goal of this proposal is not to diminish your work at all, it's simply to provide a way of integrating in a extensible way.
So thanks for all what you have done anyone can use phpactor out of box with multiple projects in one vim instances.
Users having already a setup handling this notion can plug into phpactor to reuse what they have.
Users with no need for it will keep things as they were.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I kept such idea (without any implementation) as a backup in case of non-acceptance the whole work, but it should be the default approach - not backup. Your proposition sounds reasonable: gives an abstraction that contains a minimal implementation and can be replaced by any implementation maintained independently in some separate project.

The whole implementation of this approach is yours so please make PR that closes this after merge.

@dantleech @elythyr thanks for a lot of critical word.

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks so much for all your work so far :) Even if this PR isn't merged as-is there is lots of valuable stuff here which we can take forward (especially with the Vader tests).

I've found it quite difficult to follow everything going on here, but I think we could do something like:

  • Allowing project-root strategy to be selected (custom or phpactor CWD)
  • Strategy for changing CWD if the user opens up a file != the filesystem branch of the current project root (with confirmation).

Either as part of this PR or new PR(s) - would that cover everything?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Let this PR die in the current form and (before) implement @elythyr's proposition in a separate one.

@elythyr would you like to make such PR? I can do it just as well.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

You can do it if you want.
The ideal would be to do it quickly enough so it will be in the next release.

Let me know if you won't have the time.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It can be unpredictable so we can assume I have not.


let l:cmd = g:phpactorPhpBin . ' ' . g:phpactorbinpath . ' rpc --working-dir=' . l:workspaceDir

Expand Down
47 changes: 47 additions & 0 deletions autoload/phpactor/fileutils.vim
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
function! phpactor#fileutils#searchUpwardBySingleMarker(path, marker) abort
let l:markerFile = findfile(a:marker, fnamemodify(a:path, ':p:h').';')

return empty(l:markerFile) ? v:null : fnamemodify(l:markerFile, ':p:h')
endfunction

function! phpactor#fileutils#searchDirectoryUpwardByRootMarkers(initialDirectory, workspaceRootMarkers, forbiddenDirs)
for l:marker in a:workspaceRootMarkers
let l:markerPath = phpactor#fileutils#searchUpwardBySingleMarker(a:initialDirectory, l:marker)

if v:null is l:markerPath
continue
endif

if empty(a:forbiddenDirs) || ! phpactor#fileutils#containsDirectoryFrom(l:markerPath, a:forbiddenDirs)
return l:markerPath
endif
endfor

return v:null
endfunction

function! phpactor#fileutils#normalizePath(path) abort
let l:modifiers = isdirectory(a:path) ? ':p:h' : ':p'

return simplify(fnamemodify(a:path, l:modifiers))
endfunction

function! phpactor#fileutils#containsDirectoryFrom(directory, dirList) abort
let l:directory = phpactor#fileutils#normalizePath(a:directory)

for l:subdir in a:dirList
let l:subdir = phpactor#fileutils#normalizePath(l:subdir)
if phpactor#fileutils#isSubdir(l:subdir, l:directory)
return v:true
endif
endfor

return v:false
endfunction

function! phpactor#fileutils#isSubdir(expectedSubdir, directory) abort
Comment thread
przepompownia marked this conversation as resolved.
Resolved
let l:expectedSubdir = phpactor#fileutils#normalizePath(a:expectedSubdir)
let l:directory = phpactor#fileutils#normalizePath(a:directory)

return stridx(l:expectedSubdir, l:directory) == 0
endfunction
151 changes: 151 additions & 0 deletions autoload/phpactor/project/assigner.vim
Original file line number Diff line number Diff line change
@@ -0,0 +1,151 @@
function! phpactor#project#assigner#assignProjectToBuffer(filename, allowReassign, allowInteractive)
if !exists('g:loaded_phpactor')
return
endif

if exists('b:phpactorProject') && (v:false is a:allowReassign)
return
endif
let l:project = g:phpactorProjectAssigner.resolveProjectForFile(a:filename, a:allowInteractive)
if v:null is l:project
return
endif
let b:phpactorProject = l:project

if g:phpactorProjectAssigner.repository.hasProject(b:phpactorProject)
return
endif

call g:phpactorProjectAssigner.repository.addProject(b:phpactorProject)
echomsg printf('Project with root "%s" has been created.', b:phpactorProject.primaryRootPath)
endfunction

function! phpactor#project#assigner#create(
\ projectRepository,
\ projectRootMarkers,
\ forbiddenProjectRoots,
\ initialCwd,
\ noninteractiveResolverNames
\) abort
let l:forbiddenProjectRoots = a:forbiddenProjectRoots
if index(l:forbiddenProjectRoots, '/') < 0
call add(l:forbiddenProjectRoots, '/')
endif

let l:resolverNames = filter(copy(a:noninteractiveResolverNames), function('s:isValidResolverName'))
if (index(l:resolverNames, 'initialCwd')) < 0
call add(l:resolverNames, 'initialCwd')
endif

return {
\ 'initialCwd': a:initialCwd,
\ 'projectRootMarkers': a:projectRootMarkers,
\ 'forbiddenProjectRoots': l:forbiddenProjectRoots,
\ 'repository': a:projectRepository,
\ 'resolveProjectForFile': function('s:resolveProjectForFile'),
\ 'noninteractiveResolverNames': l:resolverNames
\ }
endfunction

function s:isValidResolverName(index, resolverName) abort
let l:validProjectResolverNames = ['manual', 'rootMarkers', 'initialCwd']

return index(l:validProjectResolverNames, a:resolverName) >= 0
endfunction

function s:resolveProjectForFile(file, allowInteractive) dict abort
let l:project = l:self.repository.findProjectContainingFile(a:file)

if type(l:project) == type({})
return l:project
endif

" see phpactor#_path
let l:initialDirectory = fnamemodify(a:file, ':p:h')
let l:rootDirByMarker = phpactor#fileutils#searchDirectoryUpwardByRootMarkers(
\ l:initialDirectory,
\ l:self.projectRootMarkers,
\ l:self.forbiddenProjectRoots
\ )

let l:resolvers = {
\ 'initialCwd': { -> l:self.initialCwd },
\ 'manual': function('input', ['Enter file path: ', l:initialDirectory, 'file'])
\ }

if v:null != l:rootDirByMarker
let l:resolvers['rootMarkers'] = { -> l:rootDirByMarker }
endif

if v:false is a:allowInteractive
return s:resolveNoninteractive(l:resolvers, l:self.noninteractiveResolverNames)
endif

let l:choices = [
\ {
\ 'action': l:resolvers['initialCwd'],
\ 'message': s:printHeader(a:file, l:self.initialCwd)
\ },
\ {
\ 'action': l:resolvers['manual'],
\ 'message': printf('manual (default "%s")', l:initialDirectory)
\ }
\ ]

if v:null != l:rootDirByMarker
let l:item = {
\ 'action': l:resolvers['rootMarkers'],
\ 'message': 'autodetected by root marker: '.l:rootDirByMarker
\ }
call add(l:choices, l:item)
endif

let l:choice = 0
while index(range(1, len(l:choices)-1), l:choice) < 0
try
let l:choice = inputlist(map(copy(l:choices), {
\ number, item -> (number ? printf('%d. ', number) : '') . item['message']
\ }))
catch /^Vim:Interrupt$/
break
endtry

if l:choice == 0
break
endif

redraw
endwhile

let l:selectedDir = l:choices[l:choice]['action']()

if v:null != l:selectedDir
let l:project = phpactor#project#project#createFromRootPath(l:selectedDir)

return l:project
endif
endfunction

function s:resolveNoninteractive(resolvers, resolverNames) abort
for l:resolverName in a:resolverNames
if v:null is get(a:resolvers, l:resolverName, v:null)
continue
endif

let l:primaryRootPath = a:resolvers[l:resolverName]()

if l:primaryRootPath !=# ''
return phpactor#project#project#createFromRootPath(l:primaryRootPath)
endif
endfor
endfunction

function s:printHeader(filePath, initialCwd) abort
" heredoc are available since vim 8.1.1354
return printf(join([
\ 'Phpactor [RPC]',
\ 'There is no project enabled for "%s" yet.',
\ 'Select the way of assign the project root',
\ 'If cancelled, "%s" will be used.'
\], "\n"), a:filePath, a:initialCwd)
endfunction
23 changes: 23 additions & 0 deletions autoload/phpactor/project/project.vim
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
function! phpactor#project#project#createFromRootPath(primaryRootPath) abort
return {
\ 'primaryRootPath': s:normalizeRootPath(a:primaryRootPath),
\ 'containsFile': function('s:containsFile')
\ }
endfunction

function! s:containsFile(filepath) dict
let l:path = simplify(fnamemodify(a:filepath, ':p:h'))

return phpactor#fileutils#isSubdir(l:path, l:self.primaryRootPath)
endfunction

function s:normalizeRootPath(path) abort
let l:path = phpactor#fileutils#normalizePath(a:path)

" @todo better check if it is not an existing directory
if ! isdirectory(l:path)
throw printf('Path "%s" does not exist or is not a directory so it cannot be a root path.', l:path)
endif

return l:path
endfunction
42 changes: 42 additions & 0 deletions autoload/phpactor/project/repository.vim
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
function! phpactor#project#repository#create() abort
return {
\ 'projects': {},
\ 'isEmpty': function('s:isEmpty'),
\ 'addProject': function('s:addProject'),
\ 'findProjectContainingFile': function('s:findProjectContainingFile'),
\ 'hasProjectWithPrimaryRoot': function('s:hasProjectWithPrimaryRoot'),
\ 'hasProject': function('s:hasProject')
\ }
endfunction

function! s:findProjectContainingFile(file) dict abort
for l:rootPath in reverse(sort(keys(l:self.projects)))
let l:project = l:self.projects[l:rootPath]
if l:project.containsFile(a:file)
return l:project
endif
endfor

return v:null
endfunction

function! s:addProject(project) dict abort
" todo check type
if v:null isnot get(l:self.projects, a:project.primaryRootPath, v:null)
throw printf('Project "%s" already exists', a:project.primaryRootPath)
endif

let l:self.projects[a:project.primaryRootPath] = a:project
endfunction

function! s:hasProject(project) dict abort
return get(l:self.projects, a:project.primaryRootPath, v:false) isnot v:false
endfunction

function! s:hasProjectWithPrimaryRoot(path) dict abort
return get(l:self.projects, a:path, v:false) isnot v:false
endfunction

function! s:isEmpty() dict abort
return empty(l:self.projects)
endfunction
1 change: 1 addition & 0 deletions config/travis/vim-plugin-test.sh
Original file line number Diff line number Diff line change
@@ -1 +1,2 @@
#!/usr/bin/env sh
vim -Nu config/travis/.vimrc -c 'Vader! tests/VimPlugin/*'
1 change: 0 additions & 1 deletion ftplugin/php.vim
Original file line number Diff line number Diff line change
Expand Up @@ -3,5 +3,4 @@ augroup PhpactorInit
autocmd CompleteDone <buffer> call phpactor#_completeImportClass(v:completed_item)
augroup END


" vim: et ts=4 sw=4 fdm=marker
5 changes: 5 additions & 0 deletions ftplugin/php/commands.vim
Original file line number Diff line number Diff line change
Expand Up @@ -65,3 +65,8 @@ command! -buffer -nargs=0 PhpactorGenerateAccessors call phpactor#GenerateAccess
""
" Automatically add any missing properties to a class
command! -buffer -nargs=0 PhpactorTransform call phpactor#Transform()

""
" List projects existing in this vim instance
" (currently each project consist of its root directory only)
command! PhpactorListProjects echo keys(map(copy(g:phpactorProjectAssigner.repository.projects), { key, val -> key}))
Loading