All files Dependency.js

0% Statements 0/26
0% Branches 0/23
0% Functions 0/10
0% Lines 0/26
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                                                                                                                                                                         
// @flow
 
import DependencyPath from './DependencyPath'
 
const SCOPE_NAME_VERSION_RE = /@(.+)\/(.*)@(.*)/
const SCOPE_NAME_NO_VERSION_RE = /@(.+)\/(.+)/
const NAME_VERSION_RE = /(.*)@(.*)/
 
export default class Dependency {
  name: string
  scope: string
  version: string
 
  constructor (name: string, { scope, version }: Object = {}) {
    this.name = name
    this.scope = scope
    this.version = version
  }
 
  static fromObject (obj: Object) {
    return new Dependency(obj.name, { scope: obj.scope, version: obj.version })
  }
 
  static fromString (str: string) : Dependency {
    if (SCOPE_NAME_VERSION_RE.test(str)) {
      const scopeNameVersion = SCOPE_NAME_VERSION_RE.exec(str)
      return new Dependency(scopeNameVersion[2], {
        scope: scopeNameVersion[1],
        version: scopeNameVersion[3]
      })
    } else if (SCOPE_NAME_NO_VERSION_RE.test(str)) {
      const scopeName = SCOPE_NAME_NO_VERSION_RE.exec(str)
      return new Dependency(scopeName[2], {
        scope: scopeName[1]
      })
    } else if (NAME_VERSION_RE.test(str)) {
      const nameVersion = NAME_VERSION_RE.exec(str)
      return new Dependency(nameVersion[1], {
        version: nameVersion[2]
      })
    } else {
      return new Dependency(str)
    }
  }
 
  get path () : DependencyPath {
    return DependencyPath.fromString(this.toString())
  }
 
  static fromPath (path: DependencyPath) : Dependency {
    if (path.isAFileSystemPath || path.isAGitPath) {
      throw new Error('fromPath. File path or Git Path not yet supported')
    }
    return Dependency.fromString(path.toString())
  }
 
  static same (depA: Dependency, depB: Dependency, {
    ignoreVersion = false
  } : {
    ignoreVersion?: boolean
  } = {}) : boolean {
    return (depA.name === depB.name) &&
        (depA.scope === depB.scope) &&
        (ignoreVersion || (depA.version === depB.version))
  }
 
  get isVersioned () : boolean {
    return this.version !== undefined
  }
 
  get scopedName () : string {
    return this.scope ? `@${this.scope}/${this.name}` : this.name
  }
 
  withoutVersion () : Dependency {
    return new Dependency(this.name, { scope: this.scope })
  }
 
  toString () : string {
    return `${this.scope ? `@${this.scope}/` : ''}` +
          `${this.name}` +
          `${this.version ? `@${this.version}` : ''}`
  }
}