summaryrefslogtreecommitdiff
path: root/src/other_tools/root_maps/commit_git_map.cpp
blob: d0b1025828f2592a3e0a5768a8b34bca46a301bc (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
// Copyright 2022 Huawei Cloud Computing Technology Co., Ltd.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

#include "src/other_tools/root_maps/commit_git_map.hpp"

#include <algorithm>

#include "src/buildtool/file_system/git_repo.hpp"
#include "src/utils/cpp/tmp_dir.hpp"

namespace {

[[nodiscard]] auto GitURLIsPath(std::string const& url) noexcept -> bool {
    auto prefixes = std::vector<std::string>{"ssh://", "http://", "https://"};
    // return true if no URL prefix exists
    return std::none_of(
        prefixes.begin(), prefixes.end(), [url](auto const& prefix) {
            return (url.rfind(prefix, 0) == 0);
        });
}

}  // namespace

/// \brief Create a CommitGitMap object
auto CreateCommitGitMap(
    gsl::not_null<CriticalGitOpMap*> const& critical_git_op_map,
    JustMR::PathsPtr const& just_mr_paths,
    std::size_t jobs) -> CommitGitMap {
    auto commit_to_git = [critical_git_op_map, just_mr_paths](auto ts,
                                                              auto setter,
                                                              auto logger,
                                                              auto /* unused */,
                                                              auto const& key) {
        // get root for repo (making sure that if repo is a path, it is
        // absolute)
        std::string fetch_repo = key.repo_url;
        if (GitURLIsPath(fetch_repo)) {
            fetch_repo = std::filesystem::absolute(fetch_repo).string();
        }
        std::filesystem::path repo_root =
            JustMR::Utils::GetGitRoot(just_mr_paths, fetch_repo);
        // ensure git repo
        // define Git operation to be done
        GitOpKey op_key = {
            {
                repo_root,     // target_path
                "",            // git_hash
                "",            // branch
                std::nullopt,  // message
                not just_mr_paths->git_checkout_locations.contains(
                    fetch_repo)  // init_bare
            },
            GitOpType::ENSURE_INIT};
        critical_git_op_map->ConsumeAfterKeysReady(
            ts,
            {std::move(op_key)},
            [key,
             fetch_repo,
             repo_root,
             critical_git_op_map,
             ts,
             setter,
             logger](auto const& values) {
                GitOpValue op_result = *values[0];
                // check flag
                if (not op_result.result) {
                    (*logger)("Git init failed",
                              /*fatal=*/true);
                    return;
                }
                // setup a wrapped_logger
                auto wrapped_logger = std::make_shared<AsyncMapConsumerLogger>(
                    [logger, target_path = repo_root](auto const& msg,
                                                      bool fatal) {
                        (*logger)(fmt::format("While ensuring commit for "
                                              "repository {}:\n{}",
                                              target_path.string(),
                                              msg),
                                  fatal);
                    });
                EnsureCommit(key,
                             fetch_repo,
                             repo_root,
                             op_result.git_cas,
                             critical_git_op_map,
                             ts,
                             setter,
                             wrapped_logger);
            },
            [logger, target_path = repo_root](auto const& msg, bool fatal) {
                (*logger)(fmt::format("While running critical Git op "
                                      "ENSURE_INIT for target {}:\n{}",
                                      target_path.string(),
                                      msg),
                          fatal);
            });
    };
    return AsyncMapConsumer<GitRepoInfo, nlohmann::json>(commit_to_git, jobs);
}

void EnsureCommit(GitRepoInfo const& repo_info,
                  std::string const& fetch_repo,
                  std::filesystem::path const& repo_root,
                  GitCASPtr const& git_cas,
                  gsl::not_null<CriticalGitOpMap*> const& critical_git_op_map,
                  gsl::not_null<TaskSystem*> const& ts,
                  CommitGitMap::SetterPtr const& ws_setter,
                  CommitGitMap::LoggerPtr const& logger) {
    // ensure commit exists, and fetch if needed
    auto git_repo = GitRepo::Open(git_cas);  // link fake repo to odb
    if (not git_repo) {
        (*logger)(
            fmt::format("Could not open repository {}", repo_root.string()),
            /*fatal=*/true);
        return;
    }
    // setup wrapped logger
    auto wrapped_logger = std::make_shared<AsyncMapConsumerLogger>(
        [logger](auto const& msg, bool fatal) {
            (*logger)(fmt::format("While checking commit exists:\n{}", msg),
                      fatal);
        });
    auto is_commit_present =
        git_repo->CheckCommitExists(repo_info.hash, wrapped_logger);
    if (is_commit_present == std::nullopt) {
        return;
    }
    if (not is_commit_present.value()) {
        // if commit not there, fetch it
        // get refspec for branch
        GitOpKey op_key = {{
                               repo_root,         // target_path
                               "",                // git_hash
                               repo_info.branch,  // branch
                           },
                           GitOpType::GET_BRANCH_REFNAME};
        critical_git_op_map->ConsumeAfterKeysReady(
            ts,
            {std::move(op_key)},
            [critical_git_op_map,
             git_cas,
             repo_info,
             fetch_repo,
             repo_root,
             ts,
             ws_setter,
             logger](auto const& values) {
                GitOpValue op_result = *values[0];
                // check flag
                if (not op_result.result) {
                    (*logger)("Get branch refname failed",
                              /*fatal=*/true);
                    return;
                }
                // ensure commit exists, and fetch if needed
                auto git_repo =
                    GitRepo::Open(git_cas);  // link fake repo to odb
                if (not git_repo) {
                    (*logger)(fmt::format("Could not open repository {}",
                                          repo_root.string()),
                              /*fatal=*/true);
                    return;
                }
                // do fetch
                auto tmp_dir = JustMR::Utils::CreateTypedTmpDir("fetch");
                if (not tmp_dir) {
                    (*logger)("Failed to create fetch tmp directory!",
                              /*fatal=*/true);
                    return;
                }
                // setup wrapped logger
                auto wrapped_logger = std::make_shared<AsyncMapConsumerLogger>(
                    [logger](auto const& msg, bool fatal) {
                        (*logger)(fmt::format(
                                      "While fetching via tmp repo:\n{}", msg),
                                  fatal);
                    });
                if (not git_repo->FetchViaTmpRepo(tmp_dir->GetPath(),
                                                  fetch_repo,
                                                  *op_result.result,
                                                  wrapped_logger)) {
                    return;
                }
                // setup wrapped logger
                wrapped_logger = std::make_shared<AsyncMapConsumerLogger>(
                    [logger](auto const& msg, bool fatal) {
                        (*logger)(fmt::format(
                                      "While checking commit exists:\n{}", msg),
                                  fatal);
                    });
                // check if commit exists now, after fetch
                auto is_commit_present =
                    git_repo->CheckCommitExists(repo_info.hash, wrapped_logger);
                if (not is_commit_present) {
                    return;
                }
                if (not *is_commit_present) {
                    // commit could not be fetched, so fail
                    (*logger)(fmt::format("Could not update commit from branch "
                                          "{} for remote {}",
                                          repo_info.branch,
                                          fetch_repo),
                              /*fatal=*/true);
                    return;
                }
                // keep tag
                GitOpKey op_key = {{
                                       repo_root,       // target_path
                                       repo_info.hash,  // git_hash
                                       "",              // branch
                                       "Keep referenced tree alive"  // message
                                   },
                                   GitOpType::KEEP_TAG};
                critical_git_op_map->ConsumeAfterKeysReady(
                    ts,
                    {std::move(op_key)},
                    [git_cas, repo_info, repo_root, ws_setter, logger](
                        auto const& values) {
                        GitOpValue op_result = *values[0];
                        // check flag
                        if (not op_result.result) {
                            (*logger)("Keep tag failed",
                                      /*fatal=*/true);
                            return;
                        }
                        // ensure commit exists, and fetch if needed
                        auto git_repo =
                            GitRepo::Open(git_cas);  // link fake repo to odb
                        if (not git_repo) {
                            (*logger)(
                                fmt::format("Could not open repository {}",
                                            repo_root.string()),
                                /*fatal=*/true);
                            return;
                        }
                        // setup wrapped logger
                        auto wrapped_logger =
                            std::make_shared<AsyncMapConsumerLogger>(
                                [logger](auto const& msg, bool fatal) {
                                    (*logger)(
                                        fmt::format("While getting subtree "
                                                    "from commit:\n{}",
                                                    msg),
                                        fatal);
                                });
                        // get tree id and return workspace root
                        auto subtree = git_repo->GetSubtreeFromCommit(
                            repo_info.hash, repo_info.subdir, wrapped_logger);
                        if (not subtree) {
                            return;
                        }
                        // set the workspace root
                        (*ws_setter)(nlohmann::json::array(
                            {"git tree", *subtree, repo_root}));
                    },
                    [logger, target_path = repo_root](auto const& msg,
                                                      bool fatal) {
                        (*logger)(fmt::format("While running critical Git op "
                                              "KEEP_TAG for target {}:\n{}",
                                              target_path.string(),
                                              msg),
                                  fatal);
                    });
            },
            [logger, target_path = repo_root](auto const& msg, bool fatal) {
                (*logger)(fmt::format("While running critical Git op "
                                      "GET_BRANCH_REFNAME for target {}:\n{}",
                                      target_path.string(),
                                      msg),
                          fatal);
            });
    }
    else {
        // setup wrapped logger
        auto wrapped_logger = std::make_shared<AsyncMapConsumerLogger>(
            [logger](auto const& msg, bool fatal) {
                (*logger)(
                    fmt::format("While getting subtree from commit:\n{}", msg),
                    fatal);
            });
        // get tree id and return workspace root
        auto subtree = git_repo->GetSubtreeFromCommit(
            repo_info.hash, repo_info.subdir, wrapped_logger);
        if (not subtree) {
            return;
        }
        // set the workspace root
        (*ws_setter)(nlohmann::json::array({"git tree", *subtree, repo_root}));
    }
}