Class: Ro::Git

Inherits:
Object
  • Object
show all
Defined in:
lib/ro/git.rb

Defined Under Namespace

Classes: Error, Patch

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(root, options = {}) ⇒ Git

Returns a new instance of Git.



7
8
9
10
11
12
# File 'lib/ro/git.rb', line 7

def initialize(root, options = {})
  options = Map.for(options)

  @root = root
  @branch = options[:branch] || 'master'
end

Instance Attribute Details

#branchObject

Returns the value of attribute branch.



4
5
6
# File 'lib/ro/git.rb', line 4

def branch
  @branch
end

#patchingObject

Returns the value of attribute patching.



5
6
7
# File 'lib/ro/git.rb', line 5

def patching
  @patching
end

#rootObject

Returns the value of attribute root.



3
4
5
# File 'lib/ro/git.rb', line 3

def root
  @root
end

Instance Method Details

#patch(*args, &block) ⇒ Object

patch takes a block, allows abitrary edits (additions, modifications, deletions) to be performed by it, and then computes a single, atomic patch that is applied to the repo and pushed. the patch is returned. if the patch was not applied then patch.applied==false and it’s up to client code to decide how to proceed, perhaps retrying or saving the patchfile for later manual application



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
# File 'lib/ro/git.rb', line 21

def patch(*args, &block)
  options = Map.options_for!(args)

  user = options[:user] || ENV['USER'] || 'ro'
  msg = options[:message] || "#{ user } edits on #{ File.basename(@root).inspect }"
  add = options.has_key?(:add) ? options[:add] : true

  patch = nil

  Thread.exclusive do
    @root.lock do
      Dir.chdir(@root) do
        # ensure .git-ness
        #
          status, stdout, stderr = spawn("git rev-parse --git-dir", :raise => true, :capture => true)

          git_root = stdout.to_s.strip

          dot_git = File.expand_path(git_root)

          unless test(?d, dot_git)
            raise Error.new("missing .git directory #{ dot_git }")
          end

        # calculate a tmp branch name
        #
          time = Coerce.time(options[:time] || Time.now).utc.iso8601(2).gsub(/[^\w]/, '')
          branch = "#{ user }-#{ time }-#{ rand.to_s.gsub(/^0./, '') }"

        # allow block to edit, compute the patch, attempt to apply it
        #
          begin
          # get pristine
          #
            spawn("git checkout -f master", :raise => true)
            spawn("git fetch --all", :raise => true)
            spawn("git reset --hard origin/master", :raise => true)

          # pull recent changes
          #
            trying('to pull'){ spawn("git pull origin master") }

          # create a new temporary branch
          #
            spawn("git checkout -b #{ branch.inspect }", :raise => true)

          # the block can perform arbitrary edits
          #
            block.call

          # add all changes - additions, deletions, or modifications - unless :add => false was specified
          #
            if add
              spawn("git add . --all", :raise => true)
            end

          # commit if anything changed
          #
            changes_to_apply =
              spawn("git commit -m #{ msg.inspect }")

            if changes_to_apply
            # create the patch
            #
              status, stdout, stderr =
                spawn("git format-patch master --stdout", :raise => true, :capture => true)

              patch = Patch.new(:data => stdout, :name => branch)

              unless stdout.to_s.strip.empty?
              # apply the patch
              #
                spawn("git checkout master", :raise => true)

              #
                spawn("git rebase --abort")
                spawn("git am --abort")

                spawn("git am --abort")
                spawn("git rebase --abort")

              #
                status, stdout, stderr =
                  spawn("git am --signoff --3way --ignore-space-change --ignore-whitespace", :capture => true, :stdin => patch.data)

              #
                patch.applied = !!(status == 0)

              # commit the patch back to the repo
              #
                patch.committed =
                  begin
                    trying('to pull'){ spawn("git pull origin master") }
                    trying('to push'){ spawn("git push origin master") }
                    true
                  rescue Object
                    false
                  end
              end
            end
          ensure
          # get pristine
          #
            spawn("git checkout -f master", :raise => true)
            spawn("git fetch --all", :raise => true)
            spawn("git reset --hard origin/master", :raise => true)

            spawn("git am --abort")
            spawn("git rebase --abort")

          # get changes
          #
            trying('to pull'){ spawn("git pull") }

          # nuke the tmp branch
          #
            if patch and patch.applied and patch.committed
              spawn("git branch -D #{ branch.inspect }")
            end
          end
      end
    end
  end

  patch
end

#save(directory, options = {}) ⇒ Object



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
# File 'lib/ro/git.rb', line 204

def save(directory, options = {})
  if directory.is_a?(Node)
    directory = directory.path
  end

  options = Map.for(options)

  dir = File.expand_path(directory.to_s)

  relative_path = Ro.relative_path(dir, :from => @root)

  exists = test(?d, dir)

  action = exists ? 'edited' : 'created'

  msg = options[:message] || "#{ ENV['USER'] } #{ action } #{ relative_path }"

  @root.lock do
    FileUtils.mkdir_p(dir) unless exists

    Dir.chdir(dir) do
    # .git
    #
      status, stdout, stderr = spawn("git rev-parse --git-dir", :raise => true, :capture => true)

      git_root = stdout.to_s.strip

      dot_git = File.expand_path(git_root)

      unless test(?d, dot_git)
        raise Error.new("missing .git directory #{ dot_git }")
      end

    # correct branch
    #
      spawn("git checkout #{ @branch.inspect }", :raise => true)

    # return if nothing to do...
    #
      if `git status --porcelain`.strip.empty?
        return true
      end

    # commit the work
    #
      trying "to commit" do

        committed = 
          spawn("git add --all . && git commit -m #{ msg.inspect } -- .")

=begin
        unless committed
          spawn "git reset --hard"
        end
=end

#require 'pry'
#binding.pry
=begin
        retried = false
        begin
          spawn "git add --all . && git commit -m #{ msg.inspect } -- ."
          committed = true
        rescue
          raise if retried
          spawn "git reset --hard", :raise => false
          retry
        end
=end
      end


      trying "to push" do
        pushed = nil

        unless spawn("git push origin master")
        # merge
        #
          unless spawn("git pull")
            spawn("git checkout --ours -- .")
            spawn("git add --all .")
            spawn("git commit -F #{ dot_git }/MERGE_MSG")
          else
            raise 'wtf!?'
          end

          pushed = spawn("git push origin master")
        else
          pushed = true
        end

        pushed
      end

=begin
  git push

git pull

  # publish
  git checkout --ours -- .
  git add --all .
  git commit -F .git/MERGE_MSG
  git push
=end



    end
  end
end

#spawn(command, options = {}) ⇒ Object



351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
# File 'lib/ro/git.rb', line 351

def spawn(command, options = {})
  options = Map.for(options)

  status, stdout, stderr = systemu(command, :stdin => options[:stdin])

  Ro.log(:debug, "command: #{ command }")
  Ro.log(:debug, "status: #{ status }")
  Ro.log(:debug, "stdout:\n#{ stdout }")
  Ro.log(:debug, "stderr:\n#{ stderr }")

  if options[:raise] == true
    unless status == 0
      raise "command (#{ command }) failed with #{ status }"
    end
  end

  if options[:capture]
    [status, stdout, stderr]
  else
    status == 0
  end
end

#trying(*args, &block) ⇒ Object



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
# File 'lib/ro/git.rb', line 318

def trying(*args, &block)
  options = Map.options_for!(args)
  label = ['trying', *args].join(' - ')

  n = Integer(options[:n] || 3)
  timeout = options[:timeout]
  e = nil
  done = nil
  not_done = Object.new.freeze

  result =
    catch(:trying) do
      n.times do |i|
        done = block.call
        if done
          throw(:trying, done)
        else
          unless timeout == false
            sleep( (i + 1) * (timeout || (1 + rand)) )
          end
        end
      end

      not_done
    end

  if result == not_done
    raise(Error.new("#{ label } failed #{ n } times"))
  else
    done
  end
end