MCPcopy Create free account
hub / github.com/cli/cli / readFileRun

Function readFileRun

pkg/cmd/repo/read-file/read_file.go:128–211  ·  view source on GitHub ↗
(opts *ReadFileOptions)

Source from the content-addressed store, hash-verified

126}
127
128func readFileRun(opts *ReadFileOptions) error {
129 httpClient, err := opts.HttpClient()
130 if err != nil {
131 return err
132 }
133
134 repo, err := opts.BaseRepo()
135 if err != nil {
136 return fmt.Errorf("%w. Run this command from within a git repository, or use the `--repo` flag to specify one", err)
137 }
138
139 file, err := fetchFile(httpClient, repo, opts.Path, opts.Ref)
140 if err != nil {
141 return err
142 }
143
144 // If the API didn't return the file content inline, it'll set the encoding to "none" (e.g. for large files).
145 contentAvailable := file.Encoding != "none"
146
147 if opts.Exporter != nil {
148 // Only pay for the file content when the caller actually selected the content field.
149 if !contentAvailable && slices.Contains(opts.Exporter.Fields(), "content") {
150 if err := loadContent(httpClient, repo, file, opts.Ref); err != nil {
151 return err
152 }
153 }
154 return opts.Exporter.Write(opts.IO, file)
155 }
156
157 if !contentAvailable {
158 if err := loadContent(httpClient, repo, file, opts.Ref); err != nil {
159 return err
160 }
161 }
162
163 if opts.Output != "" {
164 dest, err := writeToOutput(file, opts.Output, opts.Clobber)
165 if err != nil {
166 return err
167 }
168 if opts.IO.IsStdoutTTY() {
169 cs := opts.IO.ColorScheme()
170 fmt.Fprintf(opts.IO.ErrOut, "%s Wrote %s to %s\n", cs.SuccessIcon(), file.Path, dest)
171 }
172 return nil
173 }
174
175 if len(file.Content) == 0 {
176 cs := opts.IO.ColorScheme()
177 fmt.Fprintf(opts.IO.ErrOut, "%s file is empty\n", cs.WarningIcon())
178 return nil
179 }
180
181 // read-file does its own escape-sequence guarding below, so it writes raw
182 // bytes through ContentOut in passthrough mode. Leaving sanitization on
183 // would corrupt binary files and strip the escapes that
184 // --allow-escape-sequences explicitly allows.
185 opts.IO.SetContentSanitization(false)

Callers 2

NewCmdReadFileFunction · 0.85
Test_readFileRunFunction · 0.85

Calls 15

BinaryContentTypeFunction · 0.92
FormatSizeFunction · 0.92
ContainsEscapeSequenceFunction · 0.92
fetchFileFunction · 0.85
loadContentFunction · 0.85
writeToOutputFunction · 0.85
ContainsMethod · 0.80
IsStdoutTTYMethod · 0.80
ColorSchemeMethod · 0.80
SuccessIconMethod · 0.80
WarningIconMethod · 0.80

Tested by 1

Test_readFileRunFunction · 0.68