0

This is what I need:

I have log statements in my javascript files, they look like this:

log.d("some log message here")

I want to dynamically add fine name and line number to these during the copy task. Ok, so adding the file name is probably easy enough, but how to I get access to line number? Strangely I could not find any information on how to do this.

The filter() method of Copy task just passing the actual line, it would be nice if it was passing 2 arguments - line and line number.

Here is the template of my task. I added comments of what I need to achieve.

I know I can get name of file from fileCopyDetails using fileCpyDetails.getSourceName() but I am stuck on how to replace the lines that start with log.d() with a new log.d statement that has line number I am really hoping someone can help me here.

task addLineNumbers(type: Copy) {
  into 'build/deploy'
  from 'source'
  eachFile { fileCopyDetails ->
    // Here I need to add line number to log.d("message")
    // to become log.d("[$fileName::$line] + $message")
    // for example, if original line in userdetails.js file was log.d("something logged here")
    // replace with log.d("[userdetails.js::43] something logged here")
  }

}
Dmitri
  • 34,780
  • 9
  • 39
  • 55
  • You might want to implement your own task for this, rather than using a `Copy` task. Implementing an Ant `FilterReader` would be another option. – Peter Niederwieser Nov 23 '14 at 22:34

2 Answers2

1

Not the most elegant solution, but works for me:

task addLineNumbers(type: Copy) {
    into 'build/deploy'
    from 'source'

    def currentFile = ""
    def lineNumber = 1

    eachFile { fileCopyDetails ->
        currentFile = fileCopyDetails.getSourceName()
        lineNumber = 1
    }

    filter { line ->
        if (line.contains('log.d("')) {
            line = line.replace('log.d("', "log.d(\"[${currentFile}::${lineNumber}]")
        }

        lineNumber++
        return line
    }
}
Alex Lipov
  • 13,503
  • 5
  • 64
  • 87
0

The Copy task just copies files (it can filter/expand files using Ant filters or Groovy SimpleTemplateEngine). You're looking for a pre-processor of sorts. I think it's possible to do that with a custom Ant filter, but it seems like a lot of work.

I think what people typically do is use something like this at runtime to find the file/line number: How can I determine the current line number in JavaScript?

Community
  • 1
  • 1
bigguy
  • 973
  • 9
  • 13
  • I am using a trick to determine file name and line number at runtime, but it's inefficient and it's exactly what I'm trying to fix with the build script so that I don't have to use this trick in production. – Dmitri Nov 23 '14 at 16:05