8

How can I run custom action (eg. copy file to build folder) after middleman built pages?

I want to put Readme.md file from source to build dir.

NARKOZ
  • 27,203
  • 7
  • 68
  • 90
  • I'm not familiar with middleman, but it looks like it runs in the terminal, so you could make a bash script to call middleman and then move the files into the correct folder. – Loktopus May 26 '14 at 23:47
  • I guess you also mean outside source - because all files within the source folder will be copied into the build by default. – Ian Warner Oct 18 '17 at 17:28

2 Answers2

15

You can use after_build hook. add following code to config.rb.

The hook which you can use is written in https://middlemanapp.com/advanced/custom_extensions/ .

Although it is not well documented, it seems that after_build can use directly in config.rb, without writing your own extension.

after_build do |builder|
  src = File.join(config[:source],"Readme.md")
  dst = File.join(config[:build_dir],"Readme.md")
  builder.thor.source_paths << File.dirname(__FILE__)
  builder.thor.copy_file(src,dst)
end
yas4891
  • 4,774
  • 3
  • 34
  • 55
ymonad
  • 11,710
  • 1
  • 38
  • 49
1

Though the after_build hook is a default answer, i would suggest using a task runner to do the job.

A task runner is awesome to make such routines easier. For example, most Middleman projects require deployment to a hosting server. So if you happen to use a task runner for deployment, you could use it for copying the file as well.

If you don't use a task runner, consider using one. It will save you a lot of nuisance.

Rake is the natural choice for Middleman's Ruby environment, but i prefer Grunt.

Here's a Grunt copy task (uses the grunt-contrib-copy plugin):

copy: {
  bowercomponents: {
    files: [
      {
        expand: true,
        flatten: true,
        src: [
          'source/Readme.md'
        ],
        dest: 'build/',
        filter: 'isFile'
      }
    ]
  }
}

And here's a deployment task using the grunt-shell plugin:

shell: {

    buildAndPublish: {
        command: [
          'echo "### Building ###"',
          'bundle exec middleman build --verbose',

          'echo "### Adding built files to git index ###"',
          'cd build/',
          'git add -A',

          'echo "### Commiting changes ###"',
          'git commit -m build',

          'echo "### Pushing the commit to the gh-pages remote branch ###"',
          'git push origin gh-pages',
          'cd ..'
        ].join(' && '),
        options: {
          stdout: true,
          stderr: true
        }
    }

}
Andrey Mikhaylov - lolmaus
  • 23,107
  • 6
  • 84
  • 133