• 跳转到 … +
    browser.coffee cake.coffee coffee-script.coffee command.coffee grammar.coffee helpers.coffee index.coffee lexer.coffee nodes.coffee optparse.coffee register.coffee repl.coffee rewriter.coffee scope.litcoffee sourcemap.litcoffee
  • command.coffee

  • ¶

    coffee 工具。处理 CoffeeScript 命令行编译成各种形式:保存到 .js 文件或打印到标准输出,或者每次源代码保存时重新编译,打印为令牌流或语法树,或启动交互式 REPL。

  • ¶

    外部依赖项。

    fs             = require 'fs'
    path           = require 'path'
    helpers        = require './helpers'
    optparse       = require './optparse'
    CoffeeScript   = require './coffee-script'
    {spawn, exec}  = require 'child_process'
    {EventEmitter} = require 'events'
    
    useWinPathSep  = path.sep is '\\'
  • ¶

    允许 CoffeeScript 触发 Node.js 事件。

    helpers.extend CoffeeScript, new EventEmitter
    
    printLine = (line) -> process.stdout.write line + '\n'
    printWarn = (line) -> process.stderr.write line + '\n'
    
    hidden = (file) -> /^\.|~$/.test file
  • ¶

    与 -h/--help 结合打印的帮助横幅。

    BANNER = '''
      Usage: coffee [options] path/to/script.coffee -- [args]
    
      If called without options, `coffee` will run your script.
    '''
  • ¶

    coffee 知道如何处理的所有有效选项标志列表。

    SWITCHES = [
      ['-b', '--bare',            'compile without a top-level function wrapper']
      ['-c', '--compile',         'compile to JavaScript and save as .js files']
      ['-e', '--eval',            'pass a string from the command line as input']
      ['-h', '--help',            'display this help message']
      ['-i', '--interactive',     'run an interactive CoffeeScript REPL']
      ['-j', '--join [FILE]',     'concatenate the source CoffeeScript before compiling']
      ['-m', '--map',             'generate source map and save as .js.map files']
      ['-M', '--inline-map',      'generate source map and include it directly in output']
      ['-n', '--nodes',           'print out the parse tree that the parser produces']
      [      '--nodejs [ARGS]',   'pass options directly to the "node" binary']
      [      '--no-header',       'suppress the "Generated by" header']
      ['-o', '--output [DIR]',    'set the output directory for compiled JavaScript']
      ['-p', '--print',           'print out the compiled JavaScript']
      ['-r', '--require [MODULE*]', 'require the given module before eval or REPL']
      ['-s', '--stdio',           'listen for and compile scripts over stdio']
      ['-l', '--literate',        'treat stdio as literate style coffee-script']
      ['-t', '--tokens',          'print out the tokens that the lexer/rewriter produce']
      ['-v', '--version',         'display the version number']
      ['-w', '--watch',           'watch scripts for changes and rerun commands']
    ]
  • ¶

    所有函数共享的顶级对象。

    opts         = {}
    sources      = []
    sourceCode   = []
    notSources   = {}
    watchedDirs  = {}
    optionParser = null
  • ¶

    通过解析传递的选项并确定要采取的操作来运行 coffee。许多标志会导致我们在编译任何内容之前转向。-- 之后传递的标志将作为参数在 process.argv 中逐字传递给您的脚本。

    exports.run = ->
      parseOptions()
  • ¶

    使 REPL CLI 使用全局上下文,以便 (a) 与 node REPL CLI 保持一致,因此 (b) 使修改原生原型的包(如“colors”和“sugar”)按预期工作。

      replCliOpts = useGlobal: yes
      opts.prelude = makePrelude opts.require       if opts.require
      replCliOpts.prelude = opts.prelude
      return forkNode()                             if opts.nodejs
      return usage()                                if opts.help
      return version()                              if opts.version
      return require('./repl').start(replCliOpts)   if opts.interactive
      return compileStdio()                         if opts.stdio
      return compileScript null, opts.arguments[0]  if opts.eval
      return require('./repl').start(replCliOpts)   unless opts.arguments.length
      literals = if opts.run then opts.arguments.splice 1 else []
      process.argv = process.argv[0..1].concat literals
      process.argv[0] = 'coffee'
    
      opts.output = path.resolve opts.output  if opts.output
      if opts.join
        opts.join = path.resolve opts.join
        console.error '''
    
        The --join option is deprecated and will be removed in a future version.
    
        If for some reason it's necessary to share local variables between files,
        replace...
    
            $ coffee --compile --join bundle.js -- a.coffee b.coffee c.coffee
    
        with...
    
            $ cat a.coffee b.coffee c.coffee | coffee --compile --stdio > bundle.js
    
        '''
      for source in opts.arguments
        source = path.resolve source
        compilePath source, yes, source
    
    makePrelude = (requires) ->
      requires.map (module) ->
        [_, name, module] = match if match = module.match(/^(.*)=(.*)$/)
        name ||= helpers.baseFileName module, yes, useWinPathSep
        "#{name} = require('#{module}')"
      .join ';'
  • ¶

    编译路径,可以是脚本或目录。如果传递目录,则递归编译其中所有“.coffee”、“.litcoffee”和“.coffee.md”扩展源文件以及所有子目录。

    compilePath = (source, topLevel, base) ->
      return if source in sources   or
                watchedDirs[source] or
                not topLevel and (notSources[source] or hidden source)
      try
        stats = fs.statSync source
      catch err
        if err.code is 'ENOENT'
          console.error "File not found: #{source}"
          process.exit 1
        throw err
      if stats.isDirectory()
        if path.basename(source) is 'node_modules'
          notSources[source] = yes
          return
        if opts.run
          compilePath findDirectoryIndex(source), topLevel, base
          return
        watchDir source, base if opts.watch
        try
          files = fs.readdirSync source
        catch err
          if err.code is 'ENOENT' then return else throw err
        for file in files
          compilePath (path.join source, file), no, base
      else if topLevel or helpers.isCoffee source
        sources.push source
        sourceCode.push null
        delete notSources[source]
        watch source, base if opts.watch
        try
          code = fs.readFileSync source
        catch err
          if err.code is 'ENOENT' then return else throw err
        compileScript(source, code.toString(), base)
      else
        notSources[source] = yes
    
    findDirectoryIndex = (source) ->
      for ext in CoffeeScript.FILE_EXTENSIONS
        index = path.join source, "index#{ext}"
        try
          return index if (fs.statSync index).isFile()
        catch err
          throw err unless err.code is 'ENOENT'
      console.error "Missing index.coffee or index.litcoffee in #{source}"
      process.exit 1
  • ¶

    根据请求的选项编译包含给定代码的单个源脚本。如果直接评估脚本,则将 __filename、__dirname 和 module.filename 设置为相对于脚本路径的正确值。

    compileScript = (file, input, base = null) ->
      o = opts
      options = compileOptions file, base
      try
        t = task = {file, input, options}
        CoffeeScript.emit 'compile', task
        if o.tokens
          printTokens CoffeeScript.tokens t.input, t.options
        else if o.nodes
          printLine CoffeeScript.nodes(t.input, t.options).toString().trim()
        else if o.run
          CoffeeScript.register()
          CoffeeScript.eval opts.prelude, t.options if opts.prelude
          CoffeeScript.run t.input, t.options
        else if o.join and t.file isnt o.join
          t.input = helpers.invertLiterate t.input if helpers.isLiterate file
          sourceCode[sources.indexOf(t.file)] = t.input
          compileJoin()
        else
          compiled = CoffeeScript.compile t.input, t.options
          t.output = compiled
          if o.map
            t.output = compiled.js
            t.sourceMap = compiled.v3SourceMap
    
          CoffeeScript.emit 'success', task
          if o.print
            printLine t.output.trim()
          else if o.compile or o.map
            writeJs base, t.file, t.output, options.jsPath, t.sourceMap
      catch err
        CoffeeScript.emit 'failure', err, task
        return if CoffeeScript.listeners('failure').length
        message = err?.stack or "#{err}"
        if o.watch
          printLine message + '\x07'
        else
          printWarn message
          process.exit 1
  • ¶

    将适当的监听器附加到通过 **stdin** 传入的编译脚本,并将它们写回 **stdout**。

    compileStdio = ->
      buffers = []
      stdin = process.openStdin()
      stdin.on 'data', (buffer) ->
        buffers.push buffer if buffer
      stdin.on 'end', ->
        compileScript null, Buffer.concat(buffers).toString()
  • ¶

    如果所有源文件都已完成读取,则将它们连接在一起并编译。

    joinTimeout = null
    compileJoin = ->
      return unless opts.join
      unless sourceCode.some((code) -> code is null)
        clearTimeout joinTimeout
        joinTimeout = wait 100, ->
          compileScript opts.join, sourceCode.join('\n'), opts.join
  • ¶

    使用 fs.watch 监视源 CoffeeScript 文件,每次文件更新时重新编译它。可以与其他选项结合使用,例如 --print。

    watch = (source, base) ->
      watcher        = null
      prevStats      = null
      compileTimeout = null
    
      watchErr = (err) ->
        throw err unless err.code is 'ENOENT'
        return unless source in sources
        try
          rewatch()
          compile()
        catch
          removeSource source, base
          compileJoin()
    
      compile = ->
        clearTimeout compileTimeout
        compileTimeout = wait 25, ->
          fs.stat source, (err, stats) ->
            return watchErr err if err
            return rewatch() if prevStats and
                                stats.size is prevStats.size and
                                stats.mtime.getTime() is prevStats.mtime.getTime()
            prevStats = stats
            fs.readFile source, (err, code) ->
              return watchErr err if err
              compileScript(source, code.toString(), base)
              rewatch()
    
      startWatcher = ->
        watcher = fs.watch source
        .on 'change', compile
        .on 'error', (err) ->
          throw err unless err.code is 'EPERM'
          removeSource source, base
    
      rewatch = ->
        watcher?.close()
        startWatcher()
    
      try
        startWatcher()
      catch err
        watchErr err
  • ¶

    监视文件目录中的新添加项。

    watchDir = (source, base) ->
      watcher        = null
      readdirTimeout = null
    
      startWatcher = ->
        watcher = fs.watch source
        .on 'error', (err) ->
          throw err unless err.code is 'EPERM'
          stopWatcher()
        .on 'change', ->
          clearTimeout readdirTimeout
          readdirTimeout = wait 25, ->
            try
              files = fs.readdirSync source
            catch err
              throw err unless err.code is 'ENOENT'
              return stopWatcher()
            for file in files
              compilePath (path.join source, file), no, base
    
      stopWatcher = ->
        watcher.close()
        removeSourceDir source, base
    
      watchedDirs[source] = yes
      try
        startWatcher()
      catch err
        throw err unless err.code is 'ENOENT'
    
    removeSourceDir = (source, base) ->
      delete watchedDirs[source]
      sourcesChanged = no
      for file in sources when source is path.dirname file
        removeSource file, base
        sourcesChanged = yes
      compileJoin() if sourcesChanged
  • ¶

    从我们的源列表和源代码缓存中删除文件。可以选择删除编译后的 JS 版本。

    removeSource = (source, base) ->
      index = sources.indexOf source
      sources.splice index, 1
      sourceCode.splice index, 1
      unless opts.join
        silentUnlink outputPath source, base
        silentUnlink outputPath source, base, '.js.map'
        timeLog "removed #{source}"
    
    silentUnlink = (path) ->
      try
        fs.unlinkSync path
      catch err
        throw err unless err.code in ['ENOENT', 'EPERM']
  • ¶

    获取源文件的相应输出 JavaScript 路径。

    outputPath = (source, base, extension=".js") ->
      basename  = helpers.baseFileName source, yes, useWinPathSep
      srcDir    = path.dirname source
      if not opts.output
        dir = srcDir
      else if source is base
        dir = opts.output
      else
        dir = path.join opts.output, path.relative base, srcDir
      path.join dir, basename + extension
  • ¶

    递归 mkdir,如 mkdir -p。

    mkdirp = (dir, fn) ->
      mode = 0o777 & ~process.umask()
    
      do mkdirs = (p = dir, fn) ->
        fs.exists p, (exists) ->
          if exists
            fn()
          else
            mkdirs path.dirname(p), ->
              fs.mkdir p, mode, (err) ->
                return fn err if err
                fn()
  • ¶

    使用编译后的代码写出 JavaScript 源文件。默认情况下,文件以 .js 文件的形式写入 cwd 中,并具有相同的名称,但输出目录可以使用 --output 自定义。

    如果提供了 generatedSourceMap,这将写入一个 .js.map 文件到与 .js 文件相同的目录中。

    writeJs = (base, sourcePath, js, jsPath, generatedSourceMap = null) ->
      sourceMapPath = outputPath sourcePath, base, ".js.map"
      jsDir  = path.dirname jsPath
      compile = ->
        if opts.compile
          js = ' ' if js.length <= 0
          if generatedSourceMap then js = "#{js}\n//# sourceMappingURL=#{helpers.baseFileName sourceMapPath, no, useWinPathSep}\n"
          fs.writeFile jsPath, js, (err) ->
            if err
              printLine err.message
              process.exit 1
            else if opts.compile and opts.watch
              timeLog "compiled #{sourcePath}"
        if generatedSourceMap
          fs.writeFile sourceMapPath, generatedSourceMap, (err) ->
            if err
              printLine "Could not write source map: #{err.message}"
              process.exit 1
      fs.exists jsDir, (itExists) ->
        if itExists then compile() else mkdirp jsDir, compile
  • ¶

    更简洁的 setTimeouts 的便利性。

    wait = (milliseconds, func) -> setTimeout func, milliseconds
  • ¶

    监视脚本时,使用时间戳记录更改很有用。

    timeLog = (message) ->
      console.log "#{(new Date).toLocaleTimeString()} - #{message}"
  • ¶

    漂亮打印令牌流,不带位置数据。

    printTokens = (tokens) ->
      strings = for token in tokens
        tag = token[0]
        value = token[1].toString().replace(/\n/, '\\n')
        "[#{tag} #{value}]"
      printLine strings.join(' ')
  • ¶

    使用 OptionParser 模块 从 process.argv 中提取 SWITCHES 中指定的选项。

    parseOptions = ->
      optionParser  = new optparse.OptionParser SWITCHES, BANNER
      o = opts      = optionParser.parse process.argv[2..]
      o.compile     or=  !!o.output
      o.run         = not (o.compile or o.print or o.map)
      o.print       = !!  (o.print or (o.eval or o.stdio and o.compile))
  • ¶

    传递给 CoffeeScript 编译器的编译时选项。

    compileOptions = (filename, base) ->
      answer = {
        filename
        literate: opts.literate or helpers.isLiterate(filename)
        bare: opts.bare
        header: opts.compile and not opts['no-header']
        sourceMap: opts.map
        inlineMap: opts['inline-map']
      }
      if filename
        if base
          cwd = process.cwd()
          jsPath = outputPath filename, base
          jsDir = path.dirname jsPath
          answer = helpers.merge answer, {
            jsPath
            sourceRoot: path.relative jsDir, cwd
            sourceFiles: [path.relative cwd, filename]
            generatedFile: helpers.baseFileName(jsPath, no, useWinPathSep)
          }
        else
          answer = helpers.merge answer,
            sourceRoot: ""
            sourceFiles: [helpers.baseFileName filename, no, useWinPathSep]
            generatedFile: helpers.baseFileName(filename, yes, useWinPathSep) + ".js"
      answer
  • ¶

    使用传递给 node 二进制文件的 --nodejs 中的参数启动一个新的 Node.js 实例,保留其他选项。

    forkNode = ->
      nodeArgs = opts.nodejs.split /\s+/
      args     = process.argv[1..]
      args.splice args.indexOf('--nodejs'), 2
      p = spawn process.execPath, nodeArgs.concat(args),
        cwd:        process.cwd()
        env:        process.env
        stdio:      [0, 1, 2]
      p.on 'exit', (code) -> process.exit code
  • ¶

    打印 --help 使用信息并退出。不显示已弃用的开关。

    usage = ->
      printLine (new optparse.OptionParser SWITCHES, BANNER).help()
  • ¶

    打印 --version 信息并退出。

    version = ->
      printLine "CoffeeScript version #{CoffeeScript.VERSION}"