| 1 | /** |
| 2 | * Copyright (c) Meta Platforms, Inc. and affiliates. |
| 3 | * |
| 4 | * This source code is licensed under the MIT license found in the |
| 5 | * LICENSE file in the root directory of this source tree. |
| 6 | */ |
| 7 | |
| 8 | import {parsePatch} from 'shared/patch/parse'; |
| 9 | import type {DiffType, ParsedDiff} from 'shared/patch/types'; |
| 10 | |
| 11 | export function parsePatchAndFilter(patch: string): ReturnType<typeof parsePatch> { |
| 12 | const result = parsePatch(patch); |
| 13 | return result.filter( |
| 14 | // empty patches and other weird situations can cause invalid files to get parsed, ignore these entirely |
| 15 | diff => diff.hunks.length > 0 || diff.newFileName != null || diff.oldFileName != null, |
| 16 | ); |
| 17 | } |
| 18 | |
| 19 | /** Similar to how uncommitted changes are sorted, sort first by type, then by filename. */ |
| 20 | export function sortFilesByType(files: Array<ParsedDiff>) { |
| 21 | files.sort((a, b) => { |
| 22 | if (a.type === b.type) { |
| 23 | const pathA = a.newFileName ?? a.oldFileName ?? ''; |
| 24 | const pathB = b.newFileName ?? b.oldFileName ?? ''; |
| 25 | return pathA.localeCompare(pathB); |
| 26 | } else { |
| 27 | return ( |
| 28 | (a.type == null ? SORT_LAST : sortKeyForType[a.type]) - |
| 29 | (b.type == null ? SORT_LAST : sortKeyForType[b.type]) |
| 30 | ); |
| 31 | } |
| 32 | }); |
| 33 | } |
| 34 | const SORT_LAST = 10; |
| 35 | const sortKeyForType: Record<DiffType, number> = { |
| 36 | Modified: 0, |
| 37 | Renamed: 1, |
| 38 | Added: 2, |
| 39 | Copied: 3, |
| 40 | Removed: 4, |
| 41 | }; |
| 42 | |