예제 #1
0
 def Run(self, argv):
   if len(argv) != 2:
     app.usage(shorthelp=1,
       detailed_error='Incorrect number of arguments, ' +
       'expected 1, got %s' % (len(argv) - 1,),
       exitcode=1)
   isbn = Isbn(argv[1])
   print isbn
예제 #2
0
 def Run(self, argv):
     if len(argv) != 2:
         app.usage(shorthelp=1,
                   detailed_error='Incorrect number of arguments, ' +
                   'expected 1, got %s' % (len(argv) - 1, ),
                   exitcode=1)
     isbn = Isbn(argv[1])
     print isbn
예제 #3
0
    def CommandRun(self, argv):
        """Execute the command with given arguments.

    First register and parse additional flags. Then run the command.

    Returns:
      Command return value.

    Args:
      argv: Remaining command line arguments after parsing command and flags
            (that is a copy of sys.argv at the time of the function call with
            all parsed flags removed).
    """
        # Register flags global when run normally
        FLAGS.AppendFlagValues(self._command_flags)
        # Prepare flags parsing, to redirect help, to show help for command
        orig_app_usage = app.usage

        def ReplacementAppUsage(shorthelp=0,
                                writeto_stdout=1,
                                detailed_error=None,
                                exitcode=None):
            AppcommandsUsage(shorthelp,
                             writeto_stdout,
                             detailed_error,
                             exitcode=exitcode,
                             show_cmd=self._command_name,
                             show_global_flags=True)

        app.usage = ReplacementAppUsage
        # Parse flags and restore app.usage afterwards
        try:
            try:
                argv = ParseFlagsWithUsage(argv)
                # Run command
                ret = self.Run(argv)
                if ret is None:
                    ret = 0
                else:
                    assert isinstance(ret, int)
                return ret
            except (app.UsageError, error):
                app.usage(shorthelp=1,
                          detailed_error=error,
                          exitcode=error.exitcode)
            except:
                if FLAGS.pdb_post_mortem:
                    traceback.print_exc()
                    pdb.post_mortem()
                raise
        finally:
            # Restore app.usage and remove this command's flags from the global flags.
            app.usage = orig_app_usage
            for flag_name in self._command_flags.FlagDict():
                delattr(FLAGS, flag_name)
예제 #4
0
def main(args):
  stopwatch.sw.start()
  if not len(args) == 2:
    app.usage(detailed_error='Must list exactly one directory to scrub.',
              exitcode=3)
  codebase = args[1]

  # TODO(dborowitz): put this in a json file in data/.
  ignore_files = ['/.git/', 'infrastructure/rhino1_7R1',
                  'infrastructure/yuicompressor', 'jsmin', '' 'BUILD', 'CONFIG',
                  'CORE', 'OWNERS', 'PRESUBMIT.py', 'QUEUE', 'README', '/bin/',
                  '/docs/']
  ignore_files_re = '|'.join(re.escape(f) for f in ignore_files)

  config = scrubber.ScrubberConfigFromJson(
      codebase,
      {'ignore_files_re': ignore_files_re},
      extension_to_scrubber_map={
          '.c': [LicensePreambleAdder('c')],
          '.cc': [LicensePreambleAdder('cc')],
          '.css': [LicensePreambleAdder('css')],
          '.ejs': [LicensePreambleAdder('ejs')],
          '.gif': [],
          '.go': [LicensePreambleAdder('go')],
          '.html': [LicensePreambleAdder('html')],
          '.ico': [],
          '.jar': [],
          '.java': [LicensePreambleAdder('java')],
          '.jpg': [],
          '.js': [LicensePreambleAdder('js')],
          '.png': [],
          '.py': [LicensePreambleAdder('py')],
          '.scala': [LicensePreambleAdder('scala')],
          '.sh': [LicensePreambleAdder('sh')],
          '.swf': [],
          '.txt': [],
          '.xml': [],
      },
      modify=FLAGS.modify)

  context = scrubber.ScrubberContext(config)

  # TODO(dbentley): refactor further so that this boilerplate
  # is folded in to ScrubberContext's run method.
  print 'Found %d files' % len(context.files)
  context.Scan()

  context.WriteOutput()
  context.Report()

  stopwatch.sw.stop()
  if FLAGS.stopwatch:
    print stopwatch.sw.dump(verbose=True)

  return context.Status()
예제 #5
0
def BadCommand(message=None):
  """Ends the app with exit status code 3, displaying the message.

  This function will not return.

  Args:
    message: The message to display, followed by the standard usage message.
  """
  if message:
    app.usage(detailed_error=('%s\n%s' % (message, MAIN_USAGE_STRING)),
              exitcode=3)
  else:
    app.usage(detailed_error=MAIN_USAGE_STRING, exitcode=3)
예제 #6
0
파일: scrubber.py 프로젝트: pir8aye/MOE-py
def BadCommand(message=None):
    """Ends the app with exit status code 3, displaying the message.

  This function will not return.

  Args:
    message: The message to display, followed by the standard usage message.
  """
    if message:
        app.usage(detailed_error=('%s\n%s' % (message, MAIN_USAGE_STRING)),
                  exitcode=3)
    else:
        app.usage(detailed_error=MAIN_USAGE_STRING, exitcode=3)
예제 #7
0
  def Run(self, argv):
    if len(argv) != 2:
      app.usage(shorthelp=1,
        detailed_error='Incorrect number of arguments, ' +
        'expected 1, got %s' % (len(argv) - 1,),
        exitcode=1)

    isbn = Isbn(argv[1])
    try:
      response = Client().LookupIsbns([isbn])
      item_info = AmazonClient.GetSalesInfo(response)[str(isbn)]
    except RuntimeError, e:
      print "Error looking up ISBN:",
      if '\n' in e:
        print
      print e
      exit(1)
예제 #8
0
    def Run(self, argv):
        if len(argv) != 2:
            app.usage(shorthelp=1,
                      detailed_error='Incorrect number of arguments, ' +
                      'expected 1, got %s' % (len(argv) - 1, ),
                      exitcode=1)

        isbn = Isbn(argv[1])
        try:
            response = Client().LookupIsbns([isbn])
            item_info = AmazonClient.GetSalesInfo(response)[str(isbn)]
        except RuntimeError, e:
            print "Error looking up ISBN:",
            if '\n' in e:
                print
            print e
            exit(1)
예제 #9
0
  def CommandRun(self, argv):
    """Execute the command with given arguments.

    First register and parse additional flags. Then run the command.

    Returns:
      Command return value.

    Args:
      argv: Remaining command line arguments after parsing command and flags
            (that is a copy of sys.argv at the time of the function call with
            all parsed flags removed).
    """
    # Register flags global when run normally
    FLAGS.AppendFlagValues(self._command_flags)
    # Prepare flags parsing, to redirect help, to show help for command
    orig_app_usage = app.usage

    def ReplacementAppUsage(shorthelp=0, writeto_stdout=1, detailed_error=None,
                            exitcode=None):
      AppcommandsUsage(shorthelp, writeto_stdout, detailed_error, exitcode=1,
                       show_cmd=self._command_name, show_global_flags=True)
    app.usage = ReplacementAppUsage
    # Parse flags and restore app.usage afterwards
    try:
      try:
        argv = ParseFlagsWithUsage(argv)
        # Run command
        if FLAGS.run_with_pdb:
          ret = pdb.runcall(self.Run, argv)
        else:
          ret = self.Run(argv)
        if ret is None:
          ret = 0
        else:
          assert isinstance(ret, int)
        return ret
      except app.UsageError, error:
        app.usage(shorthelp=1, detailed_error=error, exitcode=error.exitcode)
    finally:
      # Restore app.usage and remove this command's flags from the global flags.
      app.usage = orig_app_usage
      for flag_name in self._command_flags.FlagDict():
        delattr(FLAGS, flag_name)
예제 #10
0
  def Run(self, argv):
    if len(argv) not in [2, 3]:
      app.usage(shorthelp=1,
        detailed_error='Incorrect number of arguments, ' +
        'expected 1 or 2, got %s' % (len(argv) - 1,),
        exitcode=1)

    if len(argv) == 3:
      if FLAGS.quiet and output_filename is None:
        print 'Quiet and no output file -- nothing to do!'
        return
      outfile_name = argv[2]
      as_csv = outfile_name.endswith('.csv')
      new_outfile = not os.path.exists(outfile_name)
      self.outfile = open(outfile_name, 'a')

    input_file = argv[1]
    if not os.path.exists(input_file):
      print 'Cannot find file: %s' % (input_file,)
      exit(1)
    
    if not (FLAGS.quiet or as_csv):
      print '    ISBN         Price    Sales Rank              Title'
      print '------------- ---------- ------------',
      print '-----------------------------------------------'

    isbn_ls = map(Isbn, open(input_file).readlines())
    while isbn_ls:
      batch = map(str, isbn_ls[:10])
      isbn_ls = isbn_ls[len(batch):]
      response = Client().LookupIsbns(batch)
      sales_infos = AmazonClient.GetSalesInfo(response)
      if as_csv:
        self.WriteCsv(sales_infos, write_header=new_outfile)
      else:
        for isbn in batch:
          self.PrintItem(isbn, sales_infos.get(isbn))
예제 #11
0
    def Run(self, argv):
        if len(argv) not in [2, 3]:
            app.usage(shorthelp=1,
                      detailed_error='Incorrect number of arguments, ' +
                      'expected 1 or 2, got %s' % (len(argv) - 1, ),
                      exitcode=1)

        if len(argv) == 3:
            if FLAGS.quiet and output_filename is None:
                print 'Quiet and no output file -- nothing to do!'
                return
            outfile_name = argv[2]
            as_csv = outfile_name.endswith('.csv')
            new_outfile = not os.path.exists(outfile_name)
            self.outfile = open(outfile_name, 'a')

        input_file = argv[1]
        if not os.path.exists(input_file):
            print 'Cannot find file: %s' % (input_file, )
            exit(1)

        if not (FLAGS.quiet or as_csv):
            print '    ISBN         Price    Sales Rank              Title'
            print '------------- ---------- ------------',
            print '-----------------------------------------------'

        isbn_ls = map(Isbn, open(input_file).readlines())
        while isbn_ls:
            batch = map(str, isbn_ls[:10])
            isbn_ls = isbn_ls[len(batch):]
            response = Client().LookupIsbns(batch)
            sales_infos = AmazonClient.GetSalesInfo(response)
            if as_csv:
                self.WriteCsv(sales_infos, write_header=new_outfile)
            else:
                for isbn in batch:
                    self.PrintItem(isbn, sales_infos.get(isbn))
예제 #12
0
  def _RunCommand(self, the_state, cmd, argv):
    """Executes the given command.

    Makes the right thing happen when the appcommand raises
    app.UsageError. Temporarily makes the appcommand-specific
    command-line flags appear to be global flags.

    Args:
      the_state: state.State
      cmd: uicmd.UICmd
      argv: [str]
    Returns:
      UndoableCommand|None
    Raises:
      InvalidUsageError
    """
    flag_values = self._flag_values_by_cmd[argv[0]]
    FLAGS.AppendFlagValues(flag_values)
    # Prepare flags parsing, to redirect help, to show help for command
    orig_app_usage = app.usage

    def ReplacementAppUsage(shorthelp=0, writeto_stdout=1,
                            detailed_error=None, exitcode=None):
      """Replaces app.usage."""
      func = _GenAppcommandsUsage(
        cmd,
        the_state.Print)
      func(show_cmd=None if not argv else argv[0],
           shorthelp=shorthelp,
           writeto_stdout=writeto_stdout,
           detailed_error=detailed_error,
           exitcode=exitcode)

    app.usage = ReplacementAppUsage
    # Parse flags and restore app.usage afterwards
    try:
      try:
        uc = None
        if cmd.IsUndoable():
          uc = undoutil.UndoableCommand(argv)  # unparsed argv
        try:
          argv = flag_values(argv)
        except flags.UnrecognizedFlagError as e:
          raise app.UsageError(
            u'Cannot parse arguments. If you have a leading hyphen in one of '
            u'your arguments, preface that argument with a \'--\' argument, '
            u'the syntax that makes all following arguments positional. '
            u'Detailed error: %s'
            % unicode(e))
        except flags.FlagsError as e:
          raise app.UsageError(
            u'Cannot parse arguments. Note the \'--\' syntax which makes all '
            u'following arguments positional. Detailed error: %s'
            % unicode(e))
        try:
          cmd.Run(argv)
        except AssertionError as e:
          e.message = (u'For the following error, note that argv=%s. Error: %s'
                       % (argv, unicode(e)))
          raise
        except IncorrectUsageError as e:
          if FLAGS.pyatdl_give_full_help_for_uicmd:
            raise app.UsageError(unicode(e))
          else:
            raise
        return uc
      except app.UsageError as error:
        app.usage(shorthelp=1, detailed_error=error, exitcode=error.exitcode)
        raise InvalidUsageError(unicode(error))
      finally:
        flag_values.Reset()
    finally:
      # Restore app.usage and remove this command's flags from the global flags.
      app.usage = orig_app_usage
      FLAGS.RemoveFlagValues(flag_values)