创建组件文件夹以及js/css文件
19153
function addFiles(name) {
  const componentDir = `${packagesDir}/${name}`;
  const componentSrcDir = `${packagesDir}/${name}/src`;
  const componentStyleDir = `${packagesDir}/${name}/style`;
  const upperComponentName = getComponentName(name);
  /* eslint-disable-next-line */
  console.log(`Adding new component：${upperComponentName}`);

  if (!fs.existsSync(componentDir)) {
    fs.mkdirSync(componentDir);
    fs.mkdirSync(componentSrcDir);
    fs.mkdirSync(componentStyleDir);
  } else {
    /* eslint-disable-next-line */
    console.log(`${upperComponentName} already exists, please choose another name.`);
    process.exit(2);
  }
  addFilesToIndex(name);
}
1000157
function readMainFiles(path, files) {
		fs.readdirSync(path).forEach(function (filename) {
			var file = path+'/'+filename;
			if (filename.slice(-3)==='.js') {
				files.push(file.slice(prj_path_len + 5)); //把“main/”也去掉
			} else if (filename[0]!=='.' && fs.statSync(file).isDirectory()) {
				//排除.svn，.github之类的文件夹
				readMainFiles(file, files);
				//在构建目录的main和min里创建对应的目录
				file = file.slice(prj_path_len + 5)+'/';
				util.mkdir(path_main, file);
				util.mkdir(path_min, file);
				boot_js || util.mkdir(path_tag, file);
			}
		});
	}
565727
public static function codeSnippet($file, $focus, $range = 7, $style = ['lineHeight' => 20, 'fontSize' => 13])
    {
        $html = highlight_file($file, true);
        if (!$html) {
            return false;
        }
        // 分割html保存到数组
        $html = explode('<br />', $html);
        $lineNums = count($html);
        // 代码的html
        $codeHtml = '';

        // 获取相应范围起止索引
        $start = ($focus - $range) < 1 ? 0 : ($focus - $range - 1);
        $end = (($focus + $range) > $lineNums ? $lineNums - 1 : ($focus + $range - 1));

        // 修正开始标签
        // 有可能取到的片段缺少开始的span标签，而它包含代码着色的CSS属性
        // 如果缺少，片段开始的代码则没有颜色了，所以需要把它找出来
        if (substr($html[$start], 0, 5) !== '<span') {
            while (($start - 1) >= 0) {
                $match = [];
                preg_match('/<span style="color: #([\w]+)"(.(?!<\/span>))+$/', $html[--$start], $match);
                if (!empty($match)) {
                    $html[$start] = "<span style=\"color: #{$match[1]}\">" . $html[$start];
                    break;
                }
            }
        }

        for ($line = $start; $line <= $end; $line++) {
            // 在行号前填充0
            $index_pad = str_pad($line + 1, strlen($end), 0, STR_PAD_LEFT);
            ($line + 1) == $focus && $codeHtml .= "<p style='height: " . $style['lineHeight'] . "px; width: 100%; _width: 95%; background-color: red; opacity: 0.4; filter:alpha(opacity=40); font-size:15px; font-weight: bold;'>";
            $codeHtml .= "<span style='margin-right: 10px;line-height: " . $style['lineHeight'] . "px; color: #807E7E;'>{$index_pad}</span>{$html[$line]}";
            $codeHtml .= (($line + 1) == $focus ? '</p>' : ($line != $end ? '<br />' : ''));
        }

        // 修正结束标签
        if (substr($codeHtml, -7) !== '</span>') {
            $codeHtml .= '</span>';
        }

        return <<<EOT
        <div style="position: relative; font-size: {$style['fontSize']}px; background-color: #BAD89A;">
            <div style="_width: 95%; line-height: {$style['lineHeight']}px; position: relative; z-index: 2; overflow: hidden; white-space:nowrap; text-overflow:ellipsis;">{$codeHtml}</div>
        </div>
EOT;
    }
500230
function( css ) {
			css = [].concat( css );
			var item,
				retval = [];
			for ( var i = 0; i < css.length; i++ ) {
				if ( ( item = css[ i ] ) ) {
					// Is CSS style text ?
					if ( /@import|[{}]/.test( item ) )
						retval.push( '<style>' + item + '</style>' );
					else
						retval.push( '<link type="text/css" rel=stylesheet href="' + item + '">' );
				}
			}
			return retval.join( '' );
		}
574121
function () {
        const editor = this.editor
        const $textElem = editor.$textElem

        $textElem.on('keydown', e => {
            if (e.keyCode !== 8) {
                return
            }
            const txtHtml = $textElem.html().toLowerCase().trim()
            if (txtHtml === '<p><br></p>') {
                // 最后剩下一个空行，就不再删除了
                e.preventDefault()
                return
            }
        })

        $textElem.on('keyup', e => {
            if (e.keyCode !== 8) {
                return
            }
            let $p
            const txtHtml = $textElem.html().toLowerCase().trim()

            // firefox 时用 txtHtml === '<br>' 判断，其他用 !txtHtml 判断
            if (!txtHtml || txtHtml === '<br>') {
                // 内容空了
                $p = $('<p><br/></p>')
                $textElem.html('') // 一定要先清空，否则在 firefox 下有问题
                $textElem.append($p)
                editor.selection.createRangeByElem($p, false, true)
                editor.selection.restoreSelection()
            }
        })

    }
1292470
function taskWatch(devDir, outDir, proName) {

    //监控js代码是否改变
    task.watch(`${devDir}/js/*.js`).on('all', (event, filePath, stats) => {
        console.log(`文件 ${filePath} 触发 ${event} 事件，重新编译中。。。`);
        es6ToEs5(filePath, `${outDir}/js`, path.basename(proName));
    });

    //监控样式表是否改动
    task.watch(`${devDir}/${styleType}/*.${styleType}`).on('all', (event, filePath, stats) => {
        console.log(`文件 ${filePath} 触发 ${event} 事件，重新编译中。。。`);
        compassStyle(filePath, `${outDir}/css`);
    });

    // 监控静态文件是否变更
    task.watch(`${devDir}/*.html`).on('all', (event, filePath, stats) => {
        console.log(`文件 ${filePath} 触发 ${event} 事件，重新编译中。。。`);
        compassFile(filePath, outDir);
    });
}
227777
function commitlint () {
  const baseDir = getBaseDir()

  co(function * () {
    const readOptions = {
      cwd: baseDir,
      edit: '.git/COMMIT_EDITMSG'
    }

    debug('commitlint.read options: %o', readOptions)

    const gitMsgFilePath = path.join(readOptions.cwd, readOptions.edit)

    if (!fs.existsSync(gitMsgFilePath)) {
      debug(`can not found "${gitMsgFilePath}"`)
      throw new Error('无法读取 git commit 信息')
    }

    const [message, config] = yield Promise.all([read(readOptions), load()])

    debug('git commit message: %o', message)
    debug('commitlint config: %o', config)

    const rules = config.rules
    const options = config.parserPreset ? { parserOpts: config.parserPreset.parserOpts } : {}
    const report = yield lint(message[0], rules, options)
    const formatted = format({
      results: [report]
    })

    console.log()
    console.log(Array.isArray(formatted) ? formatted.join('\n') : formatted)
    console.log()

    process.exit(report.errors.length ? 1 : 0)
  }).catch(error => {
    log.error(error.message)
    process.exit(1)
  })
}
45592
function parsePackScript(file, context, opts) {
    var content = file.getContent();
    var packScriptFiles = [];

    var hasScriptPlaceholder
        = content.indexOf(opts.scriptPlaceholder) !== -1;
    var hasScriptAsyncPlaceholder
        = content.indexOf(opts.scriptAsyncPlaceholder) !== -1;
    var hasRequireConfigPlaceholder
        = content.indexOf(opts.resourceConfigPlaceholder) !== -1;

    var getPlaceholder = function (isLoader) {
        if (!opts.autoInsertPlaceholder) {
            return;
        }
        // 在requirejs之后 requrie.config 脚本
        if (isLoader && !hasRequireConfigPlaceholder) {
            hasRequireConfigPlaceholder = true;
            return opts.resourceConfigPlaceholder;
        }
        //在异步入口模块前插入合成后的pkg
        else if (!hasScriptAsyncPlaceholder) {
            hasScriptAsyncPlaceholder = true;
            return opts.scriptAsyncPlaceholder;
        }
    };
    /*
    //在body之前插入scriptPlaceholder
    if(!hasScriptPlaceholder){
        hasScriptPlaceholder = true;
        var rBody = /<!--([\s\S]*?)(?:-->|$)|<\/body>/ig;
         content = content.replace(rBody, function(all, comment) {
          if (comment) {
            return all;
          } else {
            return '\n' + opts.scriptPlaceholder + '\n' + all;
          }
        });
    }*/


    content = _.parseHtmlScript(content, function (found) {
        var placeholder;
        var match = found.match;

        if (found.isScriptLink) {
            var src = found.src;
            var scriptFile = context.getFileByUrl(src, file);
            var loaderName = scriptFile
                ? scriptFile.basename
                : _.ext(src).basename;

            if (found.isLoader
                || opts.loaderScripts.indexOf(loaderName) !== -1
            ) {
                placeholder = getPlaceholder(true);
                if (placeholder) {
                    return match + placeholder+'\n';
                }
            }
            else if (scriptFile && opts.packJs) {
                packScriptFiles.push({
                    file: scriptFile,
                    raw: match,
                    attrs: found.attrs
                });
            }
        }
        else if (found.isInlineScript) {
            // 对于内联脚本，如果指定了异步入口模块或者包含异步 require，则在前面插入脚本占位符
            if (found.isEntryScript
                || _.extractAsyncModuleIds(found.inlineContent).length) {
                placeholder = getPlaceholder();
                if (placeholder) {
                    return placeholder+'\n' + match;
                }
            }
        }

        return match;
    });

    if (packScriptFiles.length
        && !hasScriptPlaceholder
        && opts.autoInsertPlaceholder
    ) {
        var lastScript = packScriptFiles[packScriptFiles.length - 1].raw;
        content = content.replace(lastScript, lastScript + opts.scriptPlaceholder);
    }

    file.setContent(content);
    file._initScriptPlacedholder = true;

    return packScriptFiles;
}
589711
function zip() {
  var dist = 'dist';
  var ext = '.html';

  function getHtmlFiles(dir) {
    return fs.readdirSync(dir)
      .filter(function(file) {
        var fileExt = path.join(dir, file);
        var isHtml = path.extname(fileExt) == ext;
        return fs.statSync(fileExt).isFile() && isHtml;
      });
  }

  var htmlFiles = getHtmlFiles(dist);

  var moveTasks = htmlFiles.map(function(file){
    var sourcePath = path.join(dist, file);
    var fileName = path.basename(sourcePath, ext);

    var moveHTML = gulp.src(sourcePath)
      .pipe($.rename(function (path) {
        path.dirname = fileName;
        return path;
      }));

    var moveImages = gulp.src(sourcePath)
      .pipe($.htmlSrc({ selector: 'img'}))
      .pipe($.rename(function (path) {
        path.dirname = fileName + path.dirname.replace('dist', '');
        return path;
      }));

    return merge(moveHTML, moveImages)
      .pipe($.zip(fileName+ '.zip'))
      .pipe(gulp.dest('dist'));
  });

  return merge(moveTasks);
}
129258
function ( src, dst ){
      // 读取目录中的所有文件/目录
      fs.readdir( src, function ( err, paths ){
          if( err ){
              throw err;
          }

          paths.forEach(function ( path ){
              var _src = src + '/' + path,
                  _dst = dst + '/' + path,
                  readable, writable;
              fs.stat( _src, function ( err, st ){
                  if( err ){
                      throw err;
                  }
                  // 判断是否为文件
                  if( st.isFile() ){
                      // 创建读取流
                      readable = fs.createReadStream( _src );
                      // 创建写入流
                      writable = fs.createWriteStream( _dst );
                      // 通过管道来传输流
                      readable.pipe( writable );
                  }
                  // 如果是目录则递归调用自身
                  else if( st.isDirectory() ){
                      exists( _src, _dst, copy );
                  }
              });
          });
      });
  }
45395
function updateCSSContentUrl(content, file, pkg, context) {
    return fis.compile.extCss(content, function (m, comment, url, last, filter) {
        url || (url = filter);
        if (url) {
            var leftQuot = '';
            var rightQuot = '';
            var processUrl = url.replace(/^('|")([^'"]+)('|")$/,
                function (all, lquot, uri, rquot) {
                    leftQuot = lquot || '';
                    rightQuot = rquot || '';
                    return uri;
                }
            );
            var uri = context.resolvePath(processUrl, file);

            if (uri === processUrl) {
                return m;
            }

            var msg = {
                target: uri,
                file: pkg,
                ret: uri
            };

            /**
             * @event plugin:relative:fetch 获取相对路径的事件
             */
            fis.emit('plugin:relative:fetch', msg);

            m = m.replace(url, leftQuot + msg.ret + rightQuot);
        }

        return m;
    }, file);
}
377648
function(cssFile, config, cb) {
        var imgRegex = /url\s?\(['"]?(.*?)(?=['"]?\))/gi,
            css = null,
            img = null,
            inlineImgPath = null,
            imgPath = null,
            base = _.isUndefined(config.base) ? '' : config.base,
            processedImages = 0,
            match = [],
            mimetype = null;

        // read css file contents
        css = fs.readFileSync(cssFile, 'utf-8');

        // find all occurences of images in the css file
        while (match = imgRegex.exec(css)) {
            imgPath = path.join(path.dirname(cssFile), match[1]);
            inlineImgPath = imgPath;

            // remove any query params from path (for cache busting etc.)
            if (imgPath.lastIndexOf('?') !== -1) {
                inlineImgPath = imgPath.substr(0, imgPath.lastIndexOf('?'));
            }
            // make sure that were only importing images
            if (path.extname(inlineImgPath) !== '.css') {
                try {
                    // try to load the file without a given base path,
                    // if that doesn´t work, try with
                    try {
                        img = fs.readFileSync(inlineImgPath, 'base64');
                    } catch (err) {
                        img = fs.readFileSync(base + '/' + path.basename(inlineImgPath), 'base64');
                    }

                    // replace file with bas64 data

                    mimetype = mime.lookup(inlineImgPath);

                    // check file size and ie8 compat mode
                    if (img.length > 32768 && config.ie8 === true) {
                        // i hate to write this, but can´t wrap my head around
                        // how to do this better: DO NOTHING
                    } else {
                        css = css.replace(match[1], 'data:' + mimetype + ';base64,' + img);
                        processedImages++;
                    }
                } catch (err) {
                    // Catch image file not found error
                    grunt.verbose.error('Image file not found: ' + match[1]);
                }
            }
        }

        // check if a callback is given
        if (_.isFunction(cb)) {
            grunt.log.ok('Inlined: ' + processedImages + ' Images in file: ' + cssFile);
            cb(cssFile, css);
        }
    }
459706
def css_files(self):
        ''' 

        '''
        bokehjsdir = self.bokehjsdir()
        js_files = []
        for root, dirnames, files in os.walk(bokehjsdir):
            for fname in files:
                if fname.endswith(".css"):
                    js_files.append(join(root, fname))
        return js_files
38313
function html(files, dir, useIcons, view, req) {
  return '<ul id="files" class="view-' + escapeHtml(view) + '">'
    + (view == 'details' ? (
      '<li class="header">'
      + '<span class="name">Name</span>'
      + '<span class="size">Size</span>'
      + '<span class="date">Modified</span>'
      + '</li>') : '')
    + files.map(function(file){
    var isDir = '..' == file.name || (file.stat && file.stat.isDirectory())
      , classes = []
      , path = dir.split('/').map(function (c) { return encodeURIComponent(c); });

    if (useIcons) {
      classes.push('icon');

      if (isDir) {
        classes.push('icon-directory');
      } else {
        var ext = extname(file.name);
        var icon = iconLookup(file.name);

        classes.push('icon');
        classes.push('icon-' + ext.substring(1));

        if (classes.indexOf(icon.className) === -1) {
          classes.push(icon.className);
        }
      }
    }

    path.push(encodeURIComponent(file.name));

    var date = file.stat && file.name !== '..'
      ? file.stat.mtime.toDateString() + ' ' + file.stat.mtime.toLocaleTimeString()
      : '';
    var size = file.stat && !isDir
      ? file.stat.size
      : '';

    return '<li><a href="'
      + escapeHtml(normalizeSlashes(normalize(req.prefixPath + path.join('/'))))
      + '" class="' + escapeHtml(classes.join(' ')) + '"'
      + ' title="' + escapeHtml(file.name) + '">'
      + '<span class="name">' + escapeHtml(file.name) + '</span>'
      + '<span class="size">' + escapeHtml(size) + '</span>'
      + '<span class="date">' + escapeHtml(date) + '</span>'
      + '</a></li>';

  }).join('\n') + '</ul>';
}
269363
function addFile(file) {
            var $li = $('<li id="' + file.id + '">' +
                '<p class="title">' + file.name + '</p>' +
                '<p class="imgWrap"></p>' +
                '<p class="progress"><span></span></p>' +
                '</li>'),

                $btns = $('<div class="file-panel">' +
                    '<span class="cancel">删除</span>' + '</div>').appendTo($li),
                $prgress = $li.find('p.progress span'),
                $wrap = $li.find('p.imgWrap'),
                $info = $('<p class="error"></p>'),

                showError = function(code) {
                    switch (code) {
                        case 'interrupt':
                            text = '上传暂停';
                            break;

                        default:
                            text = '上传失败，请重试';
                            break;
                    }

                    $info.text(text).appendTo($li);
                };

            if (file.getStatus() === 'invalid') {
                showError(file.statusText);
            } else {
                $wrap.text('不能预览');
                percentages[file.id] = [file.size, 0];
                file.rotation = 0;
            }

            file.on('statuschange', function(cur, prev) {
                if (prev === 'progress') {
                    $prgress.hide().width(0);
                } else if (prev === 'queued') {
                    $li.off('mouseenter mouseleave');
                    $btns.remove();
                }

                // 成功
                if (cur === 'error' || cur === 'invalid') {
                    showError(file.statusText);
                    percentages[file.id][1] = 1;
                } else if (cur === 'interrupt') {
                    showError('interrupt');
                } else if (cur === 'queued') {
                    percentages[file.id][1] = 0;
                } else if (cur === 'progress') {
                    $info.remove();
                    $prgress.css({
                        display: 'block',
                        width: '10%'
                    });
                } else if (cur === 'complete') {
                    $li.append('<span class="success"></span>');
                }

                $li.removeClass('state-' + prev).addClass('state-' + cur);
            });

            $li.on('mouseenter', function() {
                $btns.stop().animate({
                    height: 30
                });
            });

            $li.on('mouseleave', function() {
                $btns.stop().animate({
                    height: 0
                });
            });

            $btns.on('click', 'span', function() {
                uploader.removeFile(file);
            });

            $li.appendTo($queue);
        }
3352
function cssToSss (css, file) {
    if (path.extname(file) === '.css') {
      return postcss().process(css, { stringifier: sugarss }).then(function (result) {
        return result.css
      })
    } else {
      return css
    }
  }
1125687
function copyExamp(path,pathLength){
	fs.readdir(path,function(err, files){
		if(err){
			console.log('examples read dir err:' + path);
		}else{
			// 遍历目录下所有子项
			files.forEach(function(item){
				var tmpPath = path + '/' + item;
				fs.stat(tmpPath,function(err, stat){
					if(stat.isFile()){
						// 判断文件类型,如果是.html则转化
						var htmlIndex = item.indexOf('.html');
						var jsIndex = item.indexOf('.js');
						var cssIndex = item.indexOf('.css');
						if(htmlIndex < 0 && (jsIndex > -1 || cssIndex > -1)){
							// 创建读取流
		                    readable = fs.createReadStream( tmpPath );
		                    // 创建写入流
		                    writable = fs.createWriteStream( 'examples/' + tmpPath.substring(pathLength) );
		                    // 通过管道来传输流
		                    readable.pipe(writable);
						}
						if(htmlIndex > -1){
							fs.readFile(tmpPath,function(err,data){
								var htmlStr = '';
								if(err){
									console.log('read html err:' + tmpPath)
								}else{
									htmlStr = data.toString();
								}
								var ctx = 'http://design.yonyoucloud.com/static/'
								var tpl = [
							        '<!DOCTYPE html>',
							        '<html lang="en">',
							        '<head>',
							        '<meta charset="UTF-8">',
							        '<meta name="viewport" content="width=device-width, initial-scale=1">',
							       	'<title>Title</title>',
									'<link rel="stylesheet" href="'+ ctx +'/font-awesome/css/font-awesome.css">',
							       	'<link rel="stylesheet" type="text/css" href="'+ ctx +'/uui/latest/css/u.css">',
							       	'<link rel="stylesheet" type="text/css" href="'+ ctx +'/uui/latest/css/u-extend.css">',
								    '<link rel="stylesheet" type="text/css" href="'+ ctx +'/uui/latest/css/tree.css">',
							        '<link rel="stylesheet" type="text/css" href="'+ ctx +'/uui/latest/css/grid.css">',
							        '<link rel="stylesheet" type="text/css" href="widget.css">',
							        '</head>',
							        '<body>',
							        htmlStr,
							        '<script src="'+ ctx +'/jquery/jquery-1.11.2.js"></script>',
							    	'<script src="'+ ctx +'/knockout/knockout-3.2.0.debug.js"></script>',
							        '<script src="'+ ctx +'/uui/latest/js/u-polyfill.js"></script>',
							        '<script src="'+ ctx +'/uui/latest/js/u.js"></script>',
							        '<script src="'+ ctx +'/uui/latest/js/u-tree.js"></script>',
							        '<script src="'+ ctx +'/uui/latest/js/u-grid.js"></script>',
									'<script src="'+ ctx +'/requirejs/require.debug.js"></script>',
									'<script src="widget.js"></script>',
							        '</body>',
							        '</html>'
						        ]
					        	var tplStr = tpl.join('\r\n');
					        	fs.writeFile('examples/' + tmpPath.substring(pathLength),tplStr,function(err){
						        	if(err){
						        		console.log('write err:' + 'examples/' + item + '.html');
						        	}
						        })
					        })
						}
					}
					// 子项为目录创建目录
					if(stat.isDirectory()){
						var dirPath = 'examples/' + tmpPath.substring(pathLength);
						fs.exists(dirPath, function(exist) {
							if(!exist){
								fs.mkdirSync(dirPath);
							}
						});
						copyExamp(tmpPath,pathLength);
					}
				})
			})
		}
	})
}