Search for project files


#1

I’m trying to write a plugin that finds project files for a opened source file (cargo file for a rust file). My idea was to check the directory, and to go up one level if no project file was found. This would be done until the file system root is found. However with the following code Atom gets stuck in an endless loop.
I’m thankful for every critique and hint.

  findProjectDir: (path) ->
    parent = fs.normalize (parent + '/..')

    # stop recursion at file system root
    if path == parent
      false

    cargoFile = fs.listSync(parent, ['toml'])
    console.log cargoFile

    if cargoFile.length > 0
      console.log 'Found cargo file'
      cargoFile[0]
    else
      console.log 'Nothing found, recourse'
      @test parent

  search: ->
    console.log 'Searching...'

    path = atom.workspace.getActiveTextEditor().getPath()
    @findProjectDir path

#2

Should @test be @findProjectDir? Otherwise there is no recursive call.

Also, rather than your weird kludge of parent = fs.normalize (parent + '/..'), I’d recommend just using the path.dirname function, which gives you the parent directory of the path you supply. If it is a file, it gives you the directory the file is in. If it is a directory, it gives you the parent directory of the directory.

You also probably mean parent = fs.normalize (path + '/..') on the first line. (The second parent on that line should be path.)


#3

Thanks for your comments, they were all valid and helpful. However they didn’t solve the underlying problem. Apparently CoffeeScript didn’t infer that the if ... false would return, and so keep going in the loop.
By writing the following I solved the problem:

if path is parent
    return false