2017-08-24 74 views
0

的一部分,我有如下所示的目錄結構:咕嚕複製一個排序目錄

dist/ 
static/ 
static/keep1 
static/keep2 
static/versions/1 
static/versions/2 
static/versions/3 

我想一切從複製到staticdist,與versions目錄例外。我想對目錄進行排序並採用最新版本(例如版本3)。

如果我簡單地做{expand: true, cwd:'static', src: '**', dest: 'dist/', dot: 'true'},我會得到我的臃腫目錄dist/舊的,不必要的版本

有沒有一種方法以編程方式選擇最新的版本,所以我不必手動更新我的gruntfile配置我每次更新static/versions/

我想我可能會node-globminimatch會爲我工作,也許我可以用grunt-executegrunt-run(兩者都可能會難看)。我希望有一個方法可以做到這一點。

回答

1

這可以實現而不需要額外的grunt插件。但是,必須以編程方式查找存儲在./versions/目錄中的最新版本,並且必須在運行copy任務之前計算此值。 grunt-contrib-copy沒有內置的功能來確定。

一旦確定了最新的版本目錄,只需在您的copy任務中使用一對Targets即可。

以下要點演示瞭如何可以做到這一點:

注意:此方法假定最新版本是最高編號的目錄,也未通過任何方式創建或修改的日期來確定。

Gruntfile,JS

module.exports = function(grunt) { 

    'use strict'; 

    // Additional built-in node module. 
    var stats = require('fs').lstatSync; 

    /** 
    * Find the most recent version. Loops over all paths one level deep in the 
    * `static/versions/` directory to obtain the highest numbered directory. 
    * The highest numbered directory is assumed to be the most recent version. 
    */ 
    var latestVersion = grunt.file.expand('static/versions/*') 

    // 1. Include only directories from the 'static/versions/' 
    // directory that are named with numbers only. 
    .filter(function (_path) { 
     return stats(_path).isDirectory() && /^\d+$/.test(_path.split('/')[2]); 
    }) 

    // 2. Return all the numbered directory names. 
    .map(function (dirPath) { return dirPath.split('/')[2] }) 

    // 3. Sort numbers in ascending order. 
    .sort(function (a, b) { return a - b; }) 

    // 4. Reverse array order and return highest number. 
    .reverse()[0]; 


    grunt.initConfig({ 
    copy: { 

     // First target copies everything from `static` 
     // to `dist` excluding the `versions` directory. 
     allExludingVersions:{ 
     files:[{ 
      expand: true, 
      dot: true, 
      cwd: 'static/', 
      src: ['**/*', '!versions/**'], 
      dest: 'dist/' 
     }] 
     }, 

     // Second target copies only the sub directory with the 
     // highest number name from `static/versions` to `dist`. 
     latestVersion: { 
     files: [{ 
      expand: true, 
      dot: true, 
      cwd: 'static/versions/', 
      src: latestVersion + '/**/*', 
      dest: 'dist/' 
     }] 
     } 
    } 
    }); 

    grunt.loadNpmTasks('grunt-contrib-copy'); 
    grunt.registerTask('default', ['copy']); 
}; 

結果

使用Gruntfile.js以上,(與您的示例目錄結構)運行$ grunt,將導致dist目錄構造爲如下:

dist 
├── keep1 
│ └── ... 
├── keep2 
│ └── ... 
└── 3 
    └── ...