update-license.go 8.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357
  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/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 getFiles() []string {
  133. cmd := exec.Command("git", "ls-tree", "-r", "--name-only", "HEAD")
  134. var files []string
  135. err := doLines(cmd, func(line string) {
  136. for _, p := range skipPrefixes {
  137. if strings.HasPrefix(line, p) {
  138. return
  139. }
  140. }
  141. ext := filepath.Ext(line)
  142. for _, wantExt := range extensions {
  143. if ext == wantExt {
  144. goto keep
  145. }
  146. }
  147. return
  148. keep:
  149. files = append(files, line)
  150. })
  151. if err != nil {
  152. log.Fatalf("error getting files:", err)
  153. }
  154. return files
  155. }
  156. var authorRegexp = regexp.MustCompile(`\s*[0-9]+\s*(.*)`)
  157. func gitAuthors(files []string) []string {
  158. cmds := []string{"shortlog", "-s", "-n", "-e", "HEAD", "--"}
  159. cmds = append(cmds, files...)
  160. cmd := exec.Command("git", cmds...)
  161. var authors []string
  162. err := doLines(cmd, func(line string) {
  163. m := authorRegexp.FindStringSubmatch(line)
  164. if len(m) > 1 {
  165. authors = append(authors, m[1])
  166. }
  167. })
  168. if err != nil {
  169. log.Fatalln("error getting authors:", err)
  170. }
  171. return authors
  172. }
  173. func readAuthors() []string {
  174. content, err := ioutil.ReadFile("AUTHORS")
  175. if err != nil && !os.IsNotExist(err) {
  176. log.Fatalln("error reading AUTHORS:", err)
  177. }
  178. var authors []string
  179. for _, a := range bytes.Split(content, []byte("\n")) {
  180. if len(a) > 0 && a[0] != '#' {
  181. authors = append(authors, string(a))
  182. }
  183. }
  184. // Retranslate existing authors through .mailmap.
  185. // This should catch email address changes.
  186. authors = mailmapLookup(authors)
  187. return authors
  188. }
  189. func mailmapLookup(authors []string) []string {
  190. if len(authors) == 0 {
  191. return nil
  192. }
  193. cmds := []string{"check-mailmap", "--"}
  194. cmds = append(cmds, authors...)
  195. cmd := exec.Command("git", cmds...)
  196. var translated []string
  197. err := doLines(cmd, func(line string) {
  198. translated = append(translated, line)
  199. })
  200. if err != nil {
  201. log.Fatalln("error translating authors:", err)
  202. }
  203. return translated
  204. }
  205. func writeAuthors(files []string) {
  206. merge := make(map[string]bool)
  207. // Add authors that Git reports as contributorxs.
  208. // This is the primary source of author information.
  209. for _, a := range gitAuthors(files) {
  210. merge[a] = true
  211. }
  212. // Add existing authors from the file. This should ensure that we
  213. // never lose authors, even if Git stops listing them. We can also
  214. // add authors manually this way.
  215. for _, a := range readAuthors() {
  216. merge[a] = true
  217. }
  218. // Write sorted list of authors back to the file.
  219. var result []string
  220. for a := range merge {
  221. result = append(result, a)
  222. }
  223. sort.Strings(result)
  224. content := new(bytes.Buffer)
  225. content.WriteString(authorsFileHeader)
  226. for _, a := range result {
  227. content.WriteString(a)
  228. content.WriteString("\n")
  229. }
  230. fmt.Println("writing AUTHORS")
  231. if err := ioutil.WriteFile("AUTHORS", content.Bytes(), 0644); err != nil {
  232. log.Fatalln(err)
  233. }
  234. }
  235. func getInfo(files <-chan string, out chan<- *info, wg *sync.WaitGroup) {
  236. for file := range files {
  237. stat, err := os.Lstat(file)
  238. if err != nil {
  239. fmt.Printf("ERROR %s: %v\n", file, err)
  240. continue
  241. }
  242. if !stat.Mode().IsRegular() {
  243. continue
  244. }
  245. info, err := fileInfo(file)
  246. if err != nil {
  247. fmt.Printf("ERROR %s: %v\n", file, err)
  248. continue
  249. }
  250. out <- info
  251. }
  252. wg.Done()
  253. }
  254. // fileInfo finds the lowest year in which the given file was commited.
  255. func fileInfo(file string) (*info, error) {
  256. info := &info{file: file, Year: int64(time.Now().Year())}
  257. cmd := exec.Command("git", "log", "--follow", "--find-copies", "--pretty=format:%ai", "--", file)
  258. err := doLines(cmd, func(line string) {
  259. y, err := strconv.ParseInt(line[:4], 10, 64)
  260. if err != nil {
  261. fmt.Printf("cannot parse year: %q", line[:4])
  262. }
  263. if y < info.Year {
  264. info.Year = y
  265. }
  266. })
  267. return info, err
  268. }
  269. func writeLicenses(infos <-chan *info) {
  270. for i := range infos {
  271. writeLicense(i)
  272. }
  273. }
  274. func writeLicense(info *info) {
  275. fi, err := os.Stat(info.file)
  276. if os.IsNotExist(err) {
  277. fmt.Println("skipping (does not exist)", info.file)
  278. return
  279. }
  280. if err != nil {
  281. log.Fatalf("error stat'ing %s: %v\n", info.file, err)
  282. }
  283. content, err := ioutil.ReadFile(info.file)
  284. if err != nil {
  285. log.Fatalf("error reading %s: %v\n", info.file, err)
  286. }
  287. // Construct new file content.
  288. buf := new(bytes.Buffer)
  289. licenseT.Execute(buf, info)
  290. if m := licenseCommentRE.FindIndex(content); m != nil && m[0] == 0 {
  291. buf.Write(content[:m[0]])
  292. buf.Write(content[m[1]:])
  293. } else {
  294. buf.Write(content)
  295. }
  296. // Write it to the file.
  297. if bytes.Equal(content, buf.Bytes()) {
  298. fmt.Println("skipping (no changes)", info.file)
  299. return
  300. }
  301. fmt.Println("writing", info.ShortLicense(), info.file)
  302. if err := ioutil.WriteFile(info.file, buf.Bytes(), fi.Mode()); err != nil {
  303. log.Fatalf("error writing %s: %v", info.file, err)
  304. }
  305. }
  306. func doLines(cmd *exec.Cmd, f func(string)) error {
  307. stdout, err := cmd.StdoutPipe()
  308. if err != nil {
  309. return err
  310. }
  311. if err := cmd.Start(); err != nil {
  312. return err
  313. }
  314. s := bufio.NewScanner(stdout)
  315. for s.Scan() {
  316. f(s.Text())
  317. }
  318. if s.Err() != nil {
  319. return s.Err()
  320. }
  321. if err := cmd.Wait(); err != nil {
  322. return fmt.Errorf("%v (for %s)", err, strings.Join(cmd.Args, " "))
  323. }
  324. return nil
  325. }