| // Copyright 2019 The Fuchsia Authors. All rights reserved. |
| // Use of this source code is governed by a BSD-style license that can be |
| // found in the LICENSE file. |
| |
| package gotidy |
| |
| import ( |
| "fmt" |
| "go/scanner" |
| "go/token" |
| "strings" |
| ) |
| |
| var ( |
| copyrightTemplate = strings.TrimSpace(` |
| // Copyright %d The Fuchsia Authors. All rights reserved. |
| // Use of this source code is governed by a BSD-style license that can be |
| // found in the LICENSE file.`) |
| ) |
| |
| // AddCopyrightHeader inserts the Fuchsia copyright header into a file if no copyright |
| // header is present. |
| type AddCopyrightHeader struct { |
| Year int |
| } |
| |
| func (t *AddCopyrightHeader) Tidy(input []byte) ([]byte, error) { |
| var s scanner.Scanner |
| fset := token.NewFileSet() |
| file := fset.AddFile("", fset.Base(), len(input)) // register file |
| s.Init(file, input, nil /* no error handler */, scanner.ScanComments) |
| |
| for { |
| pos, tok, literal := s.Scan() |
| // We scanned the entire file without finding the header. |
| if tok == token.EOF { |
| return t.addCopyrightHeader(input) |
| } |
| |
| // We moved past the start of the file. It's missing the header. |
| if tok == token.COMMENT && pos > 1 { |
| return t.addCopyrightHeader(input) |
| } |
| |
| if tok == token.COMMENT { |
| // The file starts with a comment and it has the header |
| if strings.HasPrefix(strings.ToLower(literal), "// copyright") { |
| return input, nil |
| } |
| return t.addCopyrightHeader(input) |
| } |
| } |
| } |
| |
| func (t *AddCopyrightHeader) addCopyrightHeader(input []byte) ([]byte, error) { |
| header := fmt.Sprintf(copyrightTemplate, t.Year) |
| return []byte(header + "\n\n" + string(input)), nil |
| } |