Sublime Forum

My first custom build system

#1

Hi,

I’d like to create a custom build system for my web developments, and frankly, i don’t know a thing about it.
The features i need :

  • find all files in the project with extensions a, b or c
  • parse them for some regex
  • replace found items to append datetime (to the reference, not to the actuel resource filename)
  • save modified files

Could you put me in the good direction on how to do that ? I lloked for tutos, but couldn’t find.

Thanks

0 Likes

#2

Click on Tools -> Build Systems -> New Build System…

Paste the following:

{
    "target": "do_stuff"
}

And save it in our Packages/User directory as “Do Stuff.sublime-build” (just hit the save keybinding and the correct folder will be presented to you).

Now open the console: click on View -> Show Console.

A python console will appear. Now activate your build system: click on Tools -> Build Systems -> Do Stuff. Hit CTRL+B and… Nothing happens. Except that in the Console, you will see:

Unable to find target command: do_stuff

Let us implement that command. Click on Tools -> Developer -> New Plugin… and paste the following:

import sublime
import sublime_plugin
import os


class DoStuffCommand(sublime_plugin.WindowCommand):
    def run(self, *args, **kwargs) -> None:
        try:
            working_dir = self.determine_working_dir(**kwargs)
        except ValueError as e:
            sublime.error_message(str(e))
            return
        self.prepare_output_view()
        self.process_files(working_dir)

    def process_files(self, working_dir: str) -> None:
        for root, _, files in os.walk(working_dir):
            for file in files:
                self.process_file(root, file)
    
    def process_file(self, root: str, file: str) -> None:
        abspath = os.path.join(root, file)
        self.print(abspath)
        # 
        # Process the file here...
        #

    def prepare_output_view(self) -> None:
        if not hasattr(self, 'output_view'):
            # Try not to call get_output_panel until the regexes are assigned
            self.output_view = self.window.create_output_panel('do_stuff')
        settings = self.output_view.settings()
        settings.set('word_wrap', False)
        settings.set('line_numbers', False)
        settings.set('gutter', False)
        settings.set('scroll_past_end', False)
        settings.set('rulers', [])
        settings.set('syntax', 'Packages/Default/Plain Text.sublime-syntax')
        # Call create_output_panel a second time after assigning the above
        # settings, so that it'll be picked up as a result buffer
        self.window.create_output_panel('do_stuff')
        self.window.run_command('show_panel', {'panel': 'output.do_stuff'})

    def determine_working_dir(self, **kwargs) -> str:
        try:
            default = self.window.project_data()['folders'][0]['path']
        except KeyError:
            default = None
        result = kwargs.get('working_dir', default)
        if result:
            return result
        # Default the to the current files directory if no working directory was given
        elif self.window.active_view() and self.window.active_view().file_name():
            return os.path.dirname(self.window.active_view().file_name())
        else:
            raise ValueError('Could not determine working directory')

    def print(self, *args) -> None:
        view = getattr(self, 'output_view', None)
        if view:
            text = '{}\n'.format(' '.join(args))
            args = {'characters': text, 'force': True, 'scroll_to_end': True}
            view.run_command('append', args)

Save this file as DoStuff.py in the folder that is presented to you (the Packages/User folder again). Now hit CTRL+B again and you should see an output panel pop-up with the files listed in your project.

You will have to implement the method process_file to do what you want. To print to the panel, use self.print("hello", "world", "etc").

Actually, after re-reading what I just wrote you might as well turn this into a regular window command with a keybinding.

1 Like

#3

Thanks a lot !
I’m sure this will help me ; i test it and i come back to this post.

0 Likes

#4

Did it work?

0 Likes