| 1 | package commands |
| 2 | |
| 3 | import ( |
| 4 | "bytes" |
| 5 | "fmt" |
| 6 | "io" |
| 7 | "os" |
| 8 | "strings" |
| 9 | "sync" |
| 10 | |
| 11 | "github.com/git-lfs/git-lfs/v3/errors" |
| 12 | "github.com/git-lfs/git-lfs/v3/filepathfilter" |
| 13 | "github.com/git-lfs/git-lfs/v3/git" |
| 14 | "github.com/git-lfs/git-lfs/v3/lfs" |
| 15 | "github.com/git-lfs/git-lfs/v3/tq" |
| 16 | "github.com/git-lfs/git-lfs/v3/tr" |
| 17 | "github.com/git-lfs/pktline" |
| 18 | "github.com/spf13/cobra" |
| 19 | ) |
| 20 | |
| 21 | const ( |
| 22 | // cleanFilterBufferCapacity is the desired capacity of the |
| 23 | // `*git.PacketWriter`'s internal buffer when the filter protocol |
| 24 | // dictates the "clean" command. 512 bytes is (in most cases) enough to |
| 25 | // hold an entire LFS pointer in memory. |
| 26 | cleanFilterBufferCapacity = 512 |
| 27 | |
| 28 | // smudgeFilterBufferCapacity is the desired capacity of the |
| 29 | // `*git.PacketWriter`'s internal buffer when the filter protocol |
| 30 | // dictates the "smudge" command. |
| 31 | smudgeFilterBufferCapacity = pktline.MaxPacketLength |
| 32 | ) |
| 33 | |
| 34 | // filterSmudgeSkip is a command-line flag owned by the `filter-process` command |
| 35 | // dictating whether or not to skip the smudging process, leaving pointers as-is |
| 36 | // in the working tree. |
| 37 | var filterSmudgeSkip bool |
| 38 | |
| 39 | func filterCommand(cmd *cobra.Command, args []string) { |
| 40 | requireStdin(tr.Tr.Get("This command should be run by the Git filter process")) |
| 41 | setupRepository() |
| 42 | installHooks(false) |
| 43 | |
| 44 | s := git.NewFilterProcessScanner(os.Stdin, os.Stdout) |
| 45 | |
| 46 | if err := s.Init(); err != nil { |
| 47 | ExitWithError(err) |
| 48 | } |
| 49 | |
| 50 | caps, err := s.NegotiateCapabilities() |
| 51 | if err != nil { |
| 52 | ExitWithError(err) |
| 53 | } |
| 54 | |
| 55 | var supportsDelay bool |
| 56 | for _, cap := range caps { |
| 57 | if cap == "capability=delay" { |
| 58 | supportsDelay = true |
| 59 | break |
| 60 | } |
| 61 | } |
| 62 | |
| 63 | skip := filterSmudgeSkip || cfg.Os.Bool("GIT_LFS_SKIP_SMUDGE", false) |
| 64 | filter := filepathfilter.New(cfg.FetchIncludePaths(), cfg.FetchExcludePaths(), filepathfilter.GitIgnore, cfg.Git) |
| 65 | |
| 66 | ptrs := make(map[string]*lfs.Pointer) |
| 67 | |
| 68 | var q *tq.TransferQueue |
| 69 | var malformed []string |
| 70 | var malformedOnWindows []string |
| 71 | var closeOnce *sync.Once |
| 72 | var available chan *tq.Transfer |
| 73 | gitfilter := lfs.NewGitFilter(cfg) |
| 74 | for s.Scan() { |
| 75 | var n int64 |
| 76 | var err error |
| 77 | var delayed bool |
| 78 | var w *pktline.PktlineWriter |
| 79 | |
| 80 | req := s.Request() |
| 81 | |
| 82 | switch req.Header["command"] { |
| 83 | case "clean": |
| 84 | s.WriteStatus(statusFromErr(nil)) |
| 85 | w = pktline.NewPktlineWriter(os.Stdout, cleanFilterBufferCapacity) |
| 86 | |
| 87 | var ptr *lfs.Pointer |
| 88 | ptr, err = clean(gitfilter, w, req.Payload, req.Header["pathname"], -1) |
| 89 | |
| 90 | if ptr != nil { |
| 91 | n = ptr.Size |
| 92 | } |
| 93 | case "smudge": |
| 94 | if q == nil && supportsDelay { |
| 95 | closeOnce = new(sync.Once) |
| 96 | available = make(chan *tq.Transfer) |
| 97 | |
| 98 | if cfg.AutoDetectRemoteEnabled() { |
| 99 | // update current remote with information gained by treeish |
| 100 | newRemote := git.FirstRemoteForTreeish(req.Header["treeish"]) |
| 101 | if newRemote != "" { |
| 102 | cfg.SetRemote(newRemote) |
| 103 | } |
| 104 | } |
| 105 | |
| 106 | q = tq.NewTransferQueue( |
| 107 | tq.Download, |
| 108 | getTransferManifestOperationRemote("download", cfg.Remote()), |
| 109 | cfg.Remote(), |
| 110 | tq.RemoteRef(fetchRemoteRef()), |
| 111 | tq.WithBatchSize(cfg.TransferBatchSize()), |
| 112 | ) |
| 113 | go infiniteTransferBuffer(q, available) |
| 114 | } |
| 115 | |
| 116 | w = pktline.NewPktlineWriter(os.Stdout, smudgeFilterBufferCapacity) |
| 117 | if req.Header["can-delay"] == "1" { |
| 118 | var ptr *lfs.Pointer |
| 119 | |
| 120 | n, delayed, ptr, err = delayedSmudge(gitfilter, s, w, req.Payload, q, req.Header["pathname"], skip, filter) |
| 121 | |
| 122 | if delayed { |
| 123 | ptrs[req.Header["pathname"]] = ptr |
| 124 | } |
| 125 | } else { |
| 126 | s.WriteStatus(statusFromErr(nil)) |
| 127 | from, ferr := incomingOrCached(req.Payload, ptrs[req.Header["pathname"]]) |
| 128 | if ferr != nil { |
| 129 | break |
| 130 | } |
| 131 | |
| 132 | n, err = smudge(gitfilter, w, from, req.Header["pathname"], skip, filter) |
| 133 | if err == nil { |
| 134 | delete(ptrs, req.Header["pathname"]) |
| 135 | } |
| 136 | } |
| 137 | case "list_available_blobs": |
| 138 | closeOnce.Do(func() { |
| 139 | // The first time that Git sends us the |
| 140 | // 'list_available_blobs' command, it is given |
| 141 | // that now it waiting until all delayed blobs |
| 142 | // are available within this smudge filter call |
| 143 | // |
| 144 | // This means that, by the time that we're here, |
| 145 | // we have seen all entries in the checkout, and |
| 146 | // should therefore instruct the transfer queue |
| 147 | // to make a batch out of whatever remaining |
| 148 | // items it has, and then close itself. |
| 149 | // |
| 150 | // This function call is wrapped in a |
| 151 | // `sync.(*Once).Do()` call so we only call |
| 152 | // `q.Wait()` once, and is called via a |
| 153 | // goroutine since `q.Wait()` is blocking. |
| 154 | go q.Wait() |
| 155 | }) |
| 156 | |
| 157 | // The first, and all subsequent calls to |
| 158 | // list_available_blobs, we read items from `tq.Watch()` |
| 159 | // until a read from that channel becomes blocking (in |
| 160 | // other words, we read until there are no more items |
| 161 | // immediately ready to be sent back to Git). |
| 162 | paths := pathnames(readAvailable(available, q.BatchSize())) |
| 163 | if len(paths) == 0 { |
| 164 | // If `len(paths) == 0`, `tq.Watch()` has |
| 165 | // closed, indicating that all items have been |
| 166 | // completely processed, and therefore, sent |
| 167 | // back to Git for checkout. |
| 168 | for path, _ := range ptrs { |
| 169 | // If we sent a path to Git but it |
| 170 | // didn't ask for the smudge contents, |
| 171 | // that path is available and Git should |
| 172 | // accept it later. |
| 173 | paths = append(paths, fmt.Sprintf("pathname=%s", path)) |
| 174 | } |
| 175 | // At this point all items have been completely processed, |
| 176 | // so we explicitly close transfer queue. If Git issues |
| 177 | // another `smudge` command the transfer queue will be |
| 178 | // created from scratch. Transfer queue needs to be recreated |
| 179 | // because it has been already partially closed by `q.Wait()` |
| 180 | q = nil |
| 181 | } |
| 182 | err = s.WriteList(paths) |
| 183 | default: |
| 184 | ExitWithError(errors.New(tr.Tr.Get("unknown command %q", req.Header["command"]))) |
| 185 | } |
| 186 | |
| 187 | if errors.IsNotAPointerError(err) { |
| 188 | malformed = append(malformed, req.Header["pathname"]) |
| 189 | err = nil |
| 190 | } else if possiblyMalformedObjectSize(n) { |
| 191 | malformedOnWindows = append(malformedOnWindows, req.Header["pathname"]) |
| 192 | } |
| 193 | |
| 194 | var status git.FilterProcessStatus |
| 195 | if delayed { |
| 196 | // If delayed, there is no need to call w.Flush() since |
| 197 | // no data was written. Calculate the status from the |
| 198 | // given error using 'delayedStatusFromErr'. |
| 199 | status = delayedStatusFromErr(err) |
| 200 | } else if ferr := w.Flush(); ferr != nil { |
| 201 | // Otherwise, we do need to call w.Flush(), since we |
| 202 | // have to assume that data was written. If the flush |
| 203 | // operation was unsuccessful, calculate the status |
| 204 | // using 'statusFromErr'. |
| 205 | status = statusFromErr(ferr) |
| 206 | } else { |
| 207 | // If the above flush was successful, we calculate the |
| 208 | // status from the above clean, smudge, or |
| 209 | // list_available_blobs command using statusFromErr, |
| 210 | // since we did not delay. |
| 211 | status = statusFromErr(err) |
| 212 | } |
| 213 | |
| 214 | s.WriteStatus(status) |
| 215 | } |
| 216 | |
| 217 | if len(malformed) > 0 { |
| 218 | fmt.Fprintln(os.Stderr, tr.Tr.GetN( |
| 219 | "Encountered %d file that should have been a pointer, but wasn't:", |
| 220 | "Encountered %d files that should have been pointers, but weren't:", |
| 221 | len(malformed), |
| 222 | len(malformed), |
| 223 | )) |
| 224 | for _, m := range malformed { |
| 225 | fmt.Fprintf(os.Stderr, "\t%s\n", m) |
| 226 | } |
| 227 | } |
| 228 | |
| 229 | if len(malformedOnWindows) > 0 && cfg.Git.Bool("lfs.largefilewarning", !git.IsGitVersionAtLeast("2.34.0")) { |
| 230 | fmt.Fprintln(os.Stderr, tr.Tr.GetN( |
| 231 | "Encountered %d file that may not have been copied correctly on Windows:", |
| 232 | "Encountered %d files that may not have been copied correctly on Windows:", |
| 233 | len(malformedOnWindows), |
| 234 | len(malformedOnWindows), |
| 235 | )) |
| 236 | |
| 237 | for _, m := range malformedOnWindows { |
| 238 | fmt.Fprintf(os.Stderr, "\t%s\n", m) |
| 239 | } |
| 240 | |
| 241 | fmt.Fprint(os.Stderr, "\n", tr.Tr.Get("See: `git lfs help smudge` for more details."), "\n") |
| 242 | } |
| 243 | |
| 244 | if err := s.Err(); err != nil && err != io.EOF { |
| 245 | ExitWithError(err) |
| 246 | } |
| 247 | } |
| 248 | |
| 249 | // infiniteTransferBuffer streams the results of q.Watch() into "available" as |
| 250 | // if available had an infinite channel buffer. |
| 251 | func infiniteTransferBuffer(q *tq.TransferQueue, available chan<- *tq.Transfer) { |
| 252 | // Stream results from q.Watch() into chan "available" via an infinite |
| 253 | // buffer. |
| 254 | |
| 255 | watch := q.Watch() |
| 256 | |
| 257 | // pending is used to keep track of an ordered list of available |
| 258 | // `*tq.Transfer`'s that cannot be written to "available" without |
| 259 | // blocking. |
| 260 | var pending []*tq.Transfer |
| 261 | |
| 262 | for { |
| 263 | if len(pending) > 0 { |
| 264 | select { |
| 265 | case t, ok := <-watch: |
| 266 | if !ok { |
| 267 | // If the list of pending elements is |
| 268 | // non-empty, stream them out (even if |
| 269 | // they block), and then close(). |
| 270 | for _, t = range pending { |
| 271 | available <- t |
| 272 | } |
| 273 | close(available) |
| 274 | return |
| 275 | } |
| 276 | pending = append(pending, t) |
| 277 | case available <- pending[0]: |
| 278 | // Otherwise, dequeue and shift the first |
| 279 | // element from pending onto available. |
| 280 | pending = pending[1:] |
| 281 | } |
| 282 | } else { |
| 283 | t, ok := <-watch |
| 284 | if !ok { |
| 285 | // If watch is closed, the "tq" is done, and |
| 286 | // there are no items on the buffer. Return |
| 287 | // immediately. |
| 288 | close(available) |
| 289 | return |
| 290 | } |
| 291 | |
| 292 | select { |
| 293 | case available <- t: |
| 294 | // Copy an item directly from <-watch onto available<-. |
| 295 | default: |
| 296 | // Otherwise, if that would have blocked, make |
| 297 | // the new read pending. |
| 298 | pending = append(pending, t) |
| 299 | } |
| 300 | } |
| 301 | } |
| 302 | } |
| 303 | |
| 304 | // incomingOrCached returns an io.Reader that is either the contents of the |
| 305 | // given io.Reader "r", or the encoded contents of "ptr". It returns an error if |
| 306 | // there was an error reading from "r". |
| 307 | // |
| 308 | // This is done because when a `command=smudge` with `can-delay=0` is issued, |
| 309 | // the entry's contents are not sent, and must be re-encoded from the stored |
| 310 | // pointer corresponding to the request's filepath. |
| 311 | func incomingOrCached(r io.Reader, ptr *lfs.Pointer) (io.Reader, error) { |
| 312 | buf := make([]byte, 1024) |
| 313 | n, err := r.Read(buf) |
| 314 | buf = buf[:n] |
| 315 | |
| 316 | if n == 0 { |
| 317 | if ptr == nil { |
| 318 | // If we read no data from the given io.Reader "r" _and_ |
| 319 | // there was no data to fall back on, return an empty |
| 320 | // io.Reader yielding no data. |
| 321 | return bytes.NewReader(buf), nil |
| 322 | } |
| 323 | // If we read no data from the given io.Reader "r", _and_ there |
| 324 | // is a pointer that we can fall back on, return an io.Reader |
| 325 | // that yields the encoded version of the given pointer. |
| 326 | return strings.NewReader(ptr.Encoded()), nil |
| 327 | } |
| 328 | |
| 329 | if err == io.EOF { |
| 330 | return bytes.NewReader(buf), nil |
| 331 | } |
| 332 | return io.MultiReader(bytes.NewReader(buf), r), err |
| 333 | } |
| 334 | |
| 335 | // readAvailable satisfies the accumulation semantics for the |
| 336 | // 'list_available_blobs' command. It accumulates items until: |
| 337 | // |
| 338 | // 1. Reading from the channel of available items blocks, or ... |
| 339 | // 2. There is one item available, or ... |
| 340 | // 3. The 'tq.TransferQueue' is completed. |
| 341 | func readAvailable(ch <-chan *tq.Transfer, cap int) []*tq.Transfer { |
| 342 | ts := make([]*tq.Transfer, 0, cap) |
| 343 | |
| 344 | for { |
| 345 | select { |
| 346 | case t, ok := <-ch: |
| 347 | if !ok { |
| 348 | return ts |
| 349 | } |
| 350 | ts = append(ts, t) |
| 351 | default: |
| 352 | if len(ts) > 0 { |
| 353 | return ts |
| 354 | } |
| 355 | |
| 356 | t, ok := <-ch |
| 357 | if !ok { |
| 358 | return ts |
| 359 | } |
| 360 | return append(ts, t) |
| 361 | } |
| 362 | } |
| 363 | } |
| 364 | |
| 365 | // pathnames formats a list of *tq.Transfers as a valid response to the |
| 366 | // 'list_available_blobs' command. |
| 367 | func pathnames(ts []*tq.Transfer) []string { |
| 368 | pathnames := make([]string, 0, len(ts)) |
| 369 | for _, t := range ts { |
| 370 | pathnames = append(pathnames, fmt.Sprintf("pathname=%s", t.Name)) |
| 371 | } |
| 372 | |
| 373 | return pathnames |
| 374 | } |
| 375 | |
| 376 | // statusFromErr returns the status code that should be sent over the filter |
| 377 | // protocol based on a given error, "err". |
| 378 | func statusFromErr(err error) git.FilterProcessStatus { |
| 379 | if err != nil && err != io.EOF { |
| 380 | return git.StatusError |
| 381 | } |
| 382 | return git.StatusSuccess |
| 383 | } |
| 384 | |
| 385 | // delayedStatusFromErr returns the status code that should be sent over the |
| 386 | // filter protocol based on a given error, "err" when the blob smudge operation |
| 387 | // was delayed. |
| 388 | func delayedStatusFromErr(err error) git.FilterProcessStatus { |
| 389 | status := statusFromErr(err) |
| 390 | |
| 391 | switch status { |
| 392 | case git.StatusSuccess: |
| 393 | return git.StatusDelay |
| 394 | default: |
| 395 | return status |
| 396 | } |
| 397 | } |
| 398 | |
| 399 | func init() { |
| 400 | RegisterCommand("filter-process", filterCommand, func(cmd *cobra.Command) { |
| 401 | cmd.Flags().BoolVarP(&filterSmudgeSkip, "skip", "s", false, "") |
| 402 | }) |
| 403 | } |