update-license.go 9.1 KB

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