OLD | NEW |
(Empty) | |
| 1 // Copyright 2016 The Chromium Authors. All rights reserved. |
| 2 // Use of this source code is governed by a BSD-style license that can be |
| 3 // found in the LICENSE file. |
| 4 |
| 5 package common |
| 6 |
| 7 import ( |
| 8 "log" |
| 9 "os" |
| 10 "path" |
| 11 "path/filepath" |
| 12 ) |
| 13 |
| 14 // OutputWriterByFilePath returns |Writer| that writes to a file whose relative |
| 15 // path from config.OutputDir() is equivalent to the relative path from |
| 16 // config.SrcRootPath() to fileName. Also, the extension of the file is changed |
| 17 // from ".mojom" to |ext|. |
| 18 // |
| 19 // e.g. If |
| 20 // ext = ".d" |
| 21 // fileName = /alpha/beta/gamma/file.mojom |
| 22 // SrcRootPath = /alpha/ |
| 23 // OutputDir = /some/output/path/ |
| 24 // |
| 25 // The writer writes to /some/output/path/beta/gamma/file.d |
| 26 func OutputWriterByFilePath(fileName string, config GeneratorConfig, ext string)
Writer { |
| 27 fileName = changeExt(fileName, ext) |
| 28 outPath := outputFileByFilePath(fileName, config) |
| 29 |
| 30 return createAndOpen(outPath) |
| 31 } |
| 32 |
| 33 // outputFileByFilePath computes a file path such that the relative path |
| 34 // from config.SrcRootPath() to the returned path is equivalent to the relative |
| 35 // path from config.SrcRootPath() to fileName. |
| 36 // |
| 37 // e.g. If |
| 38 // fileName = /alpha/beta/gamma/file.mojom |
| 39 // SrcRootPath = /alpha/ |
| 40 // OutputDir = /some/output/path/ |
| 41 // |
| 42 // The returned path is /some/output/path/beta/gamma/file.mojom |
| 43 func outputFileByFilePath(fileName string, config GeneratorConfig) string { |
| 44 var err error |
| 45 relFileName, err := filepath.Rel(config.SrcRootPath(), fileName) |
| 46 if err != nil { |
| 47 log.Fatalln(err.Error()) |
| 48 } |
| 49 return filepath.Join(config.OutputDir(), relFileName) |
| 50 } |
| 51 |
| 52 // createAndOpen opens for writing the specified file. If the file or any part |
| 53 // of the directory structure in its path does not exist, they are created. |
| 54 func createAndOpen(outPath string) (file Writer) { |
| 55 // Create the directory that will contain the output. |
| 56 outDir := path.Dir(outPath) |
| 57 if err := os.MkdirAll(outDir, os.ModeDir|0770); err != nil && !os.IsExis
t(err) { |
| 58 log.Fatalln(err.Error()) |
| 59 } |
| 60 |
| 61 var err error |
| 62 file, err = os.OpenFile(outPath, os.O_WRONLY, 0660) |
| 63 if err != nil { |
| 64 log.Fatalln(err.Error()) |
| 65 } |
| 66 |
| 67 return |
| 68 } |
| 69 |
| 70 // changeExt changes the extension of a file to the specified extension. |
| 71 func changeExt(fileName string, ext string) string { |
| 72 return fileName[:len(fileName)-len(filepath.Ext(fileName))] + ext |
| 73 } |
OLD | NEW |