summaryrefslogtreecommitdiffstats
path: root/bdep/git.cxx
blob: 2a8155019f67070c50982cba801f8d32ad877839 (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
// file      : bdep/git.cxx -*- C++ -*-
// copyright : Copyright (c) 2014-2018 Code Synthesis Ltd
// license   : MIT; see accompanying LICENSE file

#include <bdep/git.hxx>

#include <libbutl/git.mxx>

#include <bdep/diagnostics.hxx>

using namespace butl;

namespace bdep
{
  static optional<semantic_version> git_ver;

  // Check that git is at least of the specified minimum supported version.
  //
  void
  git_check_version (const semantic_version& min_ver)
  {
    // Query and cache git version on the first call.
    //
    if (!git_ver)
    {
      // Make sure that the getline() function call doesn't end up with an
      // infinite recursion.
      //
      git_ver = semantic_version ();

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

      if (!s || !(git_ver = 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.
    //
    if (*git_ver < min_ver)
      fail << "unsupported git version " << *git_ver <<
        info << "minimum supported version is " << min_ver << endf;
  }

  optional<string>
  git_line (process&& pr, fdpipe&& pipe, bool ie)
  {
    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)))
        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>
    {
      return git_line (semantic_version {2, 1, 0},
                       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::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.
    //
    process pr;
    bool io (false);
    try
    {
      fdpipe pipe (fdopen_pipe ()); // Text mode seems appropriate.

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

      pipe.out.close ();
      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;
  }
}