示例#1
0
 return new Promise(function(resolve, reject) {
   if (!self.workspace) {
     var workspace;
     var workspaceSetting = config.get('mm_workspace');
     logger.debug('Workspace not specified, retrieving base workspace: ');
     logger.debug(workspaceSetting);
     if (_.isArray(workspaceSetting)) {
       workspace = workspaceSetting[0];
     } else if (_.isString(workspaceSetting)) {
       workspace = workspaceSetting;
     }
     if (workspace && !fs.existsSync(workspace)) {
       fs.mkdirSync(workspace);
     }
     self.workspace = workspace;
     logger.debug('workspace set to: '+self.workspace);
   } else if (!fs.existsSync(self.workspace)) {
     fs.mkdirSync(self.workspace);
   }
   if (!self.workspace) {
     throw new Error('Could not set workspace for new project');
   }
   self.path = path.join(self.workspace, self.name);
   if (fs.existsSync(self.path)) {
     reject(new Error('Directory already exists!'));
   } else {
     self.id = uuid.v1();
     resolve(self.id);
   }
 });
示例#2
0
Project.prototype._isValid = function() {
  if (this.path !== undefined) {
    return fs.existsSync(path.join(this.path, 'config', '.settings'));
  } else if (this.workspace !== undefined && this.name !== undefined) {
    return fs.existsSync(path.join(this.workspace, this.name, 'config', '.settings'));
  } else {
    return fs.existsSync(path.join(process.cwd(),'config', '.settings'));
  }
};
示例#3
0
 .then(function(retrieveResult) {
   fileProperties = retrieveResult.fileProperties;
   if (fs.existsSync(path.join(self.path, 'unpackaged'))) {
     fs.renameSync(path.join(self.path, 'unpackaged'), path.join(self.path, 'src'));
   }
   // TODO: ensure packages write properly
   return self._initConfig();
 })
示例#4
0
 .catch(function(error) {
   // remove directory from workspace if we encounter an exception along the way
   logger.error('Could not retrieve and write project to file system: '+error.message);
   logger.error(error.stack);
   if (fs.existsSync(self.path)) {
     fs.removeSync(self.path);
   }
   reject(error);
 })
示例#5
0
 .then(function(retrieveResult) {
   logger.debug('retrieve result: ');
   logger.debug(retrieveResult);
   fileProperties = retrieveResult.fileProperties;
   if (fs.existsSync(path.join(self.path, 'unpackaged'))) {
     fs.removeSync(path.join(self.path, 'unpackaged'));
   }
   self.id = uuid.v1();
   return self._initConfig();
 })
示例#6
0
 .on('error', function (error) {
   if (fs.existsSync(tmpZipLocation)) {
     fs.removeAsync(tmpZipLocation)
       .then(function() {
         reject(error);
       })
       .catch(function(err) {
         reject(err);
       });
   }
 })
示例#7
0
 .on('error', function (error) {
   logger.error('error writing zip to disk', error);
   if (fs.existsSync(tmpZipLocation)) {
     fs.removeAsync(tmpZipLocation)
       .then(function() {
         reject(error);
       })
       .catch(function(err) {
         reject(err);
       });
   }
 })
示例#8
0
 unzipCommand.stderr.on('data', function (data) {
   logger.error('ERR unzipping:');
   logger.error(data);
   if (fs.existsSync(tmpZipLocation)) {
     fs.removeAsync(tmpZipLocation)
       .then(function() {
         return reject(new Error('Could not extract and write stream to file system.'));
       })
       .catch(function(err) {
         return reject(err);
       });
   }
 });
示例#9
0
  return new Promise(function(resolve, reject) {
    var fileProperties;
    if (fs.existsSync(self.path)) {
      reject(new Error('Project with this name already exists in the specified workspace.'));
    } else {
      if (!self.package) {
        // if user has not specified package, add standard developer objects to package
        self.package = [
          'ApexClass', 'ApexComponent', 'ApexPage', 'ApexTrigger', 'StaticResource'
        ];
      }
      self.sfdcClient.describe()
        .then(function(describe) {
          return self.setDescribe(describe);
        })
        .then(function() {
          self.path = path.join(self.workspace, self.name);
          fs.mkdirSync(self.path);
          fs.mkdirSync(path.join(self.path, 'config'));
          return self.sfdcClient.retrieveUnpackaged(self.package, true, self.path);
        })
        .then(function(retrieveResult) {
          fileProperties = retrieveResult.fileProperties;
          if (fs.existsSync(path.join(self.path, 'unpackaged'))) {
            fs.renameSync(path.join(self.path, 'unpackaged'), path.join(self.path, 'src'));
          }
          // TODO: ensure packages write properly
          return self._initConfig();
        })
        .then(function() {
          logger.debug('initing local store ... ');
          logger.debug(fileProperties);

          return self._writeLocalStore(fileProperties);
        })
        .then(function() {
          resolve();
        })
        .catch(function(error) {
          // remove directory from workspace if we encounter an exception along the way
          logger.error('Could not retrieve and write project to file system: '+error.message);
          logger.error(error.stack);
          if (fs.existsSync(self.path)) {
            fs.removeSync(self.path);
          }
          reject(error);
        })
        .done();
    }
  });
			function isNewer(source, destination) {
				let sassOutput = path.join(sassFolder, destination.replace(mikser.options.workingFolder,'').replace('.css','.json'));
				if (fs.existsSync(sassOutput)) {
					try {
						var sassInfo = fs.readJsonSync(sassOutput);
					} catch (err) {
						debug('Erorr processing', sassOutput, err);
						debug(fs.readFileSync(sassOutput, { encoding: 'utf8' }));
						return true;
					}
					return mikser.utils.isNewer(source, destination) || mikser.utils.isNewer(sassInfo.imports, destination);
				}
				return true;
			}
示例#11
0
 zipfile.on('end', function() {
   logger.debug('File unzipped successfully');
   if (fs.existsSync(tmpZipLocation)) {
     fs.removeAsync(tmpZipLocation)
       .then(function() {
         resolve(destination);
       })
       .catch(function(err) {
         reject(err);
       });
   } else {
     resolve(destination);
   }
 });
const copyConfigFiles = () => {
  const fileNames = ['.editorconfig', '.eslintrc', 'postcss.config.js']
  const configFolder = path.join(
    process.cwd(),
    'node_modules/kambi-widget-build-tools/widget_config/'
  )
  const paths = fileNames.map(p => {
    return path.join(configFolder, p)
  })
  paths.forEach((filePath, index) => {
    if (fs.existsSync(filePath)) {
      const fileDest = path.join(process.cwd(), fileNames[index])
      fs.copySync(filePath, fileDest)
    }
  })

  // files with special handling

  // gitignore, we need to rename it to .gitignore (npm strips .gitignore)
  filePath = path.join(configFolder, 'gitignore')
  if (fs.existsSync(filePath)) {
    const fileDest = path.join(process.cwd(), '.gitignore')
    fs.copySync(filePath, fileDest)
  }

  // mockSetupData.json, we need to copy it to /src/ and only if it doesn't exist
  filePath = path.join(configFolder, 'mockSetupData.json')
  if (fs.existsSync(filePath)) {
    const fileDest = path.join(process.cwd(), '/src/mockSetupData.json')
    if (!fs.existsSync(fileDest)) {
      fs.copySync(filePath, fileDest)
    }
  }

  return Promise.resolve()
}
示例#13
0
 finder.on('end', function () {
   // remove retrieved
   // TODO: package support
   if (fs.existsSync(remotePath)) {
     fs.removeAsync(remotePath)
       .then(function() {
         resolve();
       })
       .catch(function(err) {
         reject(err);
       });
   } else {
     resolve();
   }
 });
示例#14
0
 unzipCommand.on('close', function (code) {
   if (fs.existsSync(tmpZipLocation)) {
     fs.removeAsync(tmpZipLocation)
       .then(function() {
         if (code !== 0) {
           return reject(new Error('Could not extract and write stream to file system. [Exit Code '+code+']'));
         } else {
           return resolve(destination);
         }
       })
       .catch(function(err) {
         reject(err);
       });
   }
 });
示例#15
0
 return new Promise(function(resolve, reject) {
   var describePath = path.join(self.path, 'config', '.describe');
   if (fs.existsSync(path.join(self.path, 'config'))) {
     fs.outputFile(describePath, JSON.stringify(describe, null, 4), function(err) {
       if (err) {
         return reject(err);
       } else {
         self._describe = describe;
         resolve();
       }
     });
   } else {
     self._describe = describe;
     resolve();
   }
 });
示例#16
0
 return new Promise(function(resolve, reject) {
   if (fs.existsSync(path.join(self.path, 'config', '.session'))) {
     fs.readJson(path.join(self.path, 'config', '.session'), function(err, cachedSession) {
       if (err) {
         if (err.message.indexOf('Unexpected end of input') >= 0) {
           resolve({});
         } else {
           reject(err);
         }
       } else {
         self.cachedSession = cachedSession;
         resolve(cachedSession);
       }
     });
   } else {
     resolve({});
   }
 });
示例#17
0
 return new Promise(function(resolve, reject) {
   if (isLegacyUnzip === undefined)
     isLegacyUnzip = false;
   var tmpZipLocation = path.join(destination, 'tmp.zip');
   try {
     logger.debug('writing zip stream to', tmpZipLocation);
     readableStream
       .pipe(fstream.Writer(tmpZipLocation))
         .on('error', function (error) {
           logger.error('error writing zip to disk', error);
           if (fs.existsSync(tmpZipLocation)) {
             fs.removeAsync(tmpZipLocation)
               .then(function() {
                 reject(error);
               })
               .catch(function(err) {
                 reject(err);
               });
           }
         })
         .on('close', function() {
           logger.debug('closed write stream, unzipping now');
           var unzipPromise = isLegacyUnzip ? self.unzipLegacy.bind(self) : self.unzip.bind(self);
           unzipPromise(tmpZipLocation, destination)
             .then(function() {
               resolve(destination);
             })
             .catch(function(err) {
               reject(err);
             });
         });
   } catch(e) {
     logger.error('error writing stream', e);
     if (fs.existsSync(tmpZipLocation)) {
       fs.removeAsync(tmpZipLocation)
         .then(function() {
           reject(e);
         })
         .catch(function(err) {
           reject(err);
         });
     }
   }
 });
示例#18
0
  return new Promise(function(resolve, reject) {
    if (!fs.existsSync(path.join(self.path, 'config', '.symbols'))) {
      fs.mkdirpSync(path.join(self.path, 'config', '.symbols'));
    }

    // todo: stash existing
    var symbolService = new SymbolService(self);

    var symbolPromise = apexClassName ? symbolService.indexApexClass(apexClassName) : symbolService.index();
    symbolPromise
      .then(function() {
        logger.debug('done indexing symbols!');
        resolve();
      })
      .catch(function(err) {
        logger.error('Could not index apex symbols: '+err.message);
        reject(err);
      })
      .done();
  });
示例#19
0
    finder.on('file', function (file) {
      var fileBasename = path.basename(file);
      // file => /foo/bar/myproject/unpackaged/classes/myclass.cls
      logger.debug('refreshing file: '+file);

      var directory = path.dirname(file); //=> /foo/bar/myproject/unpackaged/classes
      var destinationDirectory = directory.replace(remotePath, path.join(self.workspace, self.name, 'src')); //=> /foo/bar/myproject/src/classes

      // make directory if it doesnt exist (parent dirs included)
      if (!fs.existsSync(destinationDirectory)) {
        fs.mkdirpSync(destinationDirectory);
      }

      // remove project metadata, replace with recently retrieved
      if (replacePackageXml && fileBasename === 'package.xml') {
        fs.removeSync(path.join(destinationDirectory, fileBasename));
        fs.copySync(file, path.join(destinationDirectory, fileBasename));
      } else if (fileBasename !== 'package.xml') {
        fs.removeSync(path.join(destinationDirectory, fileBasename));
        fs.copySync(file, path.join(destinationDirectory, fileBasename));
      }
    });
 paths.forEach((filePath, index) => {
   if (fs.existsSync(filePath)) {
     const fileDest = path.join(process.cwd(), fileNames[index])
     fs.copySync(filePath, fileDest)
   }
 })
示例#21
0
exports.isValidProjectPath = function(projectPath) {
  return fs.existsSync(path.join(projectPath, 'config', '.settings'));
};
const init = function(opt) {
  if (!opt.argv[1]) {
    return Promise.reject(new Error('Missing <project_name> argument'))
  }

  const projectName = opt.argv[1]

  if (fs.existsSync(projectName) && !opt.options.force) {
    return Promise.reject(
      new Error(
        `Directory ${projectName} exists. You can use --force to force creating it.`
      )
    )
  }

  // map of what needs to be copied where
  const files = {
    'app.scss': 'src/scss',
    'index.html': 'src/',
    'index.js': 'src/',
    'en_GB.json': 'src/i18n/',
    'sv_SE.json': 'src/i18n/',
    'EventWidget.jsx': 'src/js/Components/',
    'BetOffers.jsx': 'src/js/Components/',
    'BetOffers.scss': 'src/js/Components/',
    'Participants.jsx': 'src/js/Components/',
    'Participants.scss': 'src/js/Components/',
    'mockSetupData.json': 'src/',
    'package.json': '',
    'README.md': '',
  }

  // map of what directories need to be created
  const dirs = [
    'src/assets',
  ]

  // variables to replace across all files
  const vars = {
    projectName: projectName,
    projectVersion: opt.options.version || '1.0.0',
    projectDescription:
      opt.options.description || `Description of ${projectName}`,
  }

  const fileKeys = Object.keys(files)

  // create outer directory
  return (
    fs
      .mkdirpAsync(projectName)

      // read all templates
      .then(() =>
        Promise.all(
          fileKeys.map(name =>
            fs.readFileAsync(
              path.join(__dirname, '../react_template', name),
              'utf8'
            )
          )
        )
      )

      // inject variables
      .then(fileContents =>
        fileContents.map(fileContent => {
          return Object.keys(vars).reduce(
            (fileContent, varName) =>
              fileContent.replace(
                new RegExp(`\\$\\{${varName}\\}`, 'g'),
                vars[varName]
              ),
            fileContent
          )
        })
      )

      // create inner directories and write files
      .then(fileContents => {
        return Promise.all(
          fileContents.map((fileContent, i) => {
            const fileName = fileKeys[i],
              filePath = files[fileName]

            return fs
              .mkdirpAsync(path.join(projectName, filePath))
              .then(() =>
                fs.writeFileAsync(
                  path.join(projectName, filePath, fileName),
                  fileContent
                )
              )
          })
        )
      })

      // create additional empty directories
      .then(() => {
        return Promise.all(
          dirs.map(dir => {
            return fs.mkdirpAsync(path.join(projectName, dir))
          })
        )
      })

      // set the build-tools and core-library versions to the newest versions in package.json
      .then(() => {
        return Promise.all([
          exec(
            'npm',
            ['show', 'kambi-widget-build-tools', 'version'],
            { shell: true },
            false
          ),
          exec(
            'npm',
            ['show', 'kambi-widget-core-library', 'version'],
            { shell: true },
            false
          ),
          exec(
            'npm',
            ['show', 'kambi-widget-components', 'version'],
            { shell: true },
            false
          ),
          fs.readFileAsync(path.join(projectName, 'package.json')),
        ]).then(
          ([
            buildToolsVersion,
            coreLibraryVersion,
            componentsVersion,
            packageJson,
          ]) => {
            packageJson = JSON.parse(packageJson)

            packageJson.devDependencies['kambi-widget-build-tools'] =
              '^' + buildToolsVersion.replace('\n', '')
            packageJson.dependencies['kambi-widget-core-library'] =
              '^' + coreLibraryVersion.replace('\n', '')
            packageJson.dependencies['kambi-widget-components'] =
              '^' + componentsVersion.replace('\n', '')

            return fs.writeFileAsync(
              path.join(projectName, 'package.json'),
              JSON.stringify(packageJson, null, 3)
            )
          }
        )
      })

      // run npm install
      .then(() => {
        if (opt.options['without-npm-install']) {
          return Promise.resolve()
        }

        return exec('npm', ['install'], {
          cwd: path.join(process.cwd(), projectName),
          shell: true
        })
      })
  )
}
示例#23
0
function doesMagicDirectoryNamedExist(thaliDontCheckIn) {
  var magicFileLocation = path.join(thaliDontCheckIn,
    MAGIC_DIRECTORY_NAME_FOR_LOCAL_DEPLOYMENT);
  return fs.existsSync(magicFileLocation);
}
示例#24
0
  return new Promise(function(resolve, reject) {
    var tmpZipLocation = path.join(destination, 'tmp.zip');
    try {
      logger.debug('writing stream');
      readableStream
        .pipe(fstream.Writer(tmpZipLocation))
          .on('error', function (error) {
            if (fs.existsSync(tmpZipLocation)) {
              fs.removeAsync(tmpZipLocation)
                .then(function() {
                  reject(error);
                })
                .catch(function(err) {
                  reject(err);
                });
            }
          })
          .on('close', function() {
            logger.debug('closed write stream, unzipping now');

            var unzipCommand;

            if (self.isMac() || self.isLinux()) {
              unzipCommand = spawn('unzip', [ tmpZipLocation, '-d', destination ], { stdio: [ 'ignore', 'ignore', 'pipe' ] });
            } else if (self.isWindows()) {
              var cscriptExe = 'cscript';
              try {
                which.sync('cscript');
              } catch(e) {
                logger.debug('Could not find cscript...');
                if (os.arch() === 'ia32') {
                  cscriptExe = 'c:\\windows\\system32\\cscript.exe';
                } else {
                  cscriptExe = 'c:\\windows\\SysWOW64\\cscript.exe';
                }
              }
              logger.debug('cscriptExe is: ', cscriptExe);
              unzipCommand = spawn(cscriptExe, [path.join(__dirname, '..', '..', 'bin', 'unzip.vbs'), tmpZipLocation, destination ], { stdio: [ 'ignore', 'ignore', 'pipe' ] });
            }

            unzipCommand.on('error', function(err) {
              logger.debug('error spawning unzip process', err);
              if (err.message.indexOf('ENOENT') !== -1) {
                return reject(new Error('Could not unzip response from Salesforce. It is likely unzip (OSX/Linux) or cscript (Windows) is not available on your system PATH. Check your local machine settings.'));
              } else {
                return reject(err);
              }
            });

            unzipCommand.stderr.on('data', function (data) {
              logger.error('ERR unzipping:');
              logger.error(data);
              if (fs.existsSync(tmpZipLocation)) {
                fs.removeAsync(tmpZipLocation)
                  .then(function() {
                    return reject(new Error('Could not extract and write stream to file system.'));
                  })
                  .catch(function(err) {
                    return reject(err);
                  });
              }
            });

            unzipCommand.on('close', function (code) {
              if (fs.existsSync(tmpZipLocation)) {
                fs.removeAsync(tmpZipLocation)
                  .then(function() {
                    if (code !== 0) {
                      return reject(new Error('Could not extract and write stream to file system. [Exit Code '+code+']'));
                    } else {
                      return resolve(destination);
                    }
                  })
                  .catch(function(err) {
                    reject(err);
                  });
              }
            });
          });
    } catch(e) {
      if (fs.existsSync(tmpZipLocation)) {
        fs.removeAsync(tmpZipLocation)
          .then(function() {
            reject(e);
          })
          .catch(function(err) {
            reject(err);
          });
      }
    }
  });
示例#25
0
MavensMateUtil.prototype.isValidProjectPath = function(projectPath) {
  return fs.existsSync(path.join(projectPath, 'config', '.settings'));
};
示例#26
0
  return new Promise(function(resolve, reject) {
    if (!self._isValid()) {
      reject(new Error('This does not seem to be a valid MavensMate project directory.'));
    } else {
      if (self.path !== undefined) {
        self.workspace = path.dirname(self.path);
        self.name = path.basename(self.path);
      } else if (self.workspace !== undefined && self.name !== undefined) {
        self.path = path.join(self.workspace, self.name);
      } else {
        self.path = process.cwd();
        self.workspace = path.dirname(self.path);
        self.name = path.basename(self.path);
      }

      if (!fs.existsSync(self.path)) {
        return reject(new Error('This does not seem to be a valid MavensMate project directory.'));
      }

      logger.debug('project name', self.name);
      logger.debug('project path', self.path);
      // self.workspace = path.dirname(self.path);
      // self.name = path.basename(self.path);

      // TODO: Promise.all or reduce
      // first order of business is to ensure we have a valid sfdc-client

      self.packageXml = new Package({ project: self, path: path.join(self.path, 'src', 'package.xml') });
      self.packageXml.init()
        .then(function() {
          return self._getSettings();
        })
        .then(function() {
          return self._getCachedSession();
        })
        .then(function(cachedSession) {
          cachedSession.username = self.settings.username;
          cachedSession.password = self.settings.password;
          cachedSession.orgType = self.settings.environment;
          cachedSession.loginUrl = self.settings.loginUrl;
          if (!self.sfdcClient) {
            self.sfdcClient = new SalesforceClient(cachedSession);
            self.sfdcClient.on('sfdcclient-cache-refresh', function() {
              logger.debug('project caught event: sfdcclient-cache-refresh');
              self._writeSession()
                .then(self._getCachedSession())
                .catch(function(err) {
                  logger.debug('sfdcclient-cache-refresh: could not update local session cache');
                  throw new Error('Could not update local session cache: '+err.message);
                })
                .done();
            });
          }
          return self.sfdcClient.initialize();
        })
        .then(function() {
          return self._writeSession();
        })
        .then(function() {
          self.getLocalStore();
          return self.getOrgMetadataIndexWithSelections();
        })
        .then(function() {
          return self._refreshDescribeFromServer();
        })
        .then(function() {
          self.logService = new LogService(self);
          self.sfdcClient.on('sfdcclient-new-log', function(message) {
            if (message.sobject && message.sobject.Id) {
              self.logService.downloadLog(message.sobject.Id)
                .then(function(filePath) {
                  self.emit('new-log', filePath);
                })
                .catch(function(error) {
                  logger.debug('Could not download log: '+error.message);
                })
                .done();
            }
          });
          return self.sfdcClient.startSystemStreamingListener();
        })
        .then(function() {
          self.valid = true;
          resolve();
        })
        .catch(function(error) {
          if (error.message.indexOf('INVALID_LOGIN') >= 0 || error.message.indexOf('EXPIRED_PASSWORD') >= 0 || error.message.indexOf('LOGIN_MUST_USE_SECURITY_TOKEN') >= 0) {
            self.valid = false;
          }
          reject(error);
        })
        .done();
    }
  });
示例#27
0
  return new Promise(function(resolve, reject) {
    var pkg, fileProperties;
    if (!self.workspace) {
      throw new Error('Please select a workspace for this project');
    }
    if (!fs.existsSync(path.join(self.origin, 'src'))) {
      return reject(new Error('Project must have a top-level src directory'));
    }
    if (!fs.existsSync(path.join(self.origin, 'src', 'package.xml'))) {
      return reject(new Error('Project must have a valid package.xml file located in the src directory'));
    }

    if (self.origin !== path.join(self.workspace, self.name)) {
      if (fs.existsSync(path.join(self.workspace, self.name))) {
        return reject(new Error('Project with this name already exists in the selected workspace'));
      } else {
        // copy non-mavensmate project to selected workspace
        fs.ensureDirSync(path.join(self.workspace, self.name));
        fs.copySync(self.origin, path.join(self.workspace, self.name));
      }
    }
    self.path = path.join(self.workspace, self.name);
    fs.ensureDirSync(path.join(self.path, 'config'));

    self.sfdcClient.describe()
      .then(function(describe) {
        return self.setDescribe(describe);
      })
      .then(function() {
        pkg = new Package({ project: self, path: path.join(self.path, 'src', 'package.xml') });
        return pkg.init();
      })
      .then(function() {
        return self.sfdcClient.retrieveUnpackaged(pkg.subscription, true, self.path);
      })
      .then(function(retrieveResult) {
        logger.debug('retrieve result: ');
        logger.debug(retrieveResult);
        fileProperties = retrieveResult.fileProperties;
        if (fs.existsSync(path.join(self.path, 'unpackaged'))) {
          fs.removeSync(path.join(self.path, 'unpackaged'));
        }
        self.id = uuid.v1();
        return self._initConfig();
      })
      .then(function() {
        logger.debug('initing local store ... ');
        logger.debug(fileProperties);

        return self._writeLocalStore(fileProperties);
      })
      .then(function() {
        resolve();
      })
      .catch(function(error) {
        // remove directory from workspace if we encounter an exception along the way
        logger.error('Could not retrieve and write project to file system: '+error.message);
        logger.error(error.stack);
        if (self.origin !== path.join(self.workspace, self.name) && fs.existsSync(path.join(self.workspace, self.name))) {
          fs.removeSync(path.join(self.workspace, self.name));
        }
        reject(error);
      })
      .done();
  });
module.exports.index = (req, res) => {
  let visitor;

  if(process.env.GOOGLE_ANALYTICS_ID && process.env.GOOGLE_ANALYTICS_UUID) {
    visitor = ua(process.env.GOOGLE_ANALYTICS_ID, process.env.GOOGLE_ANALYTICS_UUID);
  }

  let source = req.query['source'];

  let sourceURL;
  let githubURL = `https://raw.githubusercontent.com${req.originalUrl}`;
  
  if(source === 'gitlab') {
    // Make sure the raw format is used
    let split = req.originalUrl.split('/');
    split[3] = 'raw';
    let path = split.join('/');
    sourceURL = `https://gitlab.com${path}`;
    console.dir(sourceURL);
  } else if(source === 'bitbucket') {
    // Make sure the raw format is used
    let split = req.originalUrl.split('/');
    split[3] = 'raw';
    let path = split.join('/');
    sourceURL = `https://bitbucket.org${path}`;
  } else if(source === 'github') {
    sourceURL = githubURL;
  } else {
    sourceURL = githubURL;
  }

  if(process.env.GOOGLE_ANALYTICS_ID && process.env.GOOGLE_ANALYTICS_UUID) {
    visitor.pageview(req.originalUrl).send();
  }

  // Store the start line and end line
  let start;
  let end;
  if(req.query['start']) {
    start = parseInt(req.query['start'], 10) - 1;
  }
  if(req.query['end']) {
    end = parseInt(req.query['end'], 10) - 1;
  }

  let cacheFileName = slugify(sourceURL);
  let cacheDir = path.dirname(require.main.filename)+'/cache';
  let cachedFilePath = cacheDir+'/'+cacheFileName +'.txt';

  // Make the cache directory if it doesn't exist
  if (!fs.existsSync(cacheDir)){
    fs.mkdirSync(cacheDir);
  }
  // First check if cached file exists
  return fs.stat(cachedFilePath, function(err) {
    return Promise.resolve(true)
    .then(() => {
      if(!err) {
        return fs.readFileAsync(cachedFilePath, 'utf8');
      } else {
        // Get the data from github
        return fetch(sourceURL)
        .then((response) => {
          if (response.status >= 400) {
            throw new Error("Bad response from server");
          }
          return response.text();
        })
        .then((code) => {
          if(code.length > 1000000){
            throw new Error("Your code sample was too large. There is a 1MB limit.");
          }

          // Add the file to the cache
          return fs.writeFileAsync(cachedFilePath, code)
          .then(() =>{
            return code;
          });
        })
        .catch((error) => {
          console.dir(error);
          return res.send('console.dir("You made a mistake somewhere. Your code could not be fetched.")');
        });
      }
    })
    .then((code) => {
      let lines = code.split('\n');

      let sampleLines = [];

      // If a start and end line were specified, store all the matching lines,
      // else, store all the lines

      if(!start) {
        start = 0;
      }

      if(!end) {
        end = lines.length - 1;
      }

      for(let i = start; i <= end; i++) {
        if(lines[i] !== undefined) {
          // Clean the quotes
          let parsedLine = lines[i].replace(/\"/ig, '\\"').replace(/\'/ig,"\\'");

          // We use document.writes to make sure it gets output to the page when the script is accessed
          sampleLines.push(`document.write('${parsedLine}\\r\\n');`);
        }
      }

      // Recombine the string
      let sampleCode = sampleLines.join('\n');


      // Add the script which loads Google code prettify
      let skin = req.query['skin'] || 'sons-of-obsidian';
      // Get lang from file extension
      let lang = req.query['lang'] || req.originalUrl.split('?')[0].split('.').reverse()[0];

      // Add the openening and closing pre tags
      let wrappedCode =''
      let genCSS = 'position: relative; top: 5px; padding: 5px; border-top: 1px #333333 solid; opacity: .7; font-family: sans-serif; font-size: 12px; font-weight: 900; margin-left: -10px; margin-bottom: -10px;';

      wrappedCode += `document.write('<div style="position: relative;"><pre class=\\"prettyprint lang-${lang}\\" style="padding:10px; padding-bottom: 20px;">');\n`;
      wrappedCode += `${sampleCode}\n`;
      wrappedCode += `document.write('<div style="${genCSS}">Generated by <a href="http://www.gitsnippet.com" target="_blank">Git Snippet</a></div>');`;
      wrappedCode += `document.write('</pre></div>');`;
      sampleCode = wrappedCode;

      let prettifyLoader ='';
      prettifyLoader += `if(window.runPrettifyLoaded !== true) {\n`
      prettifyLoader += `loadJS('https://cdn.rawgit.com/google/code-prettify/master/loader/run_prettify.js?skin=${skin}');\n`
      prettifyLoader += `function loadJS(file) {\n`
      prettifyLoader += `window.runPrettifyLoaded = true;\n`
      prettifyLoader += `var jsElm = document.createElement("script");\n`
      prettifyLoader += `jsElm.type = "application/javascript";\n`
      prettifyLoader += `jsElm.src = file;\n`
      prettifyLoader += `document.body.appendChild(jsElm);\n`
      prettifyLoader += `}\n`
      prettifyLoader +=` }\n`

      sampleCode = `${sampleCode}${prettifyLoader}`;
      
      // Return the script
      res.set('Content-Type', 'application/x-javascript'); 
      return res.send(sampleCode);
    })
  });
};
示例#29
0
  return new Promise(function(resolve, reject) {
    if (fs.existsSync(path.join(self.path, 'config', '.org_metadata'))) {
      try {
        fs.readJson(path.join(self.path, 'config', '.org_metadata'), function(err, orgMetadata) {
          if (err) {
            reject(err);
          } else {
            self.orgMetadata = orgMetadata;
            var indexService = new IndexService({ project: self });
            var metadataHelper = new MetadataHelper({ sfdcClient: self.sfdcClient });

            var promise;
            var customPackage;
            if (packageLocation) {
              customPackage = new Package({ path: packageLocation });
              promise = customPackage.init();
            } else {
              promise = new Promise(function(r) { r(); });
            }

            promise
              .then(function() {
                if (!ids) {
                  ids = [];
                  var pkg = packageLocation ? customPackage : self.packageXml;
                  _.forOwn(pkg.subscription, function(packageMembers, metadataTypeXmlName) {
                    var metadataType = metadataHelper.getTypeByXmlName(metadataTypeXmlName); //inFolder, childXmlNames
                    if (!metadataType) {
                      return reject(new Error('Unrecognized package.xml metadata type: '+metadataTypeXmlName));
                    }
                    if (_.has(metadataType, 'parentXmlName')) {
                      var parentMetadataType = metadataHelper.getTypeByXmlName(metadataType.parentXmlName);
                    }
                    if (packageMembers === '*') {
                      ids.push(metadataTypeXmlName);
                      var indexedType = _.find(orgMetadata, { 'xmlName': metadataTypeXmlName });
                      if (_.has(indexedType, 'children')) {
                        _.each(indexedType.children, function(child) {
                          child.select = true;
                        });
                      }
                    } else {
                      _.each(packageMembers, function(member) {
                        if (metadataType.inFolder) {
                          // id : Document.FolderName.FileName.txt
                          ids.push([metadataTypeXmlName, member.replace(/\//, '.')].join('.'));
                        } else if (parentMetadataType) {
                          // id : CustomObject.Object_Name__c.fields.Field_Name__c
                          var id = [ parentMetadataType.xmlName, member.split('.')[0], metadataType.tagName, member.split('.')[1] ].join('.');
                          ids.push(id);
                        } else if (_.has(metadataType, 'childXmlNames')) {
                          var indexedType = _.find(orgMetadata, { 'xmlName': metadataTypeXmlName });
                          if (indexedType) {
                            var indexedNode = _.find(indexedType.children, { 'id': [metadataTypeXmlName, member].join('.')});
                            if (_.has(indexedNode, 'children')) {
                              _.each(indexedNode.children, function(child) {
                                child.select = true;
                                if (_.has(child, 'children')) {
                                  _.each(child.children, function(grandChild) {
                                    grandChild.select = true;
                                  });
                                }
                              });
                            }
                            ids.push([metadataTypeXmlName, member].join('.'));
                          }
                        } else {
                          // id: ApexClass.MyClassName
                          ids.push([metadataTypeXmlName, member].join('.'));
                        }
                      });
                    }
                  });
                }
                indexService.setChecked(orgMetadata, ids);
                indexService.ensureParentsAreCheckedIfNecessary(orgMetadata);
                if (keyword) {
                  indexService.setVisibility(orgMetadata, keyword);
                }
                resolve(orgMetadata);
              });
          }
        });
      } catch(err) {
        logger.debug('Could not getOrgMetadataIndexWithSelections: '+err.message);
        resolve([]);
      }
    } else {
      logger.debug('org_metadata not found, returning empty array');
      resolve([]);
    }
  });