创建打包上下文实例

@param {Object} ret 静态资源表
@constructor
504873
function Context(ret) {
    this.ret = ret;

    // 初始化文件列表
    var fileMap = this.filePathMap = ret.src;

    // 初始化资源映射表
    var fileIdMap = this.fileIdMap = {};
    var fileUrlMap = this.fileUrlMap = {};
    var files = this.files = [];
    Object.keys(fileMap).forEach(function (subpath) {
        var file = fileMap[subpath];
        files.push(file);
        fileIdMap[file.id] = file;
        if (file.release) {
            fileUrlMap[file.getUrl()] = file;
        }
    });
    this.resIdMap = {};
    this.root = fis.project.getProjectPath();
    this.requireConfig = getAmdConfig();
    this.moduleConfig = amdHelper.initModuleConfig(this.requireConfig, this.root);
    this.toPackItems = [];
}
110531
function rudePackager(ret, pack, settings, opt) {
  var files = ret.src;

  // 生成映射表，方便快速查找！
  var idmapping = ret.idmapping = {};
  var urlmapping = ret.urlmapping = {};
  Object.keys(files).forEach(function(subpath) {
    var file = files[subpath];
    idmapping[file.id] = file;
    if (file.release) {
      urlmapping[file.getUrl()] = file;
    }
  });

  Object.keys(files).forEach(function(subpath) {
    var file = files[subpath];

    compile(file);
  });

  function compile(file) {
    var processor = rudePackager.lang[file.loaderLang] || rudePackager.lang[settings.processor[file.ext]];

    // 非 htmlLike 或者 没有处理器，或者已经处理过了，则跳过。
    if (!file.isHtmlLike || file.loaderLang === false || !processor || file._resource) {
      return;
    }

    // 可以让 processor 调用。
    processor._compile = compile;

    // 修改之前先，先备份。
    file._rudeBackup = file.getContent();

    var resource = createResource(ret, file);
   // console.log(resource);


    file._resource = resource;
    processor.init && processor.init(file, resource, settings);

    // all in one 包含异步依赖。
    if (settings.allInOne && settings.allInOne.includeAsyncs) {
      // 把所以异步的 js 当同步加载。
      resource.res.forEach(function(item) {
        item.async = false;
      });
    }

    processor.beforePack && processor.beforePack(file, resource, settings);

    if (settings.allInOne) {
      allInOnePack(file, resource, ret, settings.allInOne === true ? {} : settings.allInOne);
    }

    processor.before && processor.before(file, resource, settings);
    processor(file, resource, settings);
    processor.after && processor.after(file, resource, settings);

    ret.pkg[file.subpath] = file;

  }
}
388177
function respondWithFile(req, res, path, ifNoFile) {
  ifNoFile = ifNoFile || function() {};
  // We use `documentRoot` as the root wherein we seek files.
  var realpath = protectedPath(req.server.documentRoot, path);
  fs.stat(realpath, function(err, stats) {
    if (err) return ifNoFile();

    if (stats.isDirectory()) {
      realpath = p.join(realpath, 'index.html');
    }
    res.mime(p.extname(realpath).slice(1));

    // Cache management (compare timestamps at second-level precision).
    var lastModified = Math.floor(stats.mtime / 1000);
    var since = req.headers['if-modified-since'];
    if (since && (lastModified <= Math.floor(new Date(since) / 1000))) {
      res.statusCode = 304; // not modified.
      res.end();
      return;
    }
    res.setHeader('Last-Modified', stats.mtime.toUTCString());

    // Connect the output of the file to the network!
    var raw = fs.createReadStream(realpath);
    raw.on('error', function(err) {
      log(err.stack, 'error');
      res.statusCode = 404;
      res.end('Not Found\n');
    });
    raw.pipe(res.compressed());
  });
}
849462
function reload_file(arg_file_path)
{
	const file_name = path.basename(arg_file_path)
	const this_file_name = path.basename(__filename)
	if (file_name == this_file_name)
	{
		console.info('Need to reload after change on ' + this_file_name)
		return
	}
	
	const exts = ['.js', '.json']
	const ext = path.extname(arg_file_path)
	const full_path = path.resolve(arg_file_path)
	
	if ((exts.indexOf(ext) > -1) && (full_path in require.cache))
	{
		console.info('Reloading: ' + full_path)
		// console.log(require.cache[full_path].parent.children[0])
		
		delete require.cache[full_path]
		require(full_path)
	}
}
581236
function(evt) {
    $('output').innerHTML = '';
    $('result').innerHTML = '';
    oMX.Init(); /* begin with new objects */
    fls = [];
    var cnt = 0;
    var files = evt.target.files; /* FileList object */
    for (var i = 0; i < files.length; i++) { /* loop the selected files */
      var reader = new FileReader();
      reader.onload = function(file) {
        fls[cnt + 1] = oMX.AddFile(file) ? true : false;  /* get a file */
        var c = $('result').innerHTML;
        if (c !== '') {
          c += ', ';
        }
        $('result').innerHTML = c + fls[cnt];
        cnt += 2;
      };
      fls.push(files[i].name, null);
      reader.readAsText(files[i]);
    }
  }
1241731
function relative(a, b, stat) {
  if (typeof a !== 'string') {
    throw new TypeError('relative expects a string.');
  }

  if (a == '' && !b) return a;

  var len = arguments.length;
  if (len === 1) {
    b = a; a = process.cwd(); stat = null;
  }

  if (len === 2 && typeof b === 'boolean') {
    b = a; a = process.cwd(); stat = true;
  }

  if (len === 2 && typeof b === 'object') {
    stat = b; b = a; a = process.cwd();
  }

  var origB = b;

  // see if a slash exists before normalizing
  var slashA = endsWith(a, '/');
  var slashB = endsWith(b, '/');

  a = unixify(a);
  b = unixify(b);

  // if `a` had a slash, add it back
  if (slashA) { a = a + '/'; }

  if (isFile(a, stat)) {
    a = path.dirname(a);
  }

  var res = path.relative(a, b);
  if (res === '') {
    return '.';
  }

  // if `b` originally had a slash, and the path ends
  // with `b` missing a slash, then re-add the slash.
  var noslash = trimEnd(origB, '/');
  if (slashB && (res === noslash || endsWith(res, noslash))) {
    res = res + '/';
  }
  return res;
}
408301
async function scanFile (dir, ext, ret_absolute)
{
return new Promise( async function(resolve, reject){
    // console.log(dir);
    fs.readdir(dir, function(err, files){
        let file_arr = [];
        if( ! files ){
            return resolve(file_arr);
        }
        files.forEach(function(elm){
            if( elm.indexOf('.') > -1 ){
                if( !ext || '.'+ext.toUpperCase()==path.extname(elm).toUpperCase() ){
                    // 返回全路径
                    if( ret_absolute ){
                        elm = path.join(dir, elm);
                    }
                    // 检查文件后缀名
                    file_arr.push(elm);
                }
            }
        });
        resolve(file_arr);
    });
});
}
1226672
public function builder($ret, $data, $msg = '', $format = 'json')
    {
        @header('Content-type: application/json; charset=utf-8');
        $this->ret  = strval($ret);
        $this->time = time();
        $this->msg  = $msg;
        $this->data = $data;
        $this->format = $format;
    }
851677
function(rel, key, val, callback) {
    if (typeof key == 'function') {
      callback = key;
      key = val = undefined;
    }

    if (Array.isArray(rel)) {
      var txn = this._safeBatch();
      var args = [key, val];
      async.map(rel, naan.ecurry(txn.rel.update, args, [1, 2]), callback);
      return this._safeBatchCommit(txn);
    }

    var id = this._getId(rel);

    if (!this._isValidId(id)) {
      return callback(new Error("Invalid ID"));
    }

    var endpoint = util.format('%s/properties', this._relRoot(id));
    if (key) endpoint += '/' + key;

    var op = this.operation(endpoint, 'PUT', key ? val : rel.properties);
    this.call(op, function(err) {
      callback(err);
    });
  }
1319305
function(file, opts) {
	if (util.isObject(file) || util.isArray(file)) {
		return file;
	}

	var options = util.extend({
		asText: false, // true, false, 'pretty'
		javascript: false, // true, false
		scope: '', // directory to look for initial file
		variables: {
			// contains a key->value object with variables to @extends
		}
	}, opts);

	file = util.template(file, options.variables);

	/*****************************************************************************
	*  Initialize
	*****************************************************************************/

	var file_path;

	// If the file path is absolute use it
	// If not then prepend the current scope of the previous file.
	if (path.resolve(file) === path.normalize(file)) {
		file_path = path.normalize(file);
	}
	else {
		file_path = path.normalize(
			options.scope ? options.scope + '/' + file : file
		);
	}
	var class_json = parseFile(file_path, options);

	// Stores JSON objects of files that have to be merged together:
	// ["a", "b"]
	var file_list = util.isArray(class_json[indicators.EXTENDS]) ?
		class_json[indicators.EXTENDS] :
		class_json[indicators.EXTENDS] != null ?
			[ class_json[indicators.EXTENDS] ] :
			[];

	// Delete @extends from base_json to avoid infinitive recursion
	delete class_json[indicators.EXTENDS];

	// Push class_json to the path list:
	file_list.push(class_json);
	/*****************************************************************************
	*  Merge file by file
	*****************************************************************************/

	// default config for each file required:
	// set asText = false so we get an object returned
	// set scope = file's directory so there can be relative references
	var json_config = util.defaults({
		asText: false,
		scope: path.dirname(file_path),

		// _as is a hack so that we know its we are calling the function recursive
		_as: ANTI_SANITIZER
	}, options);

	// super_json is our output, start by containing first file in array
	var super_json = fromFile(file_list.shift(), json_config);

	// TODO: Figure out when to sanitize super_json hopefully we don't have to
	//   santize all returns. I'm not sure about this, and I'm not sure if we
	//   can even sanitize super_json when we return it.
	//   Is super_json used by anyone recursively?

	while (file_list.length) {
		var json = fromFile(file_list.shift(), json_config);

		merge(super_json, json);
	}

	// If this file is called from the outside eg json_merger.from...
	//   File('file_which_doesnt_extends_another_file.json')
	//   we need to sanitize the file and remove all indicators
	if (options._as != ANTI_SANITIZER) {
		super_json = util.sanitizeValue(super_json);
	}

	/*****************************************************************************
	*  Return super_json
	*****************************************************************************/
	if (options.asText) {
		return stringify(super_json, options);
	}
	else {
		return super_json;
	}
}
1096358
function inlineFileRegHandle(regFiles, buildInfo, options, reqModuleJS, file) {        
        var content = '';
        if(regFiles && regFiles.length) {
            var destMP = {'.js':options.jsDestPath,'.css':options.cssDestPath};
            for(var j=0;j<regFiles.length;j++) {
                var jp = regFiles[j].trim().replace(/(^['"]*)|(['"]*$)/g, '');               
                if(!jp) continue;
                //去除?之后面路径
                if(jp.indexOf('?') > -1) jp = jp.substr(0, jp.indexOf('?'));

                if(jp[0] == '/') {
                    //相对于当前根路径
                    var filepath = path.join(options.destPath, jp);
                }
                //相对于js构建目标目录
                else if(jp[0] != '.') { 
                    var ext = path.extname(jp).toLowerCase();
                    var dest = destMP[ext] || options.destPath;
                    var filepath = path.join(dest, jp);
                    
                    //如果不存在，则相对于当前html发布路径
                    if(!fs.existsSync(filepath)) {                        
                        filepath = path.join(options.dest, jp); 
                    }//如果不存在，则相对于当前根发布路径
                    if(!fs.existsSync(filepath) && options.destPath) {                        
                        filepath = path.join(options.destPath, jp); 
                    }                              
                    //如果文件还是不存在，则相对于项目发布路径
                    if(!fs.existsSync(filepath)) {
                        console.log(filepath + ' not exists, check dest path!');
                        //相对于当前html文件                  
                        filepath = path.join(path.dirname(file.path), jp); 
                    }
                }
                else {
                    //相对于当前html路径
                    var filepath = path.join(options.dest, jp);
                }
                //读取内联的文件内容
                content += readInlineContent(filepath, buildInfo, reqModuleJS, options) + '\n';
            }
        }
        return content;
    }
1047058
function expandToObject(input) {
    // If the input is a string, encapsulate it as an array
    var retObj = input;
    if (typeof retObj === 'string') {
      retObj = [input];
    }

    // If the retObj is an array
    if (Array.isArray(retObj)) {
      // Collect the inputs into an object
      var inputArr = retObj;
      retObj = {};

      // Iterate over the inputs
      inputArr.forEach(function (inputStr) {
        // Break down any brace exapansions
        var inputPaths = braceExpand(inputStr);

        // Iterate over the paths
        inputPaths.forEach(function (filepath) {
          // Grab the extension and save it under its key
          // TODO: Deal with observer pattern here.
          // TODO: Will probably go `classical` here
          var ext = path.extname(filepath).slice(1);
          retObj[ext] = filepath;
        });
      });
    }

    // Return the objectified src
    return retObj;
  }
957630
function createDir(srcPath, desPath) {
    var pathInfo = path.parse(desPath);
    var searchvalue = pathInfo.root[pathInfo.root.length - 1]
    var start = 0;
    var found = pathInfo.dir.indexOf(searchvalue);
    var subPath = '';
    var dirs = [];

    if (found != -1) {
        while (true) {
            subPath = pathInfo.dir.substr(start, found - start + 1);
            if (subPath != '') {
                dirs.push(subPath);
            }
            start = found + 1;
            found = pathInfo.dir.indexOf(searchvalue, start);
            if (found == -1) {
                if (start < pathInfo.dir.length) {
                    dirs.push(pathInfo.dir.substr(start));
                }
                break;
            }
        }
    }

    subPath = '';
    dirs.forEach(function (dir, num) {
        subPath += dir;
        if (!fs.existsSync(subPath)) {
            try {
                fs.mkdirSync(subPath);
            } catch (e) {
                if (e.code != 'EEXIST') {
                    console.log('[error] ', e);
                };
            }
            console.log('[info] create  dir:', subPath);
        }
        if (num == dirs.length - 1 && pathInfo.base != '') {
            copyFile(srcPath, desPath);
            //console.log('src file:', srcPath);
            //console.log('des file:', desPath);
        }
    });

}
129838
function DocFile (file, contents) {
	this.uri = file;
	this.dir = path.dirname(file);
	this.filename = path.basename(file);
	this.name = this.filename.replace(/\.js$/, '');
	this.contents = contents;
	this.comments = [];
	
	this.process();
}
84923
def fire_ret_load(self, load):
        '''
        
        '''
        if load.get('retcode') and load.get('fun'):
            if isinstance(load['fun'], list):
                # Multi-function job
                if isinstance(load['retcode'], list):
                    multifunc_ordered = True
                else:
                    multifunc_ordered = False

                for fun_index in range(0, len(load['fun'])):
                    fun = load['fun'][fun_index]
                    if multifunc_ordered:
                        if (len(load['retcode']) > fun_index and
                                load['retcode'][fun_index] and
                                fun in SUB_EVENT):
                            # Minion fired a bad retcode, fire an event
                            self._fire_ret_load_specific_fun(load, fun_index)
                    else:
                        if load['retcode'].get(fun, 0) and fun in SUB_EVENT:
                            # Minion fired a bad retcode, fire an event
                            self._fire_ret_load_specific_fun(load, fun_index)
            else:
                # Single-function job
                if load['fun'] in SUB_EVENT:
                    # Minion fired a bad retcode, fire an event
                    self._fire_ret_load_specific_fun(load)
877846
function readRecursive (base, pattern, ignore, result, read) {
  const files = fs.readdirSync(base)
  result = result || []

  files.forEach(file => {
    const newBase = path.join(base, file)
    if (fs.statSync(newBase).isDirectory()) {
      result = readRecursive(newBase, pattern, ignore, result, read)
    } else if (mm([file], pattern, { ignore }).length) {
      const details = {
        base,
        name: file,
        ext: path.extname(newBase),
        size: fs.statSync(newBase).size
      }

      if (read) {
        details.content = fs.readFileSync(newBase)
      }

      result.push(details)
    }
  })

  return result
}
494665
function loadFile(file) {
    console.log('loadFile:', file);

    // <file> can be Image, File URL object or URL string (http://* or data:image/*)
    rasterToGcode.load(file).then(function(rtg) {
        console.log('rasterToGcode:', rtg);
    })
    .catch(function(error) {
        console.error('error:', error);
    });
}