Class: Squared::Repo::Workspace

Inherits:
Object
  • Object
show all
Includes:
Format, Rake::DSL, Common, System, Task
Defined in:
lib/squared/repo/workspace.rb

Class Attribute Summary collapse

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Methods included from Common

#as_a, #get, #message, #set

Constructor Details

#initialize(main) ⇒ Workspace

Returns a new instance of Workspace.



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
# File 'lib/squared/repo/workspace.rb', line 53

def initialize(main)
  prompt = lambda do |path|
    return false unless path.directory?

    confirm "#{log_title(:warn)} \"#{sub_style(path, :bold)}\" is not empty. Continue with installation? [y/N] "
  end
  @main = main.to_s
  @home = if (val = env('REPO_HOME'))
            home = Pathname.new(val)
            if @main == home.basename.to_s
              @root = home.parent
              if home.exist?
                @root = nil unless home.directory?
              elsif !@root.exist?
                @root.mkpath
              elsif !empty?(@root)
                if prompt.(@root)
                  @override = true
                else
                  @root = nil
                end
              end
            end
            raise ArgumentError, message('REPO_HOME', val, hint: 'invalid') unless @root

            home.realdirpath
          elsif (val = env('REPO_ROOT'))
            @root = Pathname.new(val).realdirpath
            if !@root.exist?
              @root.mkpath
            elsif !empty?(@root)
              raise ArgumentError, message('REPO_ROOT', val, hint: 'exist') unless prompt.(@root)

              @override = true
            end
            @root.join(@main).realdirpath
          else
            empty?(pwd = Pathname.pwd) ? pwd.join(@main) : pwd
          end
  @root ||= @home.parent
  @series = TASK_NAME.dup
  @styles = {}
  @project = {}
  @exception = !env('PIPE_FAIL', ignore: '0').nil?
  @pipe = !env('PIPE_OUT', ignore: '0').nil?
  @verbose = true
end

Class Attribute Details

.project_kindObject (readonly)

Returns the value of attribute project_kind.



45
46
47
# File 'lib/squared/repo/workspace.rb', line 45

def project_kind
  @project_kind
end

Instance Attribute Details

#exceptionObject

Returns the value of attribute exception.



51
52
53
# File 'lib/squared/repo/workspace.rb', line 51

def exception
  @exception
end

#homeObject (readonly)

Returns the value of attribute home.



50
51
52
# File 'lib/squared/repo/workspace.rb', line 50

def home
  @home
end

#mainObject (readonly)

Returns the value of attribute main.



50
51
52
# File 'lib/squared/repo/workspace.rb', line 50

def main
  @main
end

#manifestObject

Returns the value of attribute manifest.



51
52
53
# File 'lib/squared/repo/workspace.rb', line 51

def manifest
  @manifest
end

#manifest_urlObject

Returns the value of attribute manifest_url.



51
52
53
# File 'lib/squared/repo/workspace.rb', line 51

def manifest_url
  @manifest_url
end

#rootObject (readonly)

Returns the value of attribute root.



50
51
52
# File 'lib/squared/repo/workspace.rb', line 50

def root
  @root
end

#scriptObject

Returns the value of attribute script.



51
52
53
# File 'lib/squared/repo/workspace.rb', line 51

def script
  @script
end

#seriesObject (readonly)

Returns the value of attribute series.



50
51
52
# File 'lib/squared/repo/workspace.rb', line 50

def series
  @series
end

#stylesObject

Returns the value of attribute styles.



51
52
53
# File 'lib/squared/repo/workspace.rb', line 51

def styles
  @styles
end

#verboseObject

Returns the value of attribute verbose.



51
52
53
# File 'lib/squared/repo/workspace.rb', line 51

def verbose
  @verbose
end

Class Method Details

.find(path: nil, ref: nil) ⇒ Object



37
38
39
40
41
42
43
# File 'lib/squared/repo/workspace.rb', line 37

def find(path: nil, ref: nil)
  if ref.is_a?(::Symbol) || ref.is_a?(::String)
    ret = project_kind.find { |proj| proj.to_sym == ref.to_sym }
    return ret if ret
  end
  project_kind.find { |proj| proj.is_a?(path) } if path
end

.implement(*objs) ⇒ Object



25
26
27
28
29
30
31
32
33
34
35
# File 'lib/squared/repo/workspace.rb', line 25

def implement(*objs)
  objs.each do |obj|
    next unless obj < Project::Base

    project_kind.unshift(obj)
    obj.tasks&.each do |val|
      TASK_NAME[val] = []
      TASK_BASE[val] = obj
    end
  end
end

Instance Method Details

#add(name, dir = nil, **kwargs) ⇒ Object



122
123
124
125
126
127
128
129
130
131
132
133
134
# File 'lib/squared/repo/workspace.rb', line 122

def add(name, dir = nil, **kwargs)
  path = (dir || name).to_s
  ref = kwargs[:ref]
  project = if !ref.is_a?(::Class)
              Workspace.find(path: root_path(path), ref: ref)
            elsif ref < Project::Base
              ref
            end
  instance = (project || Project::Base).new(name, path, self, **kwargs)
  @project[n = name.to_sym] = instance
  get(:project)[n] = instance
  self
end

#apply(&block) ⇒ Object



292
293
294
295
# File 'lib/squared/repo/workspace.rb', line 292

def apply(&block)
  instance_eval(&block)
  self
end

#bool_match(val, pat) ⇒ Object



335
336
337
338
339
340
341
342
343
344
345
346
# File 'lib/squared/repo/workspace.rb', line 335

def bool_match(val, pat)
  case val
  when nil, ''
    pat.is_a?(::Regexp) ? pat : nil
  when '0'
    false
  when '1'
    true
  else
    Regexp.new(val)
  end
end

#build(default: nil, parallel: []) ⇒ Object



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
# File 'lib/squared/repo/workspace.rb', line 136

def build(default: nil, parallel: [])
  group = {}
  parent = {}
  incl = Set.new
  @project.each do |name, proj|
    next unless proj.enabled?

    @series.each do |key, items|
      target = "#{name}:#{key}"
      case key
      when :build, :refresh, :depend, :outdated, :doc, :copy, :clean
        next unless proj.has?(key) || ::Rake::Task.task_defined?(target)
      else
        next unless task_defined?(proj, key)
      end
      if proj.group
        incl << proj.group
        (group[:"#{key}:#{proj.group}"] ||= []).push(target)
      else
        items << target
      end
      next unless (base = find_base(proj))

      id = base.to_sym.to_s
      next if id == proj.group

      incl << id
      (parent[:"#{key}:#{id}"] ||= []).push(target)
    end
    proj.populate
  end
  @series.merge!(parent) if incl.size > 1
  @series.merge!(group)
  if @manifest_url && (empty?(@root) || @override)
    branch = env('REPO_MANIFEST') || read_manifest
    target = branch || @manifest
    stage = nil
    failfast = true
    cmd = []
    newline = ARGV.index { |val| val.start_with?('repo:') }.to_i > 0
    parse_opts = lambda do |args|
      collect_args(args, :opts).each do |val|
        case val
        when 'no-fail'
          failfast = false
        when 'force'
          cmd << '--force-checkout'
        when 'rebase'
          cmd << '--rebase'
        when 'detach'
          cmd << '--detach'
        when 'gc'
          cmd << '--auto-gc'
        when 'no-update'
          cmd << '--no-manifest-update'
        end
      end
    end
    status = lambda do |val, alt = nil|
      ver = branch || alt
      ver ? message('repo', val.sub('{0}', 'opts*=force,rebase,detach,gc,no-update,no-fail'), ver) : 'inactive'
    end

    namespace :repo do |repo|
      desc status.('all[{0}]')
      task :all, [:opts] do |_, args|
        parse_opts.(args)
        stage ||= :all
        repo[:sync].invoke
        # rubocop:disable Style/CombinableLoops
        @project.each_value { |proj| proj.depend if proj.enabled? }
        @project.each_value do |proj|
          next unless proj.enabled? && proj.build?

          proj.has?(:dev) ? proj.refresh : proj.build
        end
        # rubocop:enable Style/CombinableLoops
      end

      desc status.("init[manifest?=#{target},{0}]", target)
      task :init, [:manifest, :opts] do |_, args|
        parse_opts.(args)
        stage = :init
        puts if newline
        system("repo init -u #{@manifest_url} -m #{args.manifest || target}.xml", chdir: @root)
        repo[:all].invoke
      end

      desc status.('sync[{0}]')
      task :sync, [:opts] do |_, args|
        raise LoadError, message('repo is not initialized', 'rake repo:init') unless branch || stage == :init

        parse_opts.(args)
        cmd << "-j#{ENV.fetch('REPO_JOBS', ::Rake::CpuCounter.count)}"
        cmd << '--fail-fast' if failfast
        puts if newline && stage != :init
        begin
          shell("repo sync #{cmd.join(' ')}", chdir: @root, exception: failfast)
        rescue StandardError => e
          emphasize(e, title: "rake stash repo:#{stage || :sync}")
          raise
        end
      end
    end
  end
  return unless enabled?

  multi = env('REPO_SYNC', ignore: '0') ? [] : parallel.map(&:to_sym)
  output = dev? ? :refresh : :build

  task default: default || output

  desc 'all[git?=rebase|stash]'
  task :all, [:git] do |_, args|
    sync = ->(key) { multi.include?(key) ? :"#{key}:sync" : key }
    pull = case args.git
           when 'rebase'
             sync.(:rebase)
           when 'stash'
             invoke sync.(:stash)
             sync.(:pull)
           else
             sync.(:pull)
           end
    invoke(pull, exception: @exception)
    invoke(output, exception: @exception)
  end

  desc 'init'
  task init: [:depend, output]

  @series.each do |key, items|
    next if items.empty?

    unless (valid = multi.include?(key))
      group = key.to_s
      valid = multi.include?(group.split(':').first.to_sym) if group.include?(':')
    end
    if valid
      desc "#{key} (thread)"
      multitask key => items

      desc "#{key} (sync)"
      task "#{key}:sync": items
    else
      desc key.to_s
      task key => items
    end
  end
end

#compose(name, &block) ⇒ Object



287
288
289
290
# File 'lib/squared/repo/workspace.rb', line 287

def compose(name, &block)
  namespace(name, &block)
  self
end

#dev?(pat = nil, script: nil) ⇒ Boolean

Returns:

  • (Boolean)


373
374
375
# File 'lib/squared/repo/workspace.rb', line 373

def dev?(pat = nil, script: nil)
  with?(pat, script: script, state: @dev)
end

#empty?(dir) ⇒ Boolean

Returns:

  • (Boolean)


348
349
350
351
352
353
354
355
# File 'lib/squared/repo/workspace.rb', line 348

def empty?(dir)
  return true if dir.empty? || dir.join('.repo').directory?
  return true if dir.children.size == 1 && dir.join(dir.children.first).to_s == __FILE__

  dir == @root && !env('REPO_ROOT').nil? && @root.children.none? do |path|
    path.directory? && !path.basename.to_s.start_with?('.') && path.to_s != @home.to_s
  end
end

#enabled?Boolean

Returns:

  • (Boolean)


357
358
359
# File 'lib/squared/repo/workspace.rb', line 357

def enabled?
  !@series[:build].empty? || !@series[:doc].empty?
end

#env(key, equals: nil, ignore: nil) ⇒ Object



307
308
309
310
311
312
# File 'lib/squared/repo/workspace.rb', line 307

def env(key, equals: nil, ignore: nil)
  ret = ENV.fetch("#{key}_#{@main.gsub(/[^\w]/, '_').upcase}", ENV[key]).to_s
  return ret == equals.to_s if equals

  ret.empty? || as_a(ignore).any? { |val| ret == val.to_s } ? nil : ret
end

#find_base(obj) ⇒ Object



331
332
333
# File 'lib/squared/repo/workspace.rb', line 331

def find_base(obj)
  Workspace.project_kind.find { |proj| obj.instance_of?(proj) }
end

#home_path(*args) ⇒ Object



327
328
329
# File 'lib/squared/repo/workspace.rb', line 327

def home_path(*args)
  @home.join(*args)
end

#multitask?Boolean

Returns:

  • (Boolean)


361
362
363
364
365
366
367
# File 'lib/squared/repo/workspace.rb', line 361

def multitask?
  ::Rake::Task.tasks.any? do |item|
    next unless item.already_invoked

    item.name.end_with?(':sync') || (!item.name.include?(':') && !item.name.start_with?('all', 'init'))
  end
end

#pipe?Boolean

Returns:

  • (Boolean)


383
384
385
# File 'lib/squared/repo/workspace.rb', line 383

def pipe?
  @pipe
end

#prod?(pat = nil, script: nil) ⇒ Boolean

Returns:

  • (Boolean)


377
378
379
380
381
# File 'lib/squared/repo/workspace.rb', line 377

def prod?(pat = nil, script: nil)
  return false if @dev == true || !@prod

  with?(pat, script: script, state: @prod)
end

#read_manifestObject



314
315
316
317
318
319
320
321
# File 'lib/squared/repo/workspace.rb', line 314

def read_manifest
  require 'rexml/document'
  file = root_path('.repo/manifest.xml')
  return unless file.exist?

  doc = REXML::Document.new(File.read(file))
  doc.elements['manifest/include'].attributes['name']&.sub('.xml', '')
end

#repo(url, manifest = 'latest') ⇒ Object



101
102
103
104
105
# File 'lib/squared/repo/workspace.rb', line 101

def repo(url, manifest = 'latest')
  @manifest_url = url
  @manifest = manifest
  self
end

#root_path(*args) ⇒ Object



323
324
325
# File 'lib/squared/repo/workspace.rb', line 323

def root_path(*args)
  @root.join(*args)
end

#run(script, **kwargs) ⇒ Object



107
108
109
110
111
112
113
114
115
116
117
118
119
120
# File 'lib/squared/repo/workspace.rb', line 107

def run(script, **kwargs)
  @script = case (val = env('REPO_BUILD'))
            when 'verbose'
              "#{script}:verbose"
            when 'silent'
              @verbose = false
              script
            else
              val || script
            end
  @dev = bool_match(env('REPO_DEV'), kwargs[:dev])
  @prod = bool_match(env('REPO_PROD'), kwargs[:prod])
  self
end

#style(name, *args) ⇒ Object



297
298
299
300
301
302
303
304
305
# File 'lib/squared/repo/workspace.rb', line 297

def style(name, *args)
  set = ->(k, v) { @styles[k.to_sym] = check_style(v, empty: false) }
  if name.is_a?(Hash)
    name.each { |k, v| set.(k, v || args.flatten) }
  else
    set.(name, args.flatten)
  end
  self
end

#task_defined?(obj, key) ⇒ Boolean

Returns:

  • (Boolean)


369
370
371
# File 'lib/squared/repo/workspace.rb', line 369

def task_defined?(obj, key)
  obj.is_a?(TASK_BASE[key])
end