code.go 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. // Copyright 2017 Google Inc. All Rights Reserved.
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. // Package printer provides support for writing generated code.
  15. package printer
  16. import (
  17. "fmt"
  18. )
  19. const indentation = " "
  20. // Code represents a file of code to be printed.
  21. type Code struct {
  22. text string
  23. indent int
  24. }
  25. // Print adds a line of code using the current indentation. Accepts printf-style format strings and arguments.
  26. func (c *Code) Print(args ...interface{}) {
  27. if len(args) > 0 {
  28. for i := 0; i < c.indent; i++ {
  29. c.text += indentation
  30. }
  31. c.text += fmt.Sprintf(args[0].(string), args[1:]...)
  32. }
  33. c.text += "\n"
  34. }
  35. // String returns the accumulated code as a string.
  36. func (c *Code) String() string {
  37. return c.text
  38. }
  39. // Indent adds one level of indentation.
  40. func (c *Code) Indent() {
  41. c.indent++
  42. }
  43. // Outdent remvoes one level of indentation.
  44. func (c *Code) Outdent() {
  45. c.indent--
  46. if c.indent < 0 {
  47. c.indent = 0
  48. }
  49. }