update-license.go 8.6 KB

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