plz / git / util.v
75 lines · 66 sloc · 1.97 KB · 1fbeec1ebbd6a39fe565a31e861235ae2a78dd52
Raw
1module git
2
3import strings
4import net.http
5import os
6
7pub fn parse_branch_name_from_receive_upload(upload string) ?string {
8 upload_lines := upload.split_into_lines()
9 if upload_lines.len == 0 {
10 return none
11 }
12 upload_header := upload_lines[0]
13 header_parts := upload_header.fields()
14 if header_parts.len < 3 {
15 return none
16 }
17 branch_reference := header_parts[2]
18 branch_name_raw := get_branch_name_from_reference(branch_reference)
19 branch_name := branch_name_raw.trim_space().trim('\0')
20 if branch_name.len == 0 {
21 return none
22 }
23 return branch_name
24}
25
26// parse_git_branch_with_last_hash parses output from `git branch -a`
27// returns the branch name
28pub fn parse_git_branch_output(output string) string {
29 output_parts := output.fields()
30 asterisk_or_branch_name := output_parts[0]
31 if asterisk_or_branch_name == '*' {
32 return output_parts[1]
33 }
34 return output_parts[0]
35}
36
37pub fn flush_packet() string {
38 return '0000'
39}
40
41pub fn write_packet(value string) string {
42 packet_length := (value.len + 4).hex()
43 return strings.repeat(`0`, 4 - packet_length.len) + packet_length + value
44}
45
46pub fn check_git_repo_url(url string) bool {
47 repo_url := remove_git_extension_if_exists(url)
48 refs_url := '${repo_url}/info/refs?service=git-upload-pack'
49 mut headers := http.new_header()
50 headers.add_custom('User-Agent', 'git/2.30.0') or {}
51 headers.add_custom('Git-Protocol', 'version=2') or {}
52 config := http.FetchConfig{
53 url: refs_url
54 header: headers
55 }
56 println('URL=$refs_url $config')
57 response := http.fetch(config) or { return false }
58 println('response=$response')
59 if response.status_code != 200 {
60 return false
61 }
62 return response.body.contains('service=git-upload-pack')
63}
64
65pub fn get_git_executable_path() ?string {
66 return os.find_abs_path_of_executable('git') or { none }
67}
68
69pub fn remove_git_extension_if_exists(git_repository_name string) string {
70 return git_repository_name.trim_string_right('.git')
71}
72
73fn get_branch_name_from_reference(value string) string {
74 return value.after('refs/heads/')
75}
76