Git лог граф в массив - PullRequest
       7

Git лог граф в массив

2 голосов
/ 17 марта 2019

Мне нужно преобразовать вывод журнала git в объект.

Я использую команду git log --all --graph --oneline --date-order.

* 8896805 (origin/firstbranch) test(firstbranch): this is my commit on this branch
| * 5fef2da (HEAD -> testbranch, origin/another, another) refactor(another): this is a change
| * 2a34d72 refactor(another): typo
| * 683d704 refactor(another): changes
* |   0120274 Merge remote-tracking branch 'origin/develop' into firstbranch
|\ \

После этого я создал массив, в котором каждый элементмассив соответствует строке этого вывода.

И с этим, я хотел бы иметь такой массив:

[
    {
        art: "*",
        commitHash: "8896805",
        branches: ["origin/firstbranch"],
        commitString: "test(firstbranch): this is my commit on this branch"
    },
    {
        art: "| *",
        commitHash: "5fef2da",
        branches: ["testbranch", "origin/another", "another"],
        commitString: "refactor(another): this is a change"
    },
    {
        art: "| *",
        commitHash: "2a34d72",
        branches: [],
        commitString: "refactor(another): typo"
    },
    {
        art: "| *",
        commitHash: "683d704",
        branches: [],
        commitString: "refactor(another): changes"
    },
    {
        art: "* |",
        commitHash: "0120274",
        branches: [],
        commitString: "Merge remote-tracking branch 'origin/develop' into firstbranch"
    },
    {
        art: "|\ \",
        commitHash: "",
        branches: [],
        commitString: ""
    }
]

Но я не могу получить этот результат.

Спасибо заранее!

Ответы [ 2 ]

1 голос
/ 17 марта 2019

Вот возможное решение с использованием одного регулярного выражения, затем обрезка каждого значения и, наконец, разбиение ветвления в массив:

const input = [
  '* 8896805 (origin/firstbranch) test(firstbranch): this is my commit on this branch',
  '| * 5fef2da (HEAD -> testbranch, origin/another, another) refactor(another): this is a change',
  '| * 2a34d72 refactor(another): typo',
  '| * 683d704 refactor(another): changes',
  '* |   0120274 Merge remote-tracking branch \'origin/develop\' into firstbranch',
  '|\\ \\'
];

const result = input.map(entry => {
  let [, alt, commitHash, branches, commitString] = entry
    .match(/^([|*\s\\]+)(?:\s+([a-f0-9]+)?(?:\s+\((?:HEAD\s+->\s+)?([^)]+)\))?(?:\s+(.*))?)?$/)
    .map(value => value ? value.trim() : '');
  branches = branches ? branches.split(/\s*,\s*/) : [];
  return {alt, commitHash, branches, commitString};
});

console.log(result);
1 голос
/ 17 марта 2019

Вы можете сделать что-то подобное с регулярным выражением.

  1. alt регулярное выражение
    • ^\W+ - соответствует всем несловесным символам в начале строки.
  2. commitHash регулярное выражение
    • \w+ - соответствует всем символам слова, и мы выбираем только первое совпадение
  3. branches regex
    • /\(.*?\)/ - Это соответствует всем ветвям ( branches here )
    • теперь из ветвей совпадений мы заменяем (Head -> и () заменой
  4. commit регулярное выражение
    • /.*?\)|\W+/ - Заменить все символы до первого ) или все несловесные символы.

let str = `* 8896805 (origin/firstbranch) test(firstbranch): this is my commit on this branch
| * 5fef2da (HEAD -> testbranch, origin\/another, another) refactor(another): this is a change
| * 2a34d72 refactor(another): typo
| * 683d704 refactor(another): changes
* |   0120274 Merge remote-tracking branch 'origin/develop' into firstbranch
|\\ \\`

let splited = str.split('\n')

let op = splited.map(inp=>{
  let alt = "" 
  inp = inp.replace(/^\W+/,(match)=>{alt=match; return ''})
  
  let commitHash = ''
  inp = inp.replace(/\s*(\w+)\s*/,(match,g1)=>{commitHash = g1;return ''})
  let branches = ''
  inp = inp.replace(/^\s*(\(.*?\))/,(match,g1)=>{branches = g1; return ''})
  branches = branches ? branches.replace(/^\s*\(HEAD\s*->\s*|[)(]/g,'').split(/\s*,\s*/) : []
  let commit = inp.trim()
  return {alt,commitHash,branches,commit}
})

console.log(op)

На стороне Примечание: - Обратите внимание, что это не полное доказательство.я рассмотрел случаи согласно предоставленным данным, но может быть намного больше случаев

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...