IO.gradle 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. import java.nio.*
  2. import java.nio.file.*
  3. /**
  4. * This will completely re-write a file, be careful.
  5. *
  6. * Simple Usage:
  7. *
  8. * modifyFile("C:\whatever\whatever.txt") {
  9. * if(it.contains("soil"))
  10. * return null // remove dirty word
  11. * else
  12. * return it
  13. * }
  14. *
  15. * The closure must return the line passed in to keep it in the file or alter it, any alteration
  16. * will be written in its place.
  17. *
  18. * To delete an entire line instead of changing it, return null
  19. * To add more lines after a given line return: it + "\n" + moreLines
  20. *
  21. * Notice that you add "\n" before your additional lines and not after the last
  22. * one because this method will normally add one for you.
  23. */
  24. def modifyFile(srcFile, Closure c) {
  25. modifyFile(srcFile, srcFile, c)
  26. }
  27. def modifyFile(srcFile, destFile, Closure c={println it;return it}) {
  28. StringBuffer ret = new StringBuffer();
  29. File src = new File(srcFile)
  30. File dest = new File(destFile)
  31. src.withReader{reader->
  32. reader.eachLine{
  33. def line=c(it)
  34. if(line != null) {
  35. ret.append(line)
  36. ret.append("\n")
  37. }
  38. }
  39. }
  40. dest.delete()
  41. dest.write(ret.toString())
  42. }
  43. /**
  44. * Copies a file specified at 'origin' to 'destination'.
  45. * If 'overwrite' is set to true any existing file at 'destination' is overwritten (defaults to false).
  46. */
  47. def copyFile(String origin, String destination, boolean overwrite=false){
  48. Path origPath = Paths.get(origin)
  49. Path destPath = Paths.get(destination)
  50. def fileAtDestination = destPath.toFile()
  51. if(fileAtDestination.exists()){
  52. if(overwrite) {
  53. fileAtDestination.delete()
  54. Files.copy(origPath, destPath)
  55. }
  56. else{
  57. println("Won't overwrite existing file $fileAtDestination")
  58. println("Call 'copyFile(orig, dest, true)' to delete the existing file first")
  59. }
  60. }
  61. else {
  62. // There's no file at the destination yet
  63. Files.copy(origPath, destPath)
  64. }
  65. }
  66. // Define methods visible to other Gradle scripts
  67. ext{
  68. modifyFile = this.&modifyFile
  69. copyFile = this.&copyFile
  70. }