summaryrefslogtreecommitdiff
path: root/app/assets/javascripts/new_branch_form.js.coffee
blob: 4b350854f7855d438dc3a06d6c5ce202c9ed91af (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
class @NewBranchForm
  constructor: (form, availableRefs) ->
    @branchNameError = form.find('.js-branch-name-error')
    @name = form.find('.js-branch-name')
    @ref  = form.find('#ref')

    @setupAvailableRefs(availableRefs)
    @setupRestrictions()
    @addBinding()
    @init()

  addBinding: ->
    @name.on 'blur', @validate

  init: ->
    @name.trigger 'blur' if @name.val().length > 0

  setupAvailableRefs: (availableRefs) ->
    @ref.autocomplete
      source: availableRefs,
      minLength: 1

  setupRestrictions: ->
    startsWith = {
      pattern: /^(\/|\.)/g,
      prefix: "can't start with",
      conjunction: "or"
    }

    endsWith = {
      pattern: /(\/|\.|\.lock)$/g,
      prefix: "can't end in",
      conjunction: "or"
    }

    invalid = {
      pattern: /(\s|~|\^|:|\?|\*|\[|\\|\.\.|@\{|\/{2,}){1}/g
      prefix: "can't contain",
      conjunction: ", "
    }

    single = {
      pattern: /^@+$/g
      prefix: "can't be",
      conjunction: "or"
    }

    @restrictions = [startsWith, invalid, endsWith, single]

  validate: =>
    @branchNameError.empty()

    unique = (values, value) ->
      values.push(value) unless value in values
      values

    formatter = (values, restriction) ->
      formatted = values.map (value) ->
        switch
          when /\s/.test value then 'spaces'
          when /\/{2,}/g.test value then 'consecutive slashes'
          else "'#{value}'"

      "#{restriction.prefix} #{formatted.join(restriction.conjunction)}"

    validator = (errors, restriction) =>
      matched = @name.val().match(restriction.pattern)

      if matched
        errors.concat formatter(matched.reduce(unique, []), restriction)
      else
        errors

    errors = @restrictions.reduce validator, []

    if errors.length > 0
      errorMessage = $("<span/>").text(errors.join(', '))
      @branchNameError.append(errorMessage)