コード例 #1
0
ファイル: handlers.go プロジェクト: disorganizer/brig
func handleCat(ctx *cli.Context, client *daemon.Client) error {
	repoPath := prefixSlash(ctx.Args().First())

	filePath := ""
	isStdoutMode := ctx.NArg() < 2

	if isStdoutMode {
		tmpFile, err := ioutil.TempFile("", ".brig-tmp-")
		if err != nil {
			return ExitCode{
				UnknownError,
				fmt.Sprintf("Unable to create temp file: %v", err),
			}
		}

		filePath = tmpFile.Name()
		defer util.Closer(tmpFile)
		defer func() {
			if err := os.Remove(filePath); err != nil {
				log.Warningf("Cannot remove temp-file: %v", err)
			}
		}()
	} else {
		absPath, err := filepath.Abs(ctx.Args()[1])
		if err != nil {
			return ExitCode{
				UnknownError,
				fmt.Sprintf("Unable to make abs path: %v: %v", filePath, err),
			}
		}

		filePath = absPath
	}

	if err := client.Cat(repoPath, filePath); err != nil {
		return ExitCode{
			UnknownError,
			fmt.Sprintf("Could not cat file: %v: %v", repoPath, err),
		}
	}

	if isStdoutMode {
		fd, err := os.Open(filePath)
		if err != nil {
			return ExitCode{
				UnknownError,
				"Could not open temp file",
			}
		}

		if _, err := io.Copy(os.Stdout, fd); err != nil {
			return ExitCode{
				UnknownError,
				fmt.Sprintf("Cannot copy to stdout: %v", err),
			}
		}

		if err := fd.Close(); err != nil {
			log.Warningf("Unable to close tmpfile handle: %v", err)
		}
	}

	return nil
}