Sublime Forum

Recursivley search up directories until file is found in build system

#1

I’m writing some C code in Sublime at the moment and my entire build process is inside a .bat file at the root of my folder.

Is there any way that when I press ctrl + b the build system can search for the .bat file in the directory of the current active file, but then look up one directory if it doesn’t exist there, and repeat as necessary until either the it reaches the root of the drive or one is found and run?

I assume there is no way to do this with Sublime’s plain build system, but if there is would anyone be able to tell me how?

If not, then I assume that I would have to write a plugin to do this and bind a key to the command, correct?

0 Likes

Sublime API and `subst` on Windows
#2

So I ended up figuring out how to create a command that I could bind to a key instead of using the build system directly.

I saved a file called Shell.py in my User folder with the following in it:

import sublime_plugin
import os

class ShellCommand(sublime_plugin.TextCommand):
    def run(self, edit, **kwargs):
        if not kwargs.get('file'):
            return
        file = kwargs.get('file')
        current_filename = self.view.window().active_view().file_name()
        if not current_filename:
            self.view.window().run_command('exec', {
                'shell_cmd': 'echo Active view not found'
            })
            return
        dir = os.path.dirname(current_filename)
        cwd = os.getcwd()
        os.chdir(dir)
        while not os.path.isfile(file):
            cur = os.path.realpath(os.getcwd())
            up = os.path.realpath(os.getcwd() + '/..')
            if up == cur:
                break
            os.chdir('..')
        if os.path.isfile(file):
            self.view.window().run_command('save')
            self.view.window().run_command('exec', {
                'shell_cmd': file + " " + current_filename + " " + dir,
                'working_dir': os.getcwd(),
                'quiet': True
            })
        else:
            self.view.window().run_command('exec', {
                'shell_cmd': 'echo File not found: ' + file
            })
        os.chdir(cwd)

I’m running on Windows so it may need some edits for Linux or Mac, but it gets the job done.

Then I can just bind it to a key like this:

{ "keys": [ "ctrl+b"], "command": "shell", "args": { "file": "build.bat" } }

2 Likes