aboutsummaryrefslogtreecommitdiff
path: root/bdep/git.cxx
blob: f9bdc04346d80111ffffce9eddbdfeceb9bdf0b9 (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
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
// file      : bdep/git.cxx -*- C++ -*-
// license   : MIT; see accompanying LICENSE file

#include <bdep/git.hxx>

#include <libbutl/git.hxx>

#include <bdep/diagnostics.hxx>

using namespace butl;

namespace bdep
{
  static pair<process_path, optional<string>> sys_git;
  static optional<semantic_version>           sys_git_ver;

// On POSIX the system git is always assumed.
//
#ifndef _WIN32
  static pair<process_path, optional<string>>& bun_git     (sys_git);
  static optional<semantic_version>&           bun_git_ver (sys_git_ver);
#else
  static pair<process_path, optional<string>> bun_git;
  static optional<semantic_version>           bun_git_ver;
#endif

  bool
  git_try_check_version (const semantic_version& min_ver, bool system)
  {
    // Query and cache git version on the first call.
    //
    optional<semantic_version>& gv (system ? sys_git_ver : bun_git_ver);

    if (!gv)
    {
      // Make sure that the getline() function call doesn't end up with an
      // infinite recursion.
      //
      gv = semantic_version ();

      optional<string> s (
        git_line (*gv, system, false /* ignore_error */, "--version"));

      if (!s || !(gv = git_version (*s)))
        fail << "unable to obtain git version";
    }

    // Note that we don't expect the min_ver to contain the build component,
    // that doesn't matter functionality-wise for git.
    //
    return *gv >= min_ver;
  }

  // As above but issue diagnostics and fail if git is older than the
  // specified minimum supported version.
  //
  void
  git_check_version (const semantic_version& min_ver, bool system)
  {
    if (!git_try_check_version (min_ver, system))
    {
      optional<semantic_version>& gv (system ? sys_git_ver : bun_git_ver);

      assert (gv); // Must have been cached by git_try_check_version().

      fail << "unsupported git version " << *gv <<
        info << "minimum supported version is " << min_ver << endf;
    }
  }

  // Return git process path and the --exec-path option, if it is required for
  // the execution.
  //
  const pair<process_path, optional<string>>&
  git_search (bool system)
  {
    tracer trace ("git_search");

    // On the first call search for the git process path, calculate the
    // --exec-path option value required for its execution, and cache them for
    // subsequent use.
    //
    pair<process_path, optional<string>>& git (system ? sys_git : bun_git);

    if (git.first.empty ())
    {
      // On startup git prepends the PATH environment variable value with the
      // computed directory path where its sub-programs are supposedly located
      // (--exec-path option, GIT_EXEC_PATH environment variable, etc; see
      // cmd_main() in git's git.c for details).
      //
      // Then, when git needs to run itself or one of its components as a
      // child process, it resolves the full executable path searching in
      // directories listed in PATH (see locate_in_PATH() in git's
      // run-command.c for details).
      //
      // On Windows we install git and its components into a place where it is
      // not expected to be, which results in the wrong path in PATH as set by
      // git (for example, c:/build2/libexec/git-core) which in turn may lead
      // to running some other git that appears in the PATH variable. To
      // prevent this we pass the git's exec directory via the --exec-path
      // option explicitly.
      //
      process_path pp;

#ifdef _WIN32

      // Figure out the bundle absolute directory path based on our own
      // process path and realize it for comparison. Though, we only need it
      // when searching for the system git.
      //
      dir_path bd;

      if (system)
      {
        // We should be able to construct/realize our process path so we don't
        // handle invalid_path.
        //
        bd = path (process::path_search (argv0, true /* init */).
                   effect_string ()).directory ().realize ();

        // Search in PATH first and fallback to the bundle directory.
        //
        pp = process::path_search ("git",
                                   true /* init */,
                                   bd,
                                   true /* path_only */);
      }
      else
#endif
        pp = process::path_search ("git", true /* init */);

      optional<string> ep;
#ifdef _WIN32

      // Note that we need to add --exec-path not only if the bundled git is
      // requested but also if we ended up with the bundled git while
      // searching for the system one.

      // Realize for comparison.
      //
      // We should be able to realize the existing program parent directory
      // path so we don't handle invalid_path.
      //
      dir_path d (pp.effect.directory ().realize ());

      if (!system || d == bd)
        ep = "--exec-path=" + d.string ();

      l4 ([&]{trace << (system ? "system: '" : "bundled: '") << pp.effect
                    << "'" << (ep ? ' ' + *ep : "");});
#endif

      git = make_pair (move (pp), move (ep));
    }

    return git;
  }

  optional<string>
  git_line (process&& pr, fdpipe&& pipe, bool ie, char delim)
  {
    optional<string> r;

    bool io (false);
    try
    {
      pipe.out.close ();
      ifdstream is (move (pipe.in), fdstream_mode::skip, ifdstream::badbit);

      string l;
      if (!eof (getline (is, l, delim)))
        r = move (l);

      is.close (); // Detect errors.
    }
    catch (const io_error&)
    {
      io = true; // Presumably git failed so check that first.
    }

    // Note: cannot use finish() since ignoring normal error.
    //
    if (!pr.wait ())
    {
      const process_exit& e (*pr.exit);

      if (!e.normal ())
        fail << "process git " << e;

      if (ie)
        r = nullopt;
      else
        throw failed (); // Assume git issued diagnostics.
    }
    else if (io)
      fail << "unable to read git output";

    return r;
  }

  url
  git_remote_url (const dir_path& repo,
                  const char* opt,
                  const char* what,
                  const char* cfg)
  {
    auto git_config = [&repo] (const char* name) -> optional<string>
    {
      // It's unlikely that the remote URL is configured globally, thus we use
      // the bundled git.
      //
      return git_line (semantic_version {2, 1, 0},
                       false /* system */,
                       repo,
                       true  /* ignore_error */,
                       "config",
                       "--get",
                       name);
    };

    auto parse_url = [] (const string& s, const char* w)
    {
      try
      {
        return url (s);
      }
      catch (const invalid_argument& e)
      {
        fail << "invalid " << w << " value '" << s << "': " << e << endf;
      }
    };

    // First try the custom config value if specified.
    //
    if (cfg != nullptr)
    {
      if (optional<string> l = git_config (cfg))
      {
        return parse_url (*l, cfg);
      }
    }

    // Next is remote.origin.build2Url.
    //
    if (optional<string> l = git_config ("remote.origin.build2Url"))
    {
      return parse_url (*l, "remote.origin.build2Url");
    }

    // Finally, get remote.origin.url and try to derive an HTTPS URL from it.
    //
    if (optional<string> l = git_config ("remote.origin.url"))
    {
      string& s (*l);

      // This one will be fuzzy and hairy. Here are some representative
      // examples of what we can encounter:
      //
      //            example.org:/path/to/repo.git
      //       user@example.org:/path/to/repo.git
      //       user@example.org:~user/path/to/repo.git
      // ssh://user@example.org/path/to/repo.git
      //
      // git://example.org/path/to/repo.git
      //
      // http://example.org/path/to/repo.git
      // https://example.org/path/to/repo.git
      //
      //        /path/to/repo.git
      // file:///path/to/repo.git
      //
      // Note that git seem to always make remote.origin.url absolute in
      // case of a local filesystem path.
      //
      // So the algorithm will be as follows:
      //
      // 1. If there is scheme, then parse as URL.
      //
      // 2. Otherwise, check if this is an absolute path.
      //
      // 3. Otherwise, assume SSH <host>:<path> thing.
      //
      url u;

      // Find the scheme.
      //
      // Note that in example.org:/path/... example.org is a valid scheme. To
      // distinguish this, we check if the scheme contains any dots (none of
      // the schemes recognized by git currently do and probably never will).
      //
      size_t p (s.find (':'));
      if (p != string::npos                       && // Has ':'.
          url::traits_type::find (s, p) == 0      && // Scheme starts at 0.
          s.rfind ('.', p - 1) == string::npos)      // No dots in scheme.
      {
        u = parse_url (s, "remote.origin.url");
      }
      else
      {
        // Absolute path or the SSH thing.
        //
        if (path_traits::absolute (s))
        {
          // This is what we want to end up with:
          //
          // file:///tmp
          // file:///c:/tmp
          //
          const char* h (s[0] == '/' ? "file://" : "file:///");
          u = parse_url (h + s, "remote.origin.url");
        }
        else if (p != string::npos)
        {
          // This can still include user (user@host) so let's add the scheme,
          // replace/erase ':', and parse it as a string representation of a
          // URL.
          //
          if (s[p + 1] == '/') // POSIX notation.
            s.erase (p, 1);
          else
            s[p] = '/';

          u = parse_url ("ssh://" + s, "remote.origin.url");
        }
        else
          fail << "invalid remote.origin.url value '" << s << "': not a URL";
      }

      // A remote URL gotta have authority.
      //
      if (u.authority)
      {
        if (u.scheme == "http" || u.scheme == "https")
        {
          // This can still include the user which we most likely don't want.
          //
          u.authority->user.clear ();
          return u;
        }

        // Derive an HTTPS URL from a remote URL (and hope for the best).
        //
        if (u.scheme != "file" && u.path)
          return url ("https", u.authority->host, *u.path);
      }

      diag_record dr (fail);

      dr << "unable to derive " << what << " from " << u;

      dr << info << "consider setting git ";
      if (cfg != nullptr)
        dr << cfg << " or ";
      dr << "remote.origin.build2Url value";

      if (opt != nullptr)
        dr << info << "or use " << opt << " to specify explicitly";
    }

    // We don't necessarily want to suggest remote.origin.build2* or the
    // option since preferably this should be derived automatically from
    // remote.origin.url.
    //
    fail << "unable to discover " << what << ": no git remote.origin.url "
         << "value" << endf;
  }

  git_repository_status
  git_status (const dir_path& repo)
  {
    git_repository_status r;

    // git-status --porcelain=2 (available since git 2.11.0) gives us all the
    // information with a single invocation.
    //
    fdpipe pipe (open_pipe ()); // Text mode seems appropriate.

    process pr (start_git (semantic_version {2, 11, 0},
                           false /* system */,
                           repo,
                           0     /* stdin  */,
                           pipe  /* stdout */,
                           2     /* stderr */,
                           "status",
                           "--porcelain=2",
                           "--branch"));

    // Shouldn't throw, unless something is severely damaged.
    //
    pipe.out.close ();

    bool io (false);
    try
    {
      ifdstream is (move (pipe.in), fdstream_mode::skip, ifdstream::badbit);

      // Lines starting with '#' are headers (come first) with any other line
      // indicating some kind of change.
      //
      // The headers we are interested in are:
      //
      // # branch.oid <commit>  | (initial)       Current commit.
      // # branch.head <branch> | (detached)      Current branch.
      // # branch.upstream <upstream_branch>      If upstream is set.
      // # branch.ab +<ahead> -<behind>           If upstream is set and
      //                                          the commit is present.
      //
      // Note that if we are in the detached HEAD state, then we will only
      // see the first two with branch.head being '(detached)'.
      //
      for (string l; !eof (getline (is, l)); )
      {
        char c (l[0]);

        if (c == '#')
        {
          if (l.compare (2, 10, "branch.oid") == 0)
          {
            r.commit = string (l, 13);

            if (r.commit == "(initial)")
              r.commit.clear ();
          }
          else if (l.compare (2, 11, "branch.head") == 0)
          {
            r.branch = string (l, 14);

            if (r.branch == "(detached)")
              r.branch.clear ();
          }
          else if (l.compare (2, 15, "branch.upstream") == 0)
          {
            r.upstream = string (l, 18);
          }
          else if (l.compare (2, 9, "branch.ab") == 0)
          {
            // Both +<ahead> and -<behind> are always present, even if 0.
            //
            size_t a (l.find ('+', 12)); assert (a != string::npos);
            size_t b (l.find ('-', 12)); assert (b != string::npos);

            if (l[a + 1] != '0') r.ahead  = true;
            if (l[b + 1] != '0') r.behind = true;
          }

          continue; // Some other header.
        }

        // Change line. For tracked entries it has the following format:
        //
        // 1 <XY> ...
        // 2 <XY> ...
        //
        // Where <XY> is a two-character field with X describing the staged
        // status and Y -- unstaged and with '.' indicating no change.
        //
        // All other lines (untracked/unmerged entries) we treat as an
        // indication of an unstaged change (see git-status(1) for details).
        //
        if (c == '1' || c == '2')
        {
          if (l[2] != '.') r.staged   = true;
          if (l[3] != '.') r.unstaged = true;
        }
        else
          r.unstaged = true;

        // Skip the rest if we already know the outcome (remember, headers
        // always come first).
        //
        if (r.staged && r.unstaged)
          break;
      }

      is.close (); // Detect errors.
    }
    catch (const io_error&)
    {
      // Presumably the child process failed and issued diagnostics so let
      // finish_git() try to deal with that.
      //
      io = true;
    }

    finish_git (pr, io);

    return r;
  }
}