update-license.go 8.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370
  1. // +build none
  2. /*
  3. This command generates GPL license headers on top of all source files.
  4. You can run it once per month, before cutting a release or just
  5. whenever you feel like it.
  6. go run update-license.go
  7. All authors (people who have contributed code) are listed in the
  8. AUTHORS file. The author names are mapped and deduplicated using the
  9. .mailmap file. You can use .mailmap to set the canonical name and
  10. address for each author. See git-shortlog(1) for an explanation of the
  11. .mailmap format.
  12. Please review the resulting diff to check whether the correct
  13. copyright assignments are performed.
  14. */
  15. package main
  16. import (
  17. "bufio"
  18. "bytes"
  19. "fmt"
  20. "io/ioutil"
  21. "log"
  22. "os"
  23. "os/exec"
  24. "path/filepath"
  25. "regexp"
  26. "runtime"
  27. "sort"
  28. "strconv"
  29. "strings"
  30. "sync"
  31. "text/template"
  32. "time"
  33. )
  34. var (
  35. // only files with these extensions will be considered
  36. extensions = []string{".go", ".js", ".qml"}
  37. // paths with any of these prefixes will be skipped
  38. skipPrefixes = []string{
  39. // boring stuff
  40. "vendor/", "tests/files/", "build/",
  41. // don't relicense vendored sources
  42. "crypto/sha3/", "crypto/ecies/", "logger/glog/",
  43. "crypto/secp256k1/curve.go",
  44. // don't license generated files
  45. "contracts/chequebook/contract/",
  46. "contracts/ens/contract/",
  47. "contracts/release/contract.go",
  48. }
  49. // paths with this prefix are licensed as GPL. all other files are LGPL.
  50. gplPrefixes = []string{"cmd/"}
  51. // this regexp must match the entire license comment at the
  52. // beginning of each file.
  53. licenseCommentRE = regexp.MustCompile(`^//\s*(Copyright|This file is part of).*?\n(?://.*?\n)*\n*`)
  54. // this text appears at the start of AUTHORS
  55. authorsFileHeader = "# This is the official list of go-ethereum authors for copyright purposes.\n\n"
  56. )
  57. // this template generates the license comment.
  58. // its input is an info structure.
  59. var licenseT = template.Must(template.New("").Parse(`
  60. // Copyright {{.Year}} The go-ethereum Authors
  61. // This file is part of {{.Whole false}}.
  62. //
  63. // {{.Whole true}} is free software: you can redistribute it and/or modify
  64. // it under the terms of the GNU {{.License}} as published by
  65. // the Free Software Foundation, either version 3 of the License, or
  66. // (at your option) any later version.
  67. //
  68. // {{.Whole true}} is distributed in the hope that it will be useful,
  69. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  70. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  71. // GNU {{.License}} for more details.
  72. //
  73. // You should have received a copy of the GNU {{.License}}
  74. // along with {{.Whole false}}. If not, see <http://www.gnu.org/licenses/>.
  75. `[1:]))
  76. type info struct {
  77. file string
  78. Year int64
  79. }
  80. func (i info) License() string {
  81. if i.gpl() {
  82. return "General Public License"
  83. }
  84. return "Lesser General Public License"
  85. }
  86. func (i info) ShortLicense() string {
  87. if i.gpl() {
  88. return "GPL"
  89. }
  90. return "LGPL"
  91. }
  92. func (i info) Whole(startOfSentence bool) string {
  93. if i.gpl() {
  94. return "go-ethereum"
  95. }
  96. if startOfSentence {
  97. return "The go-ethereum library"
  98. }
  99. return "the go-ethereum library"
  100. }
  101. func (i info) gpl() bool {
  102. for _, p := range gplPrefixes {
  103. if strings.HasPrefix(i.file, p) {
  104. return true
  105. }
  106. }
  107. return false
  108. }
  109. func main() {
  110. var (
  111. files = getFiles()
  112. filec = make(chan string)
  113. infoc = make(chan *info, 20)
  114. wg sync.WaitGroup
  115. )
  116. writeAuthors(files)
  117. go func() {
  118. for _, f := range files {
  119. filec <- f
  120. }
  121. close(filec)
  122. }()
  123. for i := runtime.NumCPU(); i >= 0; i-- {
  124. // getting file info is slow and needs to be parallel.
  125. // it traverses git history for each file.
  126. wg.Add(1)
  127. go getInfo(filec, infoc, &wg)
  128. }
  129. go func() {
  130. wg.Wait()
  131. close(infoc)
  132. }()
  133. writeLicenses(infoc)
  134. }
  135. func skipFile(path string) bool {
  136. if strings.Contains(path, "/testdata/") {
  137. return true
  138. }
  139. for _, p := range skipPrefixes {
  140. if strings.HasPrefix(path, p) {
  141. return true
  142. }
  143. }
  144. return false
  145. }
  146. func getFiles() []string {
  147. cmd := exec.Command("git", "ls-tree", "-r", "--name-only", "HEAD")
  148. var files []string
  149. err := doLines(cmd, func(line string) {
  150. if skipFile(line) {
  151. return
  152. }
  153. ext := filepath.Ext(line)
  154. for _, wantExt := range extensions {
  155. if ext == wantExt {
  156. goto keep
  157. }
  158. }
  159. return
  160. keep:
  161. files = append(files, line)
  162. })
  163. if err != nil {
  164. log.Fatalf("error getting files:", err)
  165. }
  166. return files
  167. }
  168. var authorRegexp = regexp.MustCompile(`\s*[0-9]+\s*(.*)`)
  169. func gitAuthors(files []string) []string {
  170. cmds := []string{"shortlog", "-s", "-n", "-e", "HEAD", "--"}
  171. cmds = append(cmds, files...)
  172. cmd := exec.Command("git", cmds...)
  173. var authors []string
  174. err := doLines(cmd, func(line string) {
  175. m := authorRegexp.FindStringSubmatch(line)
  176. if len(m) > 1 {
  177. authors = append(authors, m[1])
  178. }
  179. })
  180. if err != nil {
  181. log.Fatalln("error getting authors:", err)
  182. }
  183. return authors
  184. }
  185. func readAuthors() []string {
  186. content, err := ioutil.ReadFile("AUTHORS")
  187. if err != nil && !os.IsNotExist(err) {
  188. log.Fatalln("error reading AUTHORS:", err)
  189. }
  190. var authors []string
  191. for _, a := range bytes.Split(content, []byte("\n")) {
  192. if len(a) > 0 && a[0] != '#' {
  193. authors = append(authors, string(a))
  194. }
  195. }
  196. // Retranslate existing authors through .mailmap.
  197. // This should catch email address changes.
  198. authors = mailmapLookup(authors)
  199. return authors
  200. }
  201. func mailmapLookup(authors []string) []string {
  202. if len(authors) == 0 {
  203. return nil
  204. }
  205. cmds := []string{"check-mailmap", "--"}
  206. cmds = append(cmds, authors...)
  207. cmd := exec.Command("git", cmds...)
  208. var translated []string
  209. err := doLines(cmd, func(line string) {
  210. translated = append(translated, line)
  211. })
  212. if err != nil {
  213. log.Fatalln("error translating authors:", err)
  214. }
  215. return translated
  216. }
  217. func writeAuthors(files []string) {
  218. merge := make(map[string]bool)
  219. // Add authors that Git reports as contributorxs.
  220. // This is the primary source of author information.
  221. for _, a := range gitAuthors(files) {
  222. merge[a] = true
  223. }
  224. // Add existing authors from the file. This should ensure that we
  225. // never lose authors, even if Git stops listing them. We can also
  226. // add authors manually this way.
  227. for _, a := range readAuthors() {
  228. merge[a] = true
  229. }
  230. // Write sorted list of authors back to the file.
  231. var result []string
  232. for a := range merge {
  233. result = append(result, a)
  234. }
  235. sort.Strings(result)
  236. content := new(bytes.Buffer)
  237. content.WriteString(authorsFileHeader)
  238. for _, a := range result {
  239. content.WriteString(a)
  240. content.WriteString("\n")
  241. }
  242. fmt.Println("writing AUTHORS")
  243. if err := ioutil.WriteFile("AUTHORS", content.Bytes(), 0644); err != nil {
  244. log.Fatalln(err)
  245. }
  246. }
  247. func getInfo(files <-chan string, out chan<- *info, wg *sync.WaitGroup) {
  248. for file := range files {
  249. stat, err := os.Lstat(file)
  250. if err != nil {
  251. fmt.Printf("ERROR %s: %v\n", file, err)
  252. continue
  253. }
  254. if !stat.Mode().IsRegular() {
  255. continue
  256. }
  257. info, err := fileInfo(file)
  258. if err != nil {
  259. fmt.Printf("ERROR %s: %v\n", file, err)
  260. continue
  261. }
  262. out <- info
  263. }
  264. wg.Done()
  265. }
  266. // fileInfo finds the lowest year in which the given file was commited.
  267. func fileInfo(file string) (*info, error) {
  268. info := &info{file: file, Year: int64(time.Now().Year())}
  269. cmd := exec.Command("git", "log", "--follow", "--find-renames=80", "--find-copies=80", "--pretty=format:%ai", "--", file)
  270. err := doLines(cmd, func(line string) {
  271. y, err := strconv.ParseInt(line[:4], 10, 64)
  272. if err != nil {
  273. fmt.Printf("cannot parse year: %q", line[:4])
  274. }
  275. if y < info.Year {
  276. info.Year = y
  277. }
  278. })
  279. return info, err
  280. }
  281. func writeLicenses(infos <-chan *info) {
  282. for i := range infos {
  283. writeLicense(i)
  284. }
  285. }
  286. func writeLicense(info *info) {
  287. fi, err := os.Stat(info.file)
  288. if os.IsNotExist(err) {
  289. fmt.Println("skipping (does not exist)", info.file)
  290. return
  291. }
  292. if err != nil {
  293. log.Fatalf("error stat'ing %s: %v\n", info.file, err)
  294. }
  295. content, err := ioutil.ReadFile(info.file)
  296. if err != nil {
  297. log.Fatalf("error reading %s: %v\n", info.file, err)
  298. }
  299. // Construct new file content.
  300. buf := new(bytes.Buffer)
  301. licenseT.Execute(buf, info)
  302. if m := licenseCommentRE.FindIndex(content); m != nil && m[0] == 0 {
  303. buf.Write(content[:m[0]])
  304. buf.Write(content[m[1]:])
  305. } else {
  306. buf.Write(content)
  307. }
  308. // Write it to the file.
  309. if bytes.Equal(content, buf.Bytes()) {
  310. fmt.Println("skipping (no changes)", info.file)
  311. return
  312. }
  313. fmt.Println("writing", info.ShortLicense(), info.file)
  314. if err := ioutil.WriteFile(info.file, buf.Bytes(), fi.Mode()); err != nil {
  315. log.Fatalf("error writing %s: %v", info.file, err)
  316. }
  317. }
  318. func doLines(cmd *exec.Cmd, f func(string)) error {
  319. stdout, err := cmd.StdoutPipe()
  320. if err != nil {
  321. return err
  322. }
  323. if err := cmd.Start(); err != nil {
  324. return err
  325. }
  326. s := bufio.NewScanner(stdout)
  327. for s.Scan() {
  328. f(s.Text())
  329. }
  330. if s.Err() != nil {
  331. return s.Err()
  332. }
  333. if err := cmd.Wait(); err != nil {
  334. return fmt.Errorf("%v (for %s)", err, strings.Join(cmd.Args, " "))
  335. }
  336. return nil
  337. }