internal/gen: add Repackage

Factored out often used functionality to rewrite files in a package that
are used used both for generation and the package itself.

Change-Id: I94da2afb701ffe9ebef333ac0ef504585f12af88
Reviewed-on: https://go-review.googlesource.com/17189
Reviewed-by: Hyang-Ah Hana Kim <hyangah@gmail.com>
diff --git a/currency/gen.go b/currency/gen.go
index c7d25dc..4739ab3 100644
--- a/currency/gen.go
+++ b/currency/gen.go
@@ -9,10 +9,8 @@
 package main
 
 import (
-	"bytes"
 	"flag"
 	"fmt"
-	"io/ioutil"
 	"log"
 	"os"
 	"sort"
@@ -39,7 +37,7 @@
 func main() {
 	gen.Init()
 
-	rewriteCommon()
+	gen.Repackage("gen_common.go", "common.go", "currency")
 
 	// Read the CLDR zip file.
 	r := gen.OpenCLDRCoreZip()
@@ -64,22 +62,6 @@
 	b.genSymbols(w, data)
 }
 
-func rewriteCommon() {
-	// Generate common.go
-	src, err := ioutil.ReadFile("gen_common.go")
-	if err != nil {
-		log.Fatal(err)
-	}
-	const toDelete = "// +build ignore\n\npackage main\n\n"
-	i := bytes.Index(src, []byte(toDelete))
-	if i < 0 {
-		log.Fatalf("could not find %q in gen_common.go", toDelete)
-	}
-	w := &bytes.Buffer{}
-	w.Write(src[i+len(toDelete):])
-	gen.WriteGoFile("common.go", "currency", w.Bytes())
-}
-
 var constants = []string{
 	// Undefined and testing.
 	"XXX", "XTS",