Downloads the results of the latest compilation of the project
@param {Project} project
@param {string} outputDir
@return {Promise<void>}
192077
function downloadProjectCompilations(project, outputDir) {
	const promises = [];
	for (const platform in project.compilations) {
		if (!project.compilations.hasOwnProperty(platform)) {
			continue;
		}
		promises.push(downloadProjectCompilation(project, platform, outputDir).catch(() => {
			return undefined;
		}));
	}
	return Promise.all(promises);
}
659443
def download_file(self, project, path):
        

        url = self._getUrl("/projects/{}/files/{}".format(project.id, path))
        response = yield from self._session().request("GET", url, auth=self._auth)
        if response.status == 404:
            raise aiohttp.web.HTTPNotFound(text="{} not found on compute".format(path))
        return response
1147142
function(inDir, outDir, relativePath, newCache) {
    var ext = this._matchingFileExtension(relativePath);
    var moduleName = relativePath.slice(0, relativePath.length - (ext.length + 1));
    var fullInputPath = path.join(inDir, relativePath);
    var fullOutputPath = path.join(outDir, moduleName + '.' + this.targetExtension);

    var entry = this._transpileThroughCache(
      moduleName,
      fs.readFileSync(fullInputPath, 'utf-8'),
      newCache
    );

    mkdirp.sync(path.dirname(fullOutputPath));
    fs.writeFileSync(fullOutputPath, entry.output);
  }
231775
async function runProgram() {
    const args = minimist(process.argv.slice(2));

    if (args.prefix) {
        intercept(function(txt) {
            return `[${pkg.name}]\n${txt}`;
        });
    }

    let latest = await latestVersion(pkg.name, { version: `>${pkg.version}` })
                        .catch(error => pkg.version);
    if (semver.gt(latest, pkg.version)) {
        process.stderr.write(chalk.default.white(`\n     Update available `));
        process.stderr.write(chalk.default.grey(`${pkg.version}`));
        process.stderr.write(chalk.default.white(` -> `));
        process.stderr.write(chalk.default.greenBright(`${latest}\n`));
        process.stderr.write(chalk.default.white(`     Run `));
        process.stderr.write(chalk.default.blueBright(`npm i -g ${pkg.name} `));
        process.stderr.write(chalk.default.white(`to update.\n`));
    }

    if (args.version || args.v) {
        process.stdout.write(pkg.version);
        return 0;
    }

    if (args.h || args.help) {
        help(process.stdout);
        return 0;
    }

    if (args.f || args.folder) {
        let inputDir = args.f.trim();
        let outputDir = (args.o || args.out_folder) ? args.o.trim() : "./";
        if (outputDir.substr(0, 2) === "./") {
            outputDir = path.resolve(process.cwd(), outputDir.substr(2))
        }
        const len = await processFiles(inputDir, outputDir);
        process.stdout.write(chalk`{green Successfully wrote ${len} files}\n`);
        return len;
    }
    else {
        const fileContents = await getInput(args);
        if (fileContents) {
            const activities = await chatdown(fileContents, args);
            const writeConfirmation = await writeOut(activities, args);

            if (typeof writeConfirmation === 'string') {
                process.stdout.write(chalk`{green Successfully wrote file:} {blue ${writeConfirmation}}\n`);
            }
            return 0;
        }
        else {
            help();
            return -1;
        }
    }
}
736097
function(promise, result, output, isProgress) {
				var element = document.createElement("div"); //$NON-NLS-0$

				var waitCount = 0;
				var successFn = function(file) {
					this.callback = function() {
						var string = i18nUtil.formatMessage(
							messages["WroteMsg"],
							typeof(file) === "string" ? file : this.shellPageFileService.computePathString(file)); //$NON-NLS-0$
						var writer = new mResultWriters.ShellStringWriter(element);
						writer.write(string + "\n"); //$NON-NLS-0$
						if (--waitCount !== 0 || isProgress) {
							promise.progress(element);
						} else {
							promise.resolve(element);
						}
					}.bind(this);
					return this;
				}.bind(this);
				var errorFn = function(file) {
					this.callback = function(error) {
						var string = i18nUtil.formatMessage(
							messages["WriteFailMsg"],
							typeof(file) === "string" ? file : this.shellPageFileService.computePathString(file)); //$NON-NLS-0$
						string += " [" + error + "]"; //$NON-NLS-1$ //$NON-NLS-0$
						var writer = new mResultWriters.ShellStringWriter(element);
						writer.write(string + "\n"); //$NON-NLS-0$
						if (--waitCount !== 0 || isProgress) {
							promise.progress(element);
						} else {
							promise.resolve(element);
						}
					}.bind(this);
					return this;
				}.bind(this);

				var destination = output || this.shellPageFileService.getCurrentDirectory();
				waitCount++;
				this.shellPageFileService.ensureDirectory(null, destination).then(
					function(directory) {
						waitCount--;

						var files = result.getValue();
						if (!result.isArray()) {
							files = [files];
						}
						files.forEach(function(file) {
							waitCount++;
							var pathSegments = file.path.split(this.shellPageFileService.SEPARATOR);

							/* normalize instances of '.' and '..' in the path */
							var index = 0;
							while (index < pathSegments.length) {
								var segment = pathSegments[index];
								if (segment === ".") { //$NON-NLS-0$
									pathSegments.splice(index, 1);
								} else if (segment === "..") { //$NON-NLS-0$
									if (index === 0) {
										/* invalid, destination must be a descendent of the cwd */
										errorFn(i18nUtil.formatMessage(messages["WriteFailNotDescendentOfOutputDir"], file.path));
										return;
									}
									pathSegments.splice(index-- - 1, 2);
								} else {
									index++;
								}
							}

							var writeFile = function(parentNode, fileToWrite, pathSegments) {
								var segment = pathSegments[0];
								pathSegments.splice(0,1);
								var nodeString = this.shellPageFileService.computePathString(parentNode) + this.shellPageFileService.SEPARATOR + segment;
								if (pathSegments.length === 0) {
									/* attempt to write the new resource */
									if (fileToWrite.isDirectory) {
										this.shellPageFileService.ensureDirectory(parentNode, segment).then(successFn(nodeString).callback, errorFn(nodeString).callback);
									} else {
										this.shellPageFileService.ensureFile(parentNode, segment).then(
											function(file) {
												var writer = new mResultWriters.FileBlobWriter(file, this.shellPageFileService);
												writer.addBlob(fileToWrite.blob);
												writer.write().then(successFn(file).callback, errorFn(file).callback);
											}.bind(this),
											errorFn(nodeString).callback
										);
									}
									return;
								}
								/* more lead-up path segments to go */
								this.shellPageFileService.ensureDirectory(parentNode, segment).then(
									function(newNode) {
										writeFile(newNode, fileToWrite, pathSegments);
									},
									errorFn(this.shellPageFileService.computePathString(parentNode) + this.shellPageFileService.SEPARATOR + segment).callback
								);
							}.bind(this);
							writeFile(directory, file, pathSegments);
						}.bind(this));
					}.bind(this),
					errorFn(destination).callback
				);
			}
871758
function getOutputDir(output) {
  var arr = output.split(path.sep);
  arr.pop();
  return arr.join(path.sep);
}
1113632
function(project) {
        if(project.slug.toLowerCase() === 'obs'
            || project.slug.toLowerCase() === 'bible-obs'
            || project.slug.toLowerCase() === 'bible'
            || !project.chunks_url) return Promise.resolve();


        return request.read(project.chunks_url)
            .then(function(response) {
                // consume chunk data
                if(response.status !== 200) return Promise.reject(response);

                let data;
                try {
                    data = JSON.parse(response.data);
                } catch(err) {
                    console.log(project);
                    return Promise.reject(err);
                }

                try {
                    let language_id = library.addSourceLanguage({
                        slug: 'en',
                        name: 'English',
                        direction: 'ltr'
                    });

                    // TODO: retrieve the correct versification name(s) from the source language
                    let versification_id = library.addVersification({
                        slug: 'en-US',
                        name: 'American English'
                    }, language_id);


                    if (versification_id > 0) {
                        for (let chunk of data) {
                            library.addChunkMarker({
                                chapter: padSlug(chunk.chp, 2),
                                verse: padSlug(chunk.firstvs, 2)
                            }, project.slug, versification_id);
                        }
                    }
                } catch (err) {
                    return Promise.reject(err);
                }
            });
    }
1058317
function compileProject(project) {
	return project.compile()
	.catch((error) => {
		console.error("Project " + project.name + " with ID: " + project.id + " couldn't be compiled.");
		console.trace(error);
		throw error;
	});
}
556715
function(project) {
        return request.read(project.resourceUrl)
            .then(function(response) {
                // consume resource data
                if(response.status !== 200) return Promise.reject(response);

                let data;
                try {
                    data = JSON.parse(response.data);
                } catch(err) {
                    return Promise.reject(err);
                }

                for(let resource of data) {
                    try {
                        resource.slug = resource.slug.toLowerCase();
                        switch (resource.slug) {
                            case 'obs':
                            case 'ulb':
                                resource.status.translate_mode = 'all';
                                break;
                            default:
                                resource.status.translate_mode = 'gl';
                        }

                        resource.status.pub_date = resource.status.publish_date;
                        resource.translation_words_assignments_url = resource.tw_cat;
                        resource.type = 'book';
                        resource.formats = [{
                            package_version: rc.tools.spec.version,
                            mime_type: rc.tools.typeToMime('book'),
                            modified_at: resource.date_modified,
                            imported: 0,
                            url: resource.source
                        }];
                        library.addResource(resource, project.id);

                        // coerce notes to resource
                        let helpResource = {
                            slug: 'tn',
                            name: 'translationNotes',
                            type: 'help',
                            status: resource.status,
                            formats: [{
                                package_version: rc.tools.spec.version,
                                mime_type: rc.tools.typeToMime('help'),
                                modified_at: resource.date_modified,
                                imported: 0,
                                url: resource.notes
                            }]
                        };
                        helpResource.status.translate_mode = 'gl';
                        helpResource.status.source_translations = [{
                            language_slug: project.source_language_slug,
                            resource_slug: 'tn',
                            version: resource.status.version
                        }];
                        if (resource.notes) {
                            library.addResource(helpResource, project.id);
                        }

                        // coerce questions to resource
                        helpResource.slug = 'tq';
                        helpResource.name = 'translationQuestions';
                        helpResource.formats = [{
                            package_version: rc.tools.spec.version,
                            mime_type: rc.tools.typeToMime('help'),
                            modified_at: resource.date_modified,
                            imported: 0,
                            url: resource.checking_questions
                        }];
                        helpResource.status.source_translations = [{
                            language_slug: project.source_language_slug,
                            resource_slug: 'tq',
                            version: resource.status.version
                        }];
                        if (resource.checking_questions) {
                            library.addResource(helpResource, project.id);
                        }

                        // add words project (this is insert/update so it will only be added once)
                        // TRICKY: obs tw has not been unified with bible tw yet so we add it as separate project.
                        let wordsProjectId = library.addProject({
                            slug: project.slug === 'obs' ? 'bible-obs' : 'bible',
                            name: 'translationWords' + (project.slug === 'obs' ? ' OBS' : ''),
                            desc: '',
                            icon: '',
                            sort: 100,
                            chunks_url: '',
                            categories: []
                        }, project.source_language_id);

                        // add resource to words project
                        let dictResource = _.clone(helpResource);
                        dictResource.slug = 'tw';
                        dictResource.name = 'translationWords';
                        dictResource.type = 'dict';
                        dictResource.formats = [{
                            package_version: rc.tools.spec.version,
                            mime_type: rc.tools.typeToMime('dict'),
                            modified_at: resource.date_modified,
                            imported: 0,
                            url: resource.terms
                        }];
                        dictResource.status.source_translations = [{
                            language_slug: project.source_language_slug,
                            resource_slug: 'tw',
                            version: resource.status.version
                        }];
                        if (resource.terms) {
                            library.addResource(dictResource, wordsProjectId);
                        }
                    } catch (err) {
                        return Promise.reject(err);
                    }
                }
            });
    }
130360
function mkdirSync(dirPath) {
    // Get relative path to output
    const relativePath = dirPath.replace(`${CWD}${pathSep}`, '');
  	const dirs = relativePath.split(pathSep);
  	let currentDir = CWD;

    // Check if each dir exists, and if not, create it
    dirs.forEach(dir => {
      currentDir = path.resolve(currentDir, dir);
      if(!fs.existsSync(currentDir)) {
        fs.mkdirSync(currentDir);
      }
    });
  }
7460
function download(source, { verbose, output, onStart, onProgress } = {}) {
  return new Promise(function(y, n) {
    if (typeof output === 'undefined') {
      output = path.basename(url.parse(source).pathname) || 'unknown';
    }

    /**
     * Parse the source url into parts
     */
    const sourceUrl = url.parse(source);

    /**
     * Determine to use https or http request depends on source url
     */
    let request = null;
    if (sourceUrl.protocol === 'https:') {
      request = https.request;
    } else if (sourceUrl.protocol === 'http:') {
      request = http.request;
    } else {
      throw new Error('protocol should be http or https');
    }

    /**
     * Issue the request
     */
    const req = request(
      {
        method: 'GET',
        protocol: sourceUrl.protocol,
        host: sourceUrl.hostname,
        port: sourceUrl.port,
        path: sourceUrl.pathname + (sourceUrl.search || '')
      },
      function(res) {
        if (res.statusCode === 200) {
          const fileSize = Number.isInteger(res.headers['content-length'] - 0)
            ? parseInt(res.headers['content-length'])
            : 0;
          let downloadedSize = 0;

          /**
           * Create write stream
           */
          var writeStream = fs.createWriteStream(output, {
            flags: 'w+',
            encoding: 'binary'
          });

          res.pipe(writeStream);

          /**
           * Invoke `onStartCallback` function
           */
          if (onStart) {
            onStart(res.headers);
          }

          res.on('data', function(chunk) {
            downloadedSize += chunk.length;
            if (onProgress) {
              onProgress({
                fileSize,
                downloadedSize,
                percentage: fileSize > 0 ? downloadedSize / fileSize : 0
              });
            }
          });

          res.on('error', function(err) {
            writeStream.end();
            n(err);
          });

          writeStream.on('finish', function() {
            writeStream.end();
            req.end('finished');
            y({ headers: res.headers, fileSize });
          });
        } else if (
          res.statusCode === 301 ||
          res.statusCode === 302 ||
          res.statusCode === 307
        ) {
          const redirectLocation = res.headers.location;

          if (verbose) {
            console.log('node-wget-promise: Redirected to:', redirectLocation);
          }

          /**
           * Call download function recursively
           */
          download(redirectLocation, {
            output,
            onStart,
            onProgress
          })
            .then(y)
            .catch(n);
        } else {
          n('Server responded with unhandled status: ' + res.statusCode);
        }
      }
    );

    req.end('done');
    req.on('error', err => n(err));
  });
}
384035
function downloadCode(db, codePath) {
  return mkdir(codePath)
    .then(() => db.code.loadModules())
    .then((modules) => Promise.all(modules.map(module => downloadCodeModule(db, module, codePath))));
}
960393
async function copy() {
  await makeDir('build');
  await Promise.all([
    writeFile(
      'build/package.json',
      JSON.stringify(
        {
          private: true,
          engines: pkg.engines,
          dependencies: pkg.dependencies,
          scripts: {
            start: 'node server.js',
          },
        },
        null,
        2,
      ),
    ),
    copyFile('LICENSE.txt', 'build/LICENSE.txt'),
    copyFile('yarn.lock', 'build/yarn.lock'),
    copyDir('public', 'build/public'),
  ]);

  if (process.argv.includes('--watch')) {
    const watcher = chokidar.watch(['public/**/*'], { ignoreInitial: true });

    watcher.on('all', async (event, filePath) => {
      const start = new Date();
      const src = path.relative('./', filePath);
      const dist = path.join(
        'build/',
        src.startsWith('src') ? path.relative('src', src) : src,
      );
      switch (event) {
        case 'add':
        case 'change':
          await makeDir(path.dirname(dist));
          await copyFile(filePath, dist);
          break;
        case 'unlink':
        case 'unlinkDir':
          cleanDir(dist, { nosort: true, dot: true });
          break;
        default:
          return;
      }
      const end = new Date();
      const time = end.getTime() - start.getTime();
      console.info(`[${format(end)}] ${event} '${dist}' after ${time} ms`);
    });
  }
}
906796
function outputVersion () {
  fs.readFile(path.join(__dirname, '/../package.json'), function (err, data) {
    if (err) {
      console.log(err.toString())
    } else {
      const pkg = JSON.parse(data)
      const version = pkg && pkg.version ? pkg.version : 'unknown'
      console.log(version)
    }
    process.exit(0)
  })
}
810598
function npmInstall(path, success){

      var deferred = Q.defer();

      // 'success' is a flag passed from the perform cmd function which states whether the function ran
      if(success === false){
        deferred.resolve(success);
        return deferred.promise;
      }

      var hasPackage = grunt.file.isFile(path+'/package.json');

      if(options.npmInstall === true && hasPackage){

        var msg = '---> Install npm dependencies ==> '+path;
        var execString = 'cd '+path+' && npm install';

        grunt.log.writeln(msg);

        var child = exec(execString);

        // add events for logging
        child.stdout.on('data', function(data) {
          grunt.log.writeln(data);
        });
        child.stderr.on('data', function(data) {
          grunt.verbose.writeln(data);
        });
        child.on('close', function(code) {
          deferred.resolve(success);
        });

      }else{

        if(options.npmInstall === true) {
          var msg = '---> Skipping npm install as no package JSON was detected ==> ' + path;
          grunt.log.writeln(msg);
        }

        deferred.resolve();
      }


      return deferred.promise;

    }
107610
function watchjs(sources, outdir, outfile, opt_options) {
  var bundler = watchify(browserify({
    entries: sources,
    debug: false,
    // Watchify options:
    cache: {},
    packageCache: {},
    fullPaths: true
  }));

  bundler.on('update', function() {
    gutil.log('recompiling js...');
    rebundle_(bundler, outdir, outfile, opt_options);
    gutil.log('finished recompiling js');
  });
  return rebundle_(bundler, outdir, outfile, opt_options);
}
704607
def download_cli(directory, master_token=None, member=None, access_token=None,
                 source=None, project_data=False, max_size='128m',
                 verbose=False, debug=False, memberlist=None,
                 excludelist=None, id_filename=False):
    
    return download(directory, master_token, member, access_token, source,
                    project_data, max_size, verbose, debug, memberlist,
                    excludelist, id_filename)